DEV Community

Sarah Williams
Sarah Williams

Posted on

BEEP BOOP! How to make a Twitter Bot (Part 2)

Hey there! This is Part Two of how to build a Twitter bot. If you missed Part One, be sure to go back and read that first as it has important information. If you already read it and have your access keys, then you are ready for the next steps!

Today we are going to build out the bot and test it in our dev environment. Like I said in the previous post, the bot can be built using Node or Python. Today, we are going to use Node.

Couple of notes to make:

*I used various tutorials, so these are basically modified steps I used to get it working.

*These steps assume that you already have a dev environment in place.

Okay, let's get started!

Step 1: Install Node

If you used npm before you should already have Node installed as they come together. To check, type this in the terminal:

node -v

If you see a version number then you can skip to the next step. If you get an error message, you can continue these steps to install Node.

Click here to download the Node package and install it on your computer. Once installed, verify the installation by typing the above command again.

Step 2: Configure files and Install Twitter

Make a folder. Call it Bot.

From your terminal, cd into the bot folder and run these command:

touch bot.js
touch config.js
touch README.md

What did we do? Just made some files. Keep these open because we'll need them later.

Next, run this command:

npm init

Follow the prompts and fill out the information. It's okay if you don't have all the required info, those can be filled in later. When you're finished, you should see a package.json file in your bot folder. It'll look something like this:


