Learn to create and host X (Twitter) bot on Square Cloud. Complete tutorial with configuration, deployment, and practical examples in Node.js and Python.
To develop and host on Square Cloud, it’s essential to follow a structured sequence of configurations and prerequisites. This technical guide will cover the entire process, from initial setup to production deployment.
Square Cloud Account: Register through the signup page using your email.
Active Paid Plan: Ensures dedicated resources and optimized performance for your application. Check our available plans and choose the most suitable for your needs.
An active X (Twitter) account is required for authentication and bot operation. If you don’t have an account, sign up at the official X website.
A X Developer account is also required to access the APIs. Request access through the X Developer Portal.
Create the main file: Develop the index.js file with the bot’s base structure:
index.js
// Import necessary modulesconst { TwitterApi } = require('twitter-api-v2');// Configure Twitter client with authenticationconst client = new TwitterApi({ appKey: process.env.API_KEY, appSecret: process.env.API_SECRET_KEY, accessToken: process.env.ACCESS_TOKEN, accessSecret: process.env.ACCESS_TOKEN_SECRET,});// Client with read and write permissionsconst rwClient = client.readWrite;// Function to check if the bot is workingasync function verifyBot() { try { // Get authenticated user information const user = await rwClient.currentUser(); console.log(`Bot successfully initialized! User: @${user.screen_name}`); return true; } catch (error) { console.error('Error verifying bot:', error); return false; }}// Function to post a tweetasync function postTweet(text) { try { const tweet = await rwClient.tweet(text); console.log(`Tweet posted successfully! ID: ${tweet.data.id}`); return tweet; } catch (error) { console.error('Error posting tweet:', error); throw error; }}// Function to respond to mentionsasync function respondToMentions() { try { // Fetch recent mentions const mentions = await rwClient.userMentionTimeline({ count: 10, result_type: 'recent' }); for (const tweet of mentions.data) { // Check if it's a new mention (implement control logic) if (tweet.text.includes('!ping')) { // Reply to the mention await rwClient.reply( 'Pong! 🤖 X Bot working correctly!', tweet.id ); console.log(`Replied to mention from @${tweet.user.screen_name}`); } } } catch (error) { console.error('Error processing mentions:', error); }}// Function to search and interact with specific tweetsasync function searchAndInteract(query) { try { // Search tweets with a specific query const tweets = await rwClient.search(query, { count: 5, result_type: 'recent' }); for (const tweet of tweets.statuses) { // Like the tweet await rwClient.like(tweet.id_str); console.log(`Liked tweet from @${tweet.user.screen_name}`); // Wait a bit between actions to avoid rate limiting await new Promise(resolve => setTimeout(resolve, 2000)); } } catch (error) { console.error('Error searching and interacting:', error); }}// Main bot functionasync function runBot() { console.log('Starting X bot...'); // Check if the bot is configured correctly const botOk = await verifyBot(); if (!botOk) { console.error('Bot initialization failed'); return; } // Example: Post an initialization tweet try { await postTweet('🤖 X Bot initialized and running on Square Cloud!'); } catch (error) { console.log('Initialization tweet failed, but bot continues running'); } // Main bot loop setInterval(async () => { try { // Check and respond to mentions every 5 minutes await respondToMentions(); // Example: Search and interact with tweets about a specific topic // await searchAndInteract('#SquareCloud'); } catch (error) { console.error('Error in main loop:', error); } }, 5 * 60 * 1000); // 5 minutes console.log('Bot running. Press Ctrl+C to stop.');}// Signal handling for graceful shutdownprocess.on('SIGINT', () => { console.log('\nShutting down X bot...'); process.exit(0);});process.on('SIGTERM', () => { console.log('\nShutting down X bot...'); process.exit(0);});// Initialize the botrunBot();
After preparing your project files, you can now upload them to Square Cloud and host your project.
To do so, create a ZIP file containing all your project files.
Environment Variables
Security: Never include your API credentials directly in code. Always use environment variables on Square Cloud.
On Square Cloud, configure the following environment variables via the control panel:
Access the upload page and upload your project zip file.
2
Configure Your Environment
After uploading your zip, you will need to configure the name, main file or runtime environment and other settings for your project.
If you are uploading a web project, make sure to select “Web Publication” and set a subdomain to your project.
3
Deploy Your Project
Finally, click on the “Deploy” button to host your project on Square Cloud.
After deployment, you can monitor your project’s status and logs from the dashboard.
To use this method, you need to create a config file named squarecloud.app in the root directory of your project. This file will contain the necessary configuration for your project.
Learn more about: how to create the configuration file for Square Cloud.
The squarecloud.app file is a configuration file that will be used to configure your application; it will be used to define your environment.
1
Install the CLI
First, you need to have the CLI installed in your environment. If you don’t have it yet, run the following command in your terminal:
npm install -g @squarecloud/cli
If you already have it, we recommend updating it. To do this, run the following command in your terminal:
Now, to authenticate and use other CLI commands, you will find your authorization key here by clicking on “Request API Key”. After obtaining your authorization key, run the following command:
squarecloud auth login
3
Upload Your Project
Finally, to deploy your application to Square Cloud using the CLI, you need to run the following command:
To deepen your knowledge about developing X bots using twitter-api-v2, check the official twitter-api-v2 library documentation. The documentation provides detailed guides, advanced tutorials and full API references to maximize your implementation.Also see:
// Function to monitor specific hashtagsasync function monitorHashtags(hashtags) { for (const hashtag of hashtags) { try { const tweets = await rwClient.search(`#${hashtag}`, { count: 5, result_type: 'recent' }); // Process found tweets for (const tweet of tweets.statuses) { console.log(`Tweet found with #${hashtag}: ${tweet.text}`); // Implement interaction logic } } catch (error) { console.error(`Error monitoring #${hashtag}:`, error); } }}
// Function to schedule postsfunction schedulePost(text, delay) { setTimeout(async () => { try { await postTweet(text); console.log('Scheduled post published successfully!'); } catch (error) { console.error('Error publishing scheduled post:', error); } }, delay);}// Example: Schedule a post for 1 hourschedulePost('🤖 Scheduled post by the bot!', 60 * 60 * 1000);
If you continue facing technical difficulties, our specialized support team is available to assist you. Contact us and we’ll be happy to help you resolve any issue.