Twitter Bot Using NodeJS, Step By Step Guide To Develop
Tags: javascript, beginners, node, webdev
Published: 2020-06-17 04:26:32

<link rel="canonical" href="[https://medium.com/@codesprintpro/twitter-bot-using-nodejs-c72a2a50628d](https://medium.com/@codesprintpro/twitter-bot-using-nodejs-c72a2a50628d)"/>

_We will build from scratch a Twitter Bot using NodeJS which will Retweet._

In this blog, we will understand how to build a Twiter bot that will retweet every time a tweet related to #100DaysOfCode is twitter using NodeJS.

It’s better to set up a new Twitter account where we can put any random thing. Once done with the final version of the bot we can deploy it to our main Twitter account.

### Topics Covered

- Setting up the Project
- Setting up config details
- Search tweet using Twitter Search Tweet API
- Retweet using Twitter POST Tweet API
- Combine Search & Post Twitter API
- Deploy the app on Heroku
- Enhancement to the code

![](https://cdn-images-1.medium.com/max/1024/1*pJmPwLeNEb6PeoA1hfh8UA.jpeg)

#### Setting up the project

- Download and Install NodeJS from [here](https://nodejs.org/en/download/).
- Create a separate directory from your command line mkdir twitterbot.
- Go inside the directory cd twitterbot
- Setup the project files usingnpm init , fill the proper details. This will create a package.json file.
- Install twit node package npm install twit --save . Extra attribute _save_ will save the package name in a list of dependencies in package.json file.
- Create a js file where you will write code, the file name should be the same as which you gave while mentioning the _main file_ detail in npm init.

That’s all for now to set up the project. Open the project in your favorite editor.

twit package will hide many of the boilerplate code for us. We just need to worry about the Twitter APIs.

#### Setting up config details

- Open the main file in your editor. Let’s say the file name is _twitterbot.js_.
- Import _twit_ module which is present inside the _twit package_ which we downloaded in our previous step let twit = require('twit'); .

Create a twit object with config details.

{% gist https://gist.github.com/codesprintpro/04cdd317da1bfa45d9229974021373e8 %}

For getting all the above details we need to create an app on Twitter. From there we will get above four details.

- Sign in to your Twitter account.
- Go to [https://developer.twitter.com/en/apps](https://developer.twitter.com/en/apps)
- Make sure we have our phone number associated with the account we logged in.
- Click on Create an App.
- Give a unique App Name, fill _Application description_, _Website URL,_ and _Tell us how this app will be used _fields.
- Click on Create. Our app has been created.
- Go to _Key and tokens_ tab copy Consumer API key and Consumer API Secret key. Fill it in our _twitterbot.js_ file.
- Click on _Generate Access token & access token secret,_ copy _Access token,_ and _Access token secret_. Fill it in our _twitterbot.js_ file.

Run your file _twitterbot.js_ to see if the code we have written is correct or not. Though nothing dynamic happening here.

#### Search tweet using Twitter Search Tweet API

We will use the _get_ method exposed by the twit package. It takes the twitter search API and optional parameters, callback function as input. T.get('search/tweets', [params], [callback]);

The second optional argument has search query details. Suppose we want to search for Tweet having #100DaysOfCode as a hashtag, also we want to fetch 10 results at a time. For date, we will hard code it for now for some date.

{% gist https://gist.github.com/codesprintpro/7870fe129769dac861d1031ae27b8a05 %}

The q key will have the text for which we want to search and the date from which the tweet should be searched. Right now the date is hardcoded, count tells upper bound of how many tweets should be given as a result.

Now we need a function which will be called as a callback. Suppose for now we want to log the tweet message whenever we get a result of the search tweet.

{% gist https://gist.github.com/codesprintpro/85370422d52f42a651b24b9459f6e208 %}

data.statuses will give us the array of tweets that it found based on the query parameter. tweetMsgs[i].textwill give the text message of each tweet.

Final code for search tweet after callback function.

{% gist https://gist.github.com/codesprintpro/7e26a17b80cb51d63b477f486a47b086 %}

For more on [Search API](https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets).

#### Retweet using Twitter POST Tweet API

We will use the _post_ method exposed by the twit package. It takes the twitter search API and optional parameters, callback function as input. T.get('statuses/retweet/:id', {id: tweetid}, [callback]).

The API _id_ key has the value of the _id\_str_ (it is a field inside the tweet JSON which we want to retweet). Suppose _tweetMsg_ variable is a JSON value of a tweet.

```
T.post('statuses/retweet/:id', { id: tweetMsg.id\_str });
```

tweetMsg.id\_str will give the value from JSON.

Now we need a function which will be called as a callback. Suppose for now we will log if the tweet was successful or not.

{% gist https://gist.github.com/codesprintpro/42d34b25e096c6f1b5b00292e7715fdd %}

For more on [Retweet API](https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweets-id).

#### Combine Search & Post Twitter API

Now let us combine the search and post Twitter API. We will retweet each of the tweets present inside the search result.

{% gist https://gist.github.com/codesprintpro/d4eddc957dae647af7d210f881faa30d %}

> Updated code can be found [here on GitHub](https://github.com/codesprintpro/twitterbot). Remember to put config details for Twit object. Added function to give the date in real-time. setTimeout method is used to retweet in some interval.

#### Deploy the app on Heroku

We will be using Heroku to deploy our twitter bot.

- Register in Heroku online
- Create an App in the Heroku dashboard online

Local Machine Setup

- Install Heroku [https://devcenter.heroku.com/articles/heroku-cli](https://devcenter.heroku.com/articles/heroku-cli)
- Go inside the project folder and execute git init
- Then bind the project with Heroku remote by executing heroku git:remote -a {appname} . appname is the app name in Heroku.
- Execute the following commands to push code and run remotely
- git add .
- git commit -m “message"
- git push heroku master This will start executing out a bot on Heroku.
- heroku logs to check logs of the app on the server.

#### Enhancement to the code

- We can add a function that will give us a date in real-time so that we don’t have to hard code the date, which tells from which date we want the read the Tweet.
- Instead of directly retweet we can add a delay to our tweets so that not all are getting tweeted at the same time. We can use setTimeout for that.

I hope this blog will help you to understand how a simple Twitter Bot can be designed using NodeJS.

Updated code can be found [here on GitHub](https://github.com/codesprintpro/twitterbot), added code for making a tweet as favorite. Remember to put config details for Twit object. Added function to give the date in real-time.

_If you enjoyed reading this, don’t forget the like. 👏  
Thank you. Follow me on _ [_Twitter_](https://twitter.com/SachinSarawgi)_._