BEEP BOOP! How to make a Twitter Bot (Part 2)
Tags: twitter, node, bot, javascript
Published: 2019-10-30 14:14:13

---
title: BEEP BOOP! How to make a Twitter Bot (Part 2)
published: true
description: 
tags: twitter, node, bot, javascript
---

Hey there! This is Part Two of how to build a Twitter bot. If you <a href="https://dev.to/nerdyandnatural/beep-boop-how-to-make-a-twitter-bot-part-1-4nhm" target="_blank">missed Part One</a>, 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!

<h3>Step 1: Install Node</h3>

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.

<a href="https://nodejs.org/en/download/" target="_blank">Click here</a> to download the Node package and install it on your computer. Once installed, verify the installation by typing the above command again.

<h3>Step 2: Configure files and Install Twitter</h3>

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:

```javascript

{
  "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"
}
```

Under "scripts" add this:

```javascript
"start": "node bot.js"
```

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.

<h4>Optional Step: Make a GitHub repo</h4>

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.

<h3>Step 3: Add Access Keys to config.js file</h3>

Add this to your config.js file:

```javascript
module.exports = {
    consumer_key:'ACCESS_KEY_HERE',  
    consumer_secret:'ACCESS_KEY_HERE',
    access_token_key:'ACCESS_KEY_HERE',  
    access_token_secret:'ACCESS_KEY_HERE'
  }
```
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.

<h3>Step 4: Setup Bot.js</h3>

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

```javascript

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

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:

```javascript
var params = {
      q: '#battlestation',
      count: 10,
      result_type: 'recent',
      lang: 'en'    
    } 
```

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: 

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

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](https://thepracticaldev.s3.amazonaws.com/i/vw4ucmz8gybsjzafrrem.PNG)

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

For more information on search parameters, <a href="https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets" target="_blank">click here.</a>

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

```javascript
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);
    }
  })
```

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:

```javascript

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);
    }
  })
```


<h3>Step 6: Test it Out!</h3>

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 <a href="https://twitter.com/cooltechrobot" target="_blank">@cooltechrobot</a> and <a href="https://twitter.com/whosehiringbot" target="_blank">@whosehiringbot</a>

{% github nerdyandnatural/twitter-bot no-readme%}