In this tutorial, we will create a Twitter Bot with Node.js that retweets or favorites based on hashtags, and replies to users if they follow the account.

Update: the second part of this tutorial is available here!

What do you need to create this bot?

You must have Node.js installed on your system.

A Twitter Account.

Your bot will be using twit - an npm module which manipulates tweets & streams and communicates with the Twitter API.

Let’s Start

Set up an empty directory and initialize it with: $ npm init to configure this web application with a 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. To do so, edit the main field in the package.json to:

{ "main": "bot.js", },

Your current directory structure should look like this:

root/project-name |- bot.js |- config.js |- package.json

After logging into your Twitter account, follow this link: https://apps.twitter.com/app/new to create a new application.

Fill out the necessary fields in the form and click on the Create Your Twitter Application button. After creating the application, look for 'Keys and Access Tokens' and click on 'Generate Token Actions'. Copy the:

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:

//config.js /** TWITTER APP CONFIGURATION * consumer_key * consumer_secret * access_token * access_token_secret */ module.exports = { consumer_key: '', consumer_secret: '', access_token: '', access_token_secret: '' }

The Twitter bots configuration is complete now. Please note that the consumer key, consumer secret, access_token and access_token_secret will differ for every different application.

Let’s continue with our third requisite - installing the Twitter API client for node which will help us to communicate with Twitter and provide an API for all of the 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.

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

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

var Twitter = new twit(config);

So far so good?

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

Let’s write a function expression that finds the latest tweets according to the query passed as a parameter. We will initialize a params object that will hold various properties to search a tweet, but most importantly a 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 these property values like a twitter handler to monitor a specific Twitter account or a #hashtag. For our example bot, we have to find the latest tweets on #nodejs.

This is how the functionality of the retweet bot starts:

var retweet = function() { var params = { q: '#nodejs, #Nodejs', result_type: 'recent', lang: 'en' } }

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

You can always check out the 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 the Twitter.get function provided by the twit API to GET any of the REST API endpoints. The REST API endpoint is a reference to the Twitter API endpoint which we are going to call to search for tweets.

The Twitter.get function accepts three arguments: API endpoint, params object (defined by us) and a callback.

// RETWEET BOT ========================== // find latest tweet according the query 'q' in params var retweet = function() { var params = { q: '#nodejs, #Nodejs', // REQUIRED result_type: 'recent', lang: 'en' } // for more parameters, see: https://dev.twitter.com/rest/reference/get/search/tweets Twitter.get('search/tweets', params, function(err, data) { // if there no errors if (!err) { // grab ID of tweet to retweet var retweetId = data.statuses[0].id_str; // Tell TWITTER to retweet Twitter.post('statuses/retweet/:id', { id: retweetId }, function(err, response) { if (response) { console.log('Retweeted!!!'); } // if there was an error while tweeting if (err) { console.log('Something went wrong while RETWEETING... Duplication maybe...'); } }); } // if unable to Search a tweet else { console.log('Something went wrong while SEARCHING...'); } }); }

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

We can use JavaScripts timer function setInterval() to search and retweet after a specific period of time automatically.

// grab & retweet as soon as program is running... retweet(); // retweet in every 50 minutes setInterval(retweet, 3000000);

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

Favorite Bot

Similar to the retweet bot, we can define and initialize another function expression that will search and favorite a tweet randomly.

Yes, the difference here is to search and grab the tweets randomly.

We will start by creating a parameter object params that will consist of three properties as in the retweet() function expression. The bot will search for tweets using the same .get() function provided by the twit API to GET any of the Twitter API endpoints.

In our case, we need search/tweets . We will store the status of the tweet to favorite in a variable. We will apply the random function by passing the “status of the search” variable as an argument in another variable.

// FAVORITE BOT==================== // find a random tweet and 'favorite' it var favoriteTweet = function(){ var params = { q: '#nodejs, #Nodejs', // REQUIRED result_type: 'recent', lang: 'en' } // for more parametes, see: https://dev.twitter.com/rest/reference // find the tweet Twitter.get('search/tweets', params, function(err,data){ // find tweets var tweet = data.statuses; var randomTweet = ranDom(tweet); // pick a random tweet // if random tweet exists if(typeof randomTweet != 'undefined'){ // Tell TWITTER to 'favorite' Twitter.post('favorites/create', {id: randomTweet.id_str}, function(err, response){ // if there was an error while 'favorite' if(err){ console.log('CANNOT BE FAVORITE... Error'); } else{ console.log('FAVORITED... Success!!!'); } }); } }); } // grab & 'favorite' as soon as program is running... favoriteTweet(); // 'favorite' a tweet in every 60 minutes setInterval(favoriteTweet, 3600000); // function to generate a random tweet tweet function ranDom (arr) { var index = Math.floor(Math.random()*arr.length); return arr[index]; };

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 :

// Dependencies ========================= var twit = require('twit'), config = require('./config'); var Twitter = new twit(config); // RETWEET BOT ========================== // find latest tweet according the query 'q' in params var retweet = function() { var params = { q: '#nodejs, #Nodejs', // REQUIRED result_type: 'recent', lang: 'en' } Twitter.get('search/tweets', params, function(err, data) { // if there no errors if (!err) { // grab ID of tweet to retweet var retweetId = data.statuses[0].id_str; // Tell TWITTER to retweet Twitter.post('statuses/retweet/:id', { id: retweetId }, function(err, response) { if (response) { console.log('Retweeted!!!'); } // if there was an error while tweeting if (err) { console.log('Something went wrong while RETWEETING... Duplication maybe...'); } }); } // if unable to Search a tweet else { console.log('Something went wrong while SEARCHING...'); } }); } // grab & retweet as soon as program is running... retweet(); // retweet in every 50 minutes setInterval(retweet, 3000000); // FAVORITE BOT==================== // find a random tweet and 'favorite' it var favoriteTweet = function(){ var params = { q: '#nodejs, #Nodejs', // REQUIRED result_type: 'recent', lang: 'en' } // find the tweet Twitter.get('search/tweets', params, function(err,data){ // find tweets var tweet = data.statuses; var randomTweet = ranDom(tweet); // pick a random tweet // if random tweet exists if(typeof randomTweet != 'undefined'){ // Tell TWITTER to 'favorite' Twitter.post('favorites/create', {id: randomTweet.id_str}, function(err, response){ // if there was an error while 'favorite' if(err){ console.log('CANNOT BE FAVORITE... Error'); } else{ console.log('FAVORITED... Success!!!'); } }); } }); } // grab & 'favorite' as soon as program is running... favoriteTweet(); // 'favorite' a tweet in every 60 minutes setInterval(favoriteTweet, 3600000); // function to generate a random tweet tweet function ranDom (arr) { var index = Math.floor(Math.random()*arr.length); return arr[index]; };

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 :

{ "scripts": { "start": "node bot.js", } }

Then from terminal:

$ npm start

Conclusion

There are various ways to write a Twitter Bot, and this is just one way. If you have any questions, let me know in the comments!

For further reading, check out the second part of this tutorial, which discusses how to make a twitter bot that auto-replies to followers!