Twitter Bot Tutorial – Retweet & Tweet With NodeJS Locally

I finally got round to creating my own Twitter robot, something I’ve wanted to do for a good few months now. I successfully created one, and it’s actually brilliant. So, consequently, I decided to share exactly how I did it, so you can have one too! In this first part, I will explain how to set-up a Twitter bot locally on your computer, and in a later one, on a server, remotely.

A few things to do before we start

The downside to this tutorial for most of you reading is the very first thing you will need to do, it may take a while for the application to be processed. Meaning, you pretty much can’t complete this tutorial until you’ve got your developer account. But, the great thing is, this article isn’t going anywhere. So let’s go through the prerequisites

  1. Apply for a Twitter Developers Account and wait for approval (This could take up to a couple of weeks)
  2. Download NodeJsNote: for this tutorial, version 8.12.0 was used.
  3. Have an IDE handy, something like VS Code will be sufficient.

Setting Up

Creating A Twitter App & Getting API Credentials

Once you have your developer account activated, you will need to create an App. This, when completed will give you the API credentials required to use Twitters API.

You will need to fill out the following details –

  • App Name
  • App Description (Simply describe that you are building an app for Twitter Bot/Automation purposes.
  • Website URL (This is required)
  • Callback URL – Use your website URL again.
  • Privacy & Terms URL – Specify the URL to your own websites privacy policy.
  • Organization Website – Fill our the same URL for your website again.
  • Hit the create button
  • Within the App interface, click the Keys & Tokens tab.
  • You will be able to see the Consumer API Keys already generated.
  • In the next section Access token & access token secret click the create button to generate them.
  • Done!

Setting Up The Project

Ok, so now we’ve got the prerequisites out of the way, we can start to build our bot.

  1. Create a folder in a directory of your choice, name it something memorable like TwitterBot.
  2. Start up your CLI, in my case it’s the Windows Command Prompt.
  3. Use the cd command and navigate the folder you just created. For example: cd C:\TwitterBot
  4. Type npm init and hit that enter button!
  5. Fill out all of the details that are asked about the new project, or you can hit enter for every single question if you live life on the edge.
  6. Now, enter the following command npm install twit, this will install a very helpful package to aid using the Twitter API.

Take a peek inside the project folder, there should be a node_modules folder and a package.json file. If not, go through the last 6 steps again,

Bot Creation & Configuration

Now it’s time for the fun part, development of the Twitter bot itself.

Step 1

Create a new JavaScript file in the root of your project directory. Name it something like bot.js.

Step 2

Now, we need to require the functionality of the Twit package we installed earlier with NPM. To do this, make sure the following code is at the top of the new bot.js file.

var twit = require("twit");

Step 3

Let’s set up an instance of the Twit helper, add the following code, filling out all your API credentials from your developer account.

var Twitter = new twit({
    consumer_key: 'xxxxxxxxxxxx',
    consumer_secret: 'xxxxxxxxxx',
    access_token: 'xxxxxxxxxxxxx',
    access_token_secret: 'xxxxxxxxxxxx',
    timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
    strictSSL: true, // optional - requires SSL certificates to be valid.
})

This beautiful object will now have access to many helpful functions for your disposal. The first one we can try is posting a simple tweet to your account.

Post A Tweet

Let’s add the following code to prepare for posting a tweet to your Twitter account –

Twitter.post('statuses/update', { status: 'Hello World, Of Course!' }, function(err, data, response) {
    console.log(data)
  });

Time to run the robot and post to your account! If you’ve used Node before you’ll know what to do, but if not, following these steps

  1. Open your Command Prompt.
  2. Navigate to the project directory, eg: cd C:\TwitterBot
  3. Run the following command node bot.js or node whatever-you-named-your-file
  4. You should see a JSON response returned in your CLI. Something like the following –
{ created_at: 'Sat Sep 22 19:22:00 +0000 2018',
  id: 1043581196431765500,
  id_str: '1043581196431765509',
  text: 'Hello World, Of Course!',
...................

Go check your Twitter profile page and see the tweet! You did it, your very first robotic tweet!

Automated Retweet

Either remove the Twitter.post code or simply comment it out for now. Then go ahead and add the following code to prepare for retweeting tweets.

var retweet = function () {
    var params = {
        q: '#100DaysOfCode, #301DaysOfCode, #JavaScript, #PHP, #NodeJs', // Hashtags to search tweets within
        result_type: 'recent',
        lang: 'en'
    }
    Twitter.get('search/tweets', params, function (err, data) {
        if (!err) {
                var retweetId = data.statuses[0].id_str;
                Twitter.post('statuses/retweet/:id', {
                    id: retweetId
                }, function (err, response) {
                    if (response) {
                        console.log('Retweeted!!!');
                    }
                    if (err) {
                          console.log(err);
                        console.log('Problem when retweeting. Possibly already retweeted this tweet!');
                    }
                });
        }
        else {
            console.log('Error during tweet search call');
        }
    });
};

A couple of notable points about the above code are as follows –

  • The q param essentially means query strings, which hashtags do you want the API call to return tweets from. As you can see, you can have a list of different hashtags you are interested in retweeting too.
  • Result Type has 3 options to use; recent, popular and mixed. These have their obvious meaning, but for the popular tag, I am not sure what the API gauges as popular exactly. Is it something with 500+ retweets or something with 1000+ favorites. To be safe, use the recent option.

Time to add the final piece of code, the function call itself. Add the following code to the bottom of the file –

retweet();

Let’s run and automate a retweet.

  1. Open your Command Prompt.
  2. Navigate to the project directory, eg: cd C:\TwitterBot
  3. Run the following command node bot.js or node whatever-you-named-your-file

If all is well, you will see ‘Retweeted!!!’ returned to the terminal. If not, you will see one of the errors messages in the terminal and it’s time to dig deeper with the err variable.

Retweeting Tweets That Have A Certain Criteria

The great thing about searching for tweets in the Twitter API, is that it returns a lot of helpful data about each tweet. Meaning you could add further complexity to your functions quite easily. The following screenshot shows what data is returned for each tweet.

tweet search response

One of the commonly used values is retweet_count, this would enable to only retweet tweet’s that have had a certain number of retweets already. That being said, here’s how to only retweet tweets that have already had more than ten retweets already, notice the additional if statement

var retweet = function () {
    var params = {
        q: '#100DaysOfCode, #301DaysOfCode, #JavaScript, #PHP, #NodeJs', // Hashtags to search tweets within
        result_type: 'recent',
        lang: 'en'
    }
    Twitter.get('search/tweets', params, function (err, data) {
        if (!err) {

            if (data.statuses[0].retweet_count > 10) { // If tweet has more than ten RT's

                var retweetId = data.statuses[0].id_str;
                Twitter.post('statuses/retweet/:id', {
                    id: retweetId
                }, function (err, response) {
                    if (response) {
                        console.log('Retweeted!!!');
                    }
                    if (err) {
                          console.log(err);
                        console.log('Problem when retweeting. Possibly already retweeted this tweet!');
                    }
                });
            }
        }
        else {
            console.log('Error during tweet search call');
        }
    });
};

That is one example of how the data is quite valuable when being searched, there are lot of ways to filter tweets down to only interact with specific interests.

Summary

In this article you will lay the ground-work with some simple automation Twitter bot actions. Consequently, this will open doors for much more advanced functionality. But, this all depends on what you are trying to achieve exactly. In the next article, I will be explaining how to get a Twitter bot ‘online’ so it can run continuously without you having to execute functions at the terminal. Have fun!

Interesting Links

 

Twitter Bot Tutorial – Retweet & Tweet With NodeJS Locally

You May Also Like

Leave a Reply

Your email address will not be published.