Let’s Create a Twitter Bot (Listen and Retweet)

Video Tutorial

Getting Started

A Bot is simply an application you create for doing a specific job on a social platform (Twitter, Facebook, Slack…) let’s say you have a hashtag for your campaign and you need to listen for everything happens on this hashtag.

In this tutorial, we are going to create a very basic twitter bot that will listen for a specific hashtag and grab the latest tweet on that hashtag and retweet it on the user’s account.

Bots use specific platforms API for fetching and submitting data, therefore we need to use Twitter’s API for searching for hashtag tweets and retweet them.

First, create a Twitter App that will allow you access the Twitter’s API through an access token keys that will be generated once you create the application so make sure to copy those keys (Consumer Key/Secret and Access Token Key/Secret) in order to use them later for bot API authentication.

Also, make sure to take a look on the Twitter’s API Reference for more information on the endpoints and the needed parameters for accessing a specific piece of information and for more information to expand your basic bot.

We will use VSCode as the editor and Nodejs for a javascript engine since bots run on the server so that makes it a bit easier for you to use.

Bot Authentication

First, let’s install twit module that will do the scary things for us and authenticate us with the API.

npm install twit --save

For authenticating with the server we need the keys from the application that we have created on the twitter’s platform (Cosumer_Key, Cosumer_Secret, Access_Token, Access_Token_Secret).

Create Config.js on the same directory as twbot,js (the main bot app).

//Config Object 
let config = {
    consumer_key: "key",
    consumer_secret: "key",
    access_token: "key",
    access_token_secret: "key"
};
//Export the Config to access from the main bot app.
module.exports = config;

Use the configuration to authenticate.

let Twit = require("twit");

//Create an Instance of Twitter API and Authenticate using App Keys 
let T = new Twit(require("./config"));

Now your bot is ready to send and receive requests from the Twitter’s API.

Listen/Search for Hashtag

Now we need from out bot to search for recent tweets on a specific hashtag and therefore we need to hit the search/tweets API endpoint with the query in order to get the tweets array so we can then retweet it.

For the query that we going to send the server is composed into three parts the hashtag name, count of tweets and the type of the result (Recent or Popular).

//Our Search Object 
let searchHashtag = { q: "#coding", count: 1, result_type: "recent" };
//We will use #coding hashtag just because we like coding :)
//The main function to search and retweet
function retweet() {
   //Send a GET Request to search/tweets inorder to get the tweets with the Query 
   T.get("search/tweets", searchHashtag, (err, data) => {
           //Check for any errors 
           if (err) {
               console.log("Cannot Grab Latest Tweet On Hashtag: ", searchHashtag.q);
               return; ///< exit function
           }
           console.log("Data: ", data); ///< Quick Test
    }
}

Now if you tried to run the above function then you would get a list of recent tweets on the #coding hashtag console logged for you and therefore you can make sure that everything is working fine with your bot and now you can retweet the most recent tweet on your twitter profile.

Retweet #hashtag tweets

Retweeting means that you are going to create something, therefore, we need to submit a post request with our tweet and to tell twitter which tweet to retweet we simply give him the tweet ID that we have got by searching the hashtag, simple.

...
//Make sure that the Data is valid 
if (data && data.statuses.length > 0) {
    //Tweets are on an array on the searched object (data.statuses)
    let tweet = data.statuses[0];
    //We want to retweet only one tweet so we access the first one (0 index)
    console.log(tweet); ///< LOG IT 
    //Retweet using the tweet's ID 
    T.post("statuses/retweet/" + tweet.id_str, (e, res) => {
        //Any Errors?
        if (e) {
            console.log("Cannot Retweet your Tweet!");
            return;
        }
        //Success
        if (res) {
            console.log("Success, Check your Account for the Retweet!");
        }
    });
} else {
    //Empty Statuses Array (Hashtag has no tweets!)
    console.log("No Tweets on the Hashtag: ", searchHashtag.q);
}
...

The object that we get from the search has the tweets on an array under the statuses attribute and since we want to retweet only one tweet (you still can retweet all of them using a for loop) therefore we send a post request to the statuses/retweet/:id endpoint and we need to concatenate the tweet’s id in order to know which one to retweet on our profile.

We get a response after the post request has been completed either success or there was an error when trying to retweet we just want to console log it for making it more user-friendly.

Keep the Bot Alive

Bots are generally created for doing the same function over and over again so it would make easier for us. So we want from our bot to run each hour and search for the recent tweet on the hashtag if there is any then retweet.

//Use SetInterval function for running the retweet function each hour 
setInterval(retweet, 3600 * 1000); 
//Hour = 3600 second and each second has 1000 ms => 3600 * 1000 ms

What’s Next

Now you have a working bot prototype, you can expand it by adding more functionalities for ex: replying to messages or getting trending tweets.

There are a plenty of things you can do with the Twitter’s API right out of the box.

No Comments Yet