{
  "name": "bottest",
  "version": "1.0.0",
  "description": "Twitter bot",
  "main": "bot.js",
  "dependencies": {
    "twitter": "^1.7.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "test"
  },
  "author": "Sarah Williams",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

Under "scripts" add this:

"start": "node bot.js"
Enter fullscreen mode Exit fullscreen mode

This tells your JSON the default command for running your bot.

Next you'll need to install Twitter. To install it, type this in your terminal:

npm install --save twitter

This will not only install twitter, but it will also add the dependency to you json files so you don't have to do it.

Optional Step: Make a GitHub repo

Now if you want to deploy to GitHub then you can make a repo in GitHub and run git init. Just be very careful that you do not deploy config.js while the access keys are still saved in the file. Even if you overwrite the files, the old version will still be saved unless you make new keys or delete the repo. I did not setup my GitHub until I deployed to Heroku for this reason. I'll actually go into the GitHub steps more in Part 3.

Step 3: Add Access Keys to config.js file

Add this to your config.js file:

module.exports = {
    consumer_key:'ACCESS_KEY_HERE',  
    consumer_secret:'ACCESS_KEY_HERE',
    access_token_key:'ACCESS_KEY_HERE',  
    access_token_secret:'ACCESS_KEY_HERE'
  }
Enter fullscreen mode Exit fullscreen mode

We're just testing the bot, so for now, we're going to add the keys to the config file. When we get ready to deploy the files, we're going to remove these, so be sure to back up them up in a text file.

In the ACCESS_KEY_HERE, copy your API keys you created from Twitter and replace the text in the space. Don't forget to hit save.

Step 4: Setup Bot.js

Go into your bot.js file and add this code:


var Twitter = require('twitter');
var config = require('./config.js');
var Tweet = new Twitter(config);
Enter fullscreen mode Exit fullscreen mode

This code is just the files required to help our bot run.

Next, we need to add search parameters. This will tell our bot what tweets to search for.

Add this section:

var params = {
      q: '#battlestation',
      count: 10,
      result_type: 'recent',
      lang: 'en'    
    } 
Enter fullscreen mode Exit fullscreen mode

Neat! We're telling the search parameters (var params) to search for tweets tagged with #battlestation, keep the search count to 10, only pull the most recent tweets and pull them in English.

**Note: it's best practice to keep the search count number to 10 or under. This prevents spam abuse with your Twitter account, hitting the retweet limit too quickly, and getting your account suspended.

But what if we want to add more hashtags? I think I want to add #pcbuilds and #cooltechoftheday to the query as well. Let's modify the search query:

var params = {
      q: '#battlestation OR #pcbuild OR #cooltechoftheday',
      count: 10,
      result_type: 'recent',
      lang: 'en'    
    } 
Enter fullscreen mode Exit fullscreen mode

Now, our search query knows to pull tweets that have at least one of those hashtags in them

TIP: If you need help on getting your search parameters set correctly, do an advanced search on Twitter. When your search results come up, you'll see the actual query that twitter used to pull your tweets and can use them in the query. It'll look like this:

Alt Text

You can then copy and paste those parameters into you bot.js file.

For more information on search parameters, click here.

Next, let's tell our bot to retweet the tweets it's searching. Add this code to your section:

Tweet.get('search/tweets', params, function(err, data, response) {
    if(!err){
        for(let i = 0; i < data.statuses.length; i++){
            let id = { id: data.statuses[i].id_str }
            Tweet.post('statuses/retweet', id, function(err, response){
              if(err){
                console.log(err[0].message);
              }
              else{
                let username = response.user.screen_name;
                let tweetId = response.id_str;
                console.log('Retweeted: ', `https://twitter.com/${username}/status/${tweetId}`)
              }
            });
          }
    } else {
      console.log(err);
    }
  })
Enter fullscreen mode Exit fullscreen mode

The next steps are using the tweets from the search results and retweet them to our Twitter account. The last part outputs results whether it was able to retweet it. If it's already been tweeted, it will tell us. If it's a new tweet, it will retweet it and tell us the link where it was retweeted.

Altogether, your code should look something like this:


var Twitter = require('twitter');
var config = require('./config.js');
var Tweet = new Twitter(config);


    var params = {
      q: '#battlestation OR #pcbuild OR #cooltechoftheday',
      count: 10,
      result_type: 'recent',
      lang: 'en'    
    } 

Tweet.get('search/tweets', params, function(err, data, response) {
    if(!err){
        for(let i = 0; i < data.statuses.length; i++){
            let id = { id: data.statuses[i].id_str }
            Tweet.post('statuses/retweet', id, function(err, response){
              if(err){
                console.log(err[0].message);
              }
              else{
                let username = response.user.screen_name;
                let tweetId = response.id_str;
                console.log('Retweeted: ', `https://twitter.com/${username}/status/${tweetId}`)
              }
            });
          }
    } else {
      console.log(err);
    }
  })
Enter fullscreen mode Exit fullscreen mode

Step 6: Test it Out!

Now that you have your files all setup, it's time to put it to the test! Go ahead and run this command in your terminal:

node bot.js

Your terminal should start outputting the results. If you see "Retweeted" with a link multiple times, that means it's working! To verify, go to your Twitter profile and refresh the page. You should see the tweets come up.

Awesome, our bot is alive! But we want to automate this bot so that it always retweeting (That's the whole point right?)

In our third and final part of the series, I'll show you how to get your bot up and running in Heroku!

In the meantime, you can check my GitHub repo below! Also, you can see both my bots in action on Twitter @cooltechrobot and @whosehiringbot

Top comments (5)

Collapse
 
stanjdev profile image
stanjdev

Does anyone know why I keep getting this error in terminal after I followed all the steps and entered node bot.js ?

console.log(err[0].message);
                                   ^

TypeError: Cannot read property 'message' of undefined
Enter fullscreen mode Exit fullscreen mode

I have followed 3 other tutorials that were very similar to this, and I followed this one because it was made most recently (2019).

Any idea what could be wrong? I even copied and pasted it entirely, installed the twitter dependency, and my keys and secret keys are recent.

Collapse
 
maawais profile image
maawais • Edited

Replace error block with this:

if(err){
console.log('Error:- ', err.message);
}

You will get the exact error message.

Collapse
 
yanant profile image
yanant

Hey Sarah! Great tutorial series you've put together here :)

Do you know how I can stop the bot from retweeting duplicate values?

Collapse
 
tjcola0 profile image
TJCola

i installed node but when I type node -v it says 'node' is not recognized as an internal or external command.

Collapse
 
yanant profile image
yanant

That's odd. Do you remember which command you used to install it?