DEV Community

Sachin Sarawgi
Sachin Sarawgi

Posted on

Twitter Bot Using NodeJS, Step By Step Guide To Develop

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

Setting up the project

  • Download and Install NodeJS from here.
  • 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.

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
  • 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.

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.

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.

For more on Search API.

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.

For more on Retweet API.

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.

Updated code can be found here on GitHub. 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
  • 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, 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
._

Oldest comments (0)