Create a Simple Twitter Bot with Node.js

Published on Nov 23, 2016

9 min read

NODEJS

Originally Published at Hackernoon.com

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.

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?

🔗

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:

root/project-name
|- bot.js
|- config.js
|- 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 consumerconsumer_key: '',
11 consumerconsumer_secret: '',
12 accessaccess_token: '',
13 accessaccess_tokenaccess_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.

$ 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 parameters, 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 parameters, 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(
22 'favorites/create',
23 { id: randomTweet.id_str },
24 function (err, response) {
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};
36// grab & 'favorite' as soon as program is running...
37favoriteTweet();
38// 'favorite' a tweet in every 60 minutes
39setInterval(favoriteTweet, 3600000);
40
41// function to generate a random tweet tweet
42function ranDom(arr) {
43 var index = Math.floor(Math.random() * arr.length);
44 return arr[index];
45}

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(
71 'favorites/create',
72 { id: randomTweet.id_str },
73 function (err, response) {
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};
85// grab & 'favorite' as soon as program is running...
86favoriteTweet();
87// 'favorite' a tweet in every 60 minutes
88setInterval(favoriteTweet, 3600000);
89
90// function to generate a random tweet tweet
91function ranDom(arr) {
92 var index = Math.floor(Math.random() * arr.length);
93 return arr[index];
94}

Usage

🔗

To run this bot, go to your terminal:

$ 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:

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


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.