Create a Simple Twitter Bot with Node.js

2016-11-23

How about a Twitter Bot that retweets, favorites, on the basis of hashtags and replies to other users if they follow it? I made a similar kind of a Twitter Bot (@nodejstweet) that feeds me the latest or the ongoing news/articles/how-to’s on a set of hashtags such as #Nodejs, #MongoDB, #AngularJS, #IonicFramework, et cetera. At the time I never expected it having more followers than me but that has been surpassed.

A glimpse of a Twitter Bot that I made for sole purpose of information

What this bot will do?

This is a simple Twitter bot and will retweet, favorite/like randomly on the basis of hashtags as a query that we will use and continue to do so after a certain period of time interval.

What you need?

  • You must have Node.js installed on your system.
  • A Twitter Account.
  • Your bot will be using twit which is an npm module to manipulate tweets and streams, and to communicate with the Twitter API.

Let’s Start

Setup an empty directory and initialise it with:$ npm init to configure this web application with package.json file. Then create two new files: bot.js & config.js in that directory.

bot.js will be our main app file in which we will be writing the source code of our Twitter Bot, and so in package.json edit the main field to:

1{
2 "main": "bot.js"
3}

Your current directory structure should look like this:

1root/project-name
2|- bot.js
3|- config.js
4|- package.json

Configuring and granting permissions from Twitter API

After logging to to your Twitter account, follow to this link: https://apps.twitter.com/app/new to create a new application. Fill out the necessary fields in the form click on the button Create Your Twitter Application. After creating the application, look for Keys and Access Tokens under the nav-panes and click on Generate Token Actions\ and then copy:

  • Consumer Key
  • Consumer Secret
  • Access Token
  • Access Token Secret

Open the config.js file and paste all four values inside it. Expose those values using module.export:

1//config.js
2/\*\* TWITTER APP CONFIGURATION
3 \* consumer\_key
4 \* consumer\_secret
5 \* access\_token
6 \* access\_token\_secret
7 \*/
8
9module.exports = {
10 consumer\_key: '',
11 consumer\_secret: '',
12 access\_token: '',
13 access\_token\_secret: ''
14}

Now, the Twitter bot’s configuration is step is complete. Please note, for every different application, the consumer key, consumer secret, access_token and access_token_secret will differ.

Building the bot

Since the configuration step is complete, now let’s install our third requisite that is Twitter API client for node and will help us to communicate to Twitter API and provide an API for all necessary actions (such as retweet and favorite a tweet).

We will start by installing the dependency we need for our application.

1$ npm install --save twit

After the dependency has finished installing, go to the bot.js file and require the dependency and config.js file.

1var twit = require(’twit’);
2var config = require(./config.js’);

Pass the configuration (consumer and access tokens) of our Twitter application in config.js to twit:

1var Twitter = new twit(config)

So far, so good?

PLEASE NOTE: You must refer to twit documentation for a deep reference.

Retweet Bot

Let’s write a function expression that finds the latest tweets according to the query passed as a parameter. We will initialise a params object that will hold various properties to search a tweet, but most importantly query or q property that will refine our searches. Whatever value you feed in this property, our bot will search the tweets to retweet based on this criteria. You can feed this property values like a twitter handler, to monitor a specific twitter account or a #hashtag. For our example bot, we have find latest tweets on #nodejs.

This is how the functionality of the retweet bot starts:

1var retweet = function() {
2 var params = {
3 q: '#nodejs, #Nodejs',
4 result\_type: 'recent',
5 lang: 'en'
6 }

The other two properties: result_type and lang are optional. On defining the result_type: 'recent' notifies bot to only search for the latest tweets, tweets that have occurred in the time period since our bot has started or it made the last retweet.

There is a list of parameters provided by the Twitter API.

Our next step is to search for the tweets based on our parameters. For this, we will use Twitter.get function provided by twit API to GET any of the REST API endpoints. The REST API endpoint is a reference to the Twitter API endpoint we are going to make a call to search for tweets. The Twitter.get function accepts three arguments: API endpoint, params object (defined by us) and a callback.

1// RETWEET BOT ==========================
2
3// find latest tweet according the query 'q' in params
4var retweet = function() {
5 var params = {
6 q: '#nodejs, #Nodejs', // REQUIRED
7 result_type: 'recent',
8 lang: 'en'
9 }
10 // for more parametes, see: https://dev.twitter.com/rest/reference/get/search/tweets
11
12 Twitter.get('search/tweets', params, function(err, data) {
13 // if there no errors
14 if (!err) {
15 // grab ID of tweet to retweet
16 var retweetId = data.statuses[0].id_str
17 // Tell TWITTER to retweet
18 Twitter.post(
19 'statuses/retweet/:id',
20 {
21 id: retweetId
22 },
23 function(err, response) {
24 if (response) {
25 console.log('Retweeted!!!')
26 }
27 // if there was an error while tweeting
28 if (err) {
29 console.log(
30 'Something went wrong while RETWEETING... Duplication maybe...'
31 )
32 }
33 }
34 )
35 }
36 // if unable to Search a tweet
37 else {
38 console.log('Something went wrong while SEARCHING...')
39 }
40 })
41}

To post or to retweet the tweet our bot has found we use Twitter.post() method to POST any of the REST API endpoints. It also takes the same number of arguments as Twitter.get().

Now to automate this action we defined above, we can use JavaScript’s timer function setInterval() to search and retweet after a specific period of time.

1// grab & retweet as soon as program is running...
2retweet()
3// retweet in every 50 minutes
4setInterval(retweet, 3000000)

Please note that all JavaScript’s Timer functions take the amount of time argument in milliseconds.

Favorite Bot

Similar to retweet bot we can define and initialise another function expression that will search and favorite a tweet randomly. Yes, the difference here is to search and grab the tweet randomly. We will start by creating a parameter object params that will consist of three properties as in retweet() function expression. The bot will search for tweets using the same .get() function provided by twit API to GET any of the Twitter API endpoints. In our case, we need search/tweets. Then we will store the status of the search for tweet to favorite in a variable and in a another variable we will apply the random function by passing the “status of the search” variable as an argument.

1// FAVORITE BOT====================
2
3// find a random tweet and 'favorite' it
4var favoriteTweet = function() {
5 var params = {
6 q: '#nodejs, #Nodejs', // REQUIRED
7 result_type: 'recent',
8 lang: 'en'
9 }
10 // for more parametes, see: https://dev.twitter.com/rest/reference
11
12 // find the tweet
13 Twitter.get('search/tweets', params, function(err, data) {
14 // find tweets
15 var tweet = data.statuses
16 var randomTweet = ranDom(tweet) // pick a random tweet
17
18 // if random tweet exists
19 if (typeof randomTweet != 'undefined') {
20 // Tell TWITTER to 'favorite'
21 Twitter.post('favorites/create', { id: randomTweet.id_str }, function(
22 err,
23 response
24 ) {
25 // if there was an error while 'favorite'
26 if (err) {
27 console.log('CANNOT BE FAVORITE... Error')
28 } else {
29 console.log('FAVORITED... Success!!!')
30 }
31 })
32 }
33 })
34}
35// grab & 'favorite' as soon as program is running...
36favoriteTweet()
37// 'favorite' a tweet in every 60 minutes
38setInterval(favoriteTweet, 3600000)
39
40// function to generate a random tweet tweet
41function ranDom(arr) {
42 var index = Math.floor(Math.random() * arr.length)
43 return arr[index]
44}

Note that the tweets searched by our bot are all stored in an array. Again, we use JavaScript’s timer function setInterval()to search and favorite the tweet after a specific period of time in milliseconds.

The complete module: bot.js :

1// Dependencies =========================
2var twit = require('twit'),
3 config = require('./config')
4
5var Twitter = new twit(config)
6
7// RETWEET BOT ==========================
8
9// find latest tweet according the query 'q' in params
10var retweet = function() {
11 var params = {
12 q: '#nodejs, #Nodejs', // REQUIRED
13 result_type: 'recent',
14 lang: 'en'
15 }
16 Twitter.get('search/tweets', params, function(err, data) {
17 // if there no errors
18 if (!err) {
19 // grab ID of tweet to retweet
20 var retweetId = data.statuses[0].id_str
21 // Tell TWITTER to retweet
22 Twitter.post(
23 'statuses/retweet/:id',
24 {
25 id: retweetId
26 },
27 function(err, response) {
28 if (response) {
29 console.log('Retweeted!!!')
30 }
31 // if there was an error while tweeting
32 if (err) {
33 console.log(
34 'Something went wrong while RETWEETING... Duplication maybe...'
35 )
36 }
37 }
38 )
39 }
40 // if unable to Search a tweet
41 else {
42 console.log('Something went wrong while SEARCHING...')
43 }
44 })
45}
46
47// grab & retweet as soon as program is running...
48retweet()
49// retweet in every 50 minutes
50setInterval(retweet, 3000000)
51
52// FAVORITE BOT====================
53
54// find a random tweet and 'favorite' it
55var favoriteTweet = function() {
56 var params = {
57 q: '#nodejs, #Nodejs', // REQUIRED
58 result_type: 'recent',
59 lang: 'en'
60 }
61 // find the tweet
62 Twitter.get('search/tweets', params, function(err, data) {
63 // find tweets
64 var tweet = data.statuses
65 var randomTweet = ranDom(tweet) // pick a random tweet
66
67 // if random tweet exists
68 if (typeof randomTweet != 'undefined') {
69 // Tell TWITTER to 'favorite'
70 Twitter.post('favorites/create', { id: randomTweet.id_str }, function(
71 err,
72 response
73 ) {
74 // if there was an error while 'favorite'
75 if (err) {
76 console.log('CANNOT BE FAVORITE... Error')
77 } else {
78 console.log('FAVORITED... Success!!!')
79 }
80 })
81 }
82 })
83}
84// grab & 'favorite' as soon as program is running...
85favoriteTweet()
86// 'favorite' a tweet in every 60 minutes
87setInterval(favoriteTweet, 3600000)
88
89// function to generate a random tweet tweet
90function ranDom(arr) {
91 var index = Math.floor(Math.random() * arr.length)
92 return arr[index]
93}

Usage

To run this bot, go to your terminal:

1$ node bot.js

To avoid this monotonous process you can use npm scripts or nodemon. You can also deploy this app on Heroku for a continuous integration.

To use npm scripts, make this edit under scripts in package.json :

1{
2 "scripts": {
3 "start": "node bot.js"
4 }
5}

Then from terminal:

1$ npm start

There are various ways to write a Twitter Bot, this is just one way. Your bot can be smart and you can do various things with it. You just have to refer to twit documentation for other RESTful API methods to manipulate Twitter API endpoints.

For further reading check out Botwiki.org for various types of bots on vast amount of platforms. For advanced reading, check out Botwiki’s list of tutorials of Twitter Bots in different programming languages.

Originally Published at Hackernoon.com

I'm Aman working as an independent fullstack developer with technologies such as Node.js, ReactJS, and React Native. I try to document and write tutorials to help JavaScript, Web and Mobile developers.