JavascriptNode.JSProgrammingTechnology

Create Twitter Bot Using Node.js Twit Package

Do you want to automate your tweets? Or create a twitter follow bot that follows relevant tweeters and thus enhances your engagement on this social media platform? If yes, then this tutorial is for you as today, I will teach you how to create twitter bot using Node.Js Twit package.

What is Node.JS Twit Package?

In case you are not aware of what Node.Js packages are, then quickly getting through this phase, Node.Js packages are bunch of ready made, open source codes that anyone can use in their Node.Js projects by referencing to them.

These packages are created by developers testing new things and who want to give back something to the world.

The biggest advantage of these packages are that you don’t have to “Re-Invent The Wheel” by writing programs to do something. If any problem has already been resolved by any package, just refer to it in your program and that’s it. There are a lot of Twitter bot packages available to buy but not all of them work well so it’s important to do your research beforehand. It won’t take much time to up-read on these tools. Because are review sites like Bountii.com inc which review Twitter, Instagram and Youtube bots for you so that you don’t have to do the legwork! Whichever you choose, make sure it works for you and your platforms.

The Twit Package to Create Twitter Bot

Similarly, talking about Node.Js Twit Package, it is an API based ready made code originally created by Tolga Tezel that eases the process of creating a twitter bot.

You can read the entire code and its documentation on this page

Twit package is not the only way to create twitter bot. In fact, it’s not even necessary to use any package at all. However, since we are more interested in the end product rather than learning the intricacies of the node.js language, we will rather use the package and save our time.

However, if you want to develop twitter bot from the scratch then I appreciate your grit,go ahead and do give it a try. But at the same time I would say that this wouldn’t be a wise choice if you are short on time.

Twitter Bot – Basic Functions

Before we start developing our bot, lets draw an outline of what it will be able to do.

  1. Search tweets based on a particular string/query
  2. Post (text) tweets/updates after regular intervals
  3. Respond with a thank you message when followed.

Though you can do a lot more than that, but I believe that will cover the most of the important portion you need to know to create one functioning and responsive twitter bot..

Twitter Bot – Prerequisite Information

If you see the first few codes of the Twit package (by following the link above), you may notice that it’s asking for the information such as consumer key, access token etc.

Node.Js Twit Package - Twitter Consumer Key

This information is exclusive to every user and twitter uses it to identify the user and his account.

I’ve written a separate article titled, Generate Twitter API Consumer Key and Access Tokens discussing what Twitter API keys are and how you can generate them to use in this tutorial.

Once, you have the consumer keys and the access tokens, we’ll start writing our code.

1. Install Twit Package in Node.JS

We’ll start by installing the Twit package on our (Node.JS) server.

Open up your Node.Js command prompt and enter the following code:

npm install twit

2. Save your Twitter API Keys in Separate File – Config.js

This step does not affect the functionality but I’d suggest you to keep your API keys in separate file. This way, you can call that file in any other program you want. So you don’t need to store your keys again and again every time you write a new program. Just write the piece of code once and refer to it in your program.

We will name the file, config.js

3. Print Message When the Server Starts

Again, this is also an optional step but you may prefer knowing if your server is running. So by writing just a one line code on your server.js file, we can easily implement this.

console.log(‘The Bot has started');

4. Create Necessary Variables

We already downloaded and installed Twit package above. Now let’s jump to the next steps in our server.js file:

  1. Use the Twit package by “requiring” it and store it in a variable named, Twit.
  2. Refer to our API keys in the config.js file and store it in the config variable.
  3. Configure the twit package and store it in a new variable called, T. Configuration means that we are letting the Twit package know what our API keys are.

Remember, we need our API keys so that the Twitter’s server is able to identify us.

//use the Twit package
var Twit = require('twit');  

//call the API keys we saved in the config.js file
var config = require('./config');  

//configure the twit package with our API keys
var T = new Twit(config);    

5. Search Tweets Using Twit’s Get API

In order to search for any tweet that fulfills our search criteria, we can use Twti’s Get API. Note that this is different from the regular Node.JS Get and Post Methods that I discussed in one of my previous articles.

Twit’s GET API accepts following 3 arguments.

  1. Path: In technical terms, it means what endpoint to hit. In simpler terms, Path means what to look for? For instance, to “search” for “Tweets” we can type, search/tweets
  2. Param: Short for “Parameters”, this is an optional argument. In the context of searching the tweets, you can define say, the criteria to search and/or how many search result to display etc.
  3. Callback: This argument, often a function, tells what to do when the (GET) API is executed. The Callback functions takes 3 arguments.

Callback Function

function(err, data, response)

  1. Err: is the error message that’s generated if the API is not properly executed
  2. Data: is the parsed message from Twitter
  3. Response: is the incoming http message

The code to search for tweet(s) using the GET API goes like this.

var params = {

       //search for this query
       q: ‘TheUsualStuff', 

       //number of searches
       count: 2 
   };

//this will do the magic for us   
T.get('search/tweets', params, gotData); 


//Callback function
function gotData(err, data, response) {

   //Tweets from other users
   var tweets = data.statuses;

   for (var i = 0; i<=tweets.length; i++) {
       console.log(tweets[i].text);
   }
}

6. Post Tweets Using Twit's POST API

Once we've seen what parameters Twit's GET API accepts, it becomes easier for us to implement other APIs. Like the Twit's POST API.

The POST API can be used to post tweets on twitter. However, you need to be careful when using bots to tweet as Twitter has set out some guidelines to post on Twitter.

(Repeated) violations of any of these rules may result in (severe situations) in the blockage of your account.

One such example is posting the exact same status consecutively.

Your twitter bot will show an error if you do this as Twitter will simply refuse to post such status.

Coming to our code, since we need to post status updates after every regular intervals, we'll be using Javascript's setInterval() function.

Again, just like GET, the POST API also accepts 3 arguments.

I believe I don't need to go in further details of what these arguments are as they are the exact same as in the GET API.

function tweet() {
       //Generate random number to make tweet different from previous ones
       var r = Math.floor(Math.random()*100); 
       
       //This is our Tweet (status/update)
       var tweet = {
            status: ‘Tweet Number: '+ r + ‘ Have a Good Day...!'
        };

        //This will post our tweet on Twitter
        T.post('statuses/update', tweet, tweeted);

        //The Callback function  
        function tweeted(err, data, response) {

           //Error handling          
           if (err) {
               console.log(err);
           }
           else {
               console.log(‘Tweet Posted!');
           }
    }

//tweets after every one hour
setInterval(tweet, 1000*60);

You may have realized that we can also store tweets in our database, access our database from Node.js and then post from there. However, for this article, creating database and then posting articles from there is out of our scope for now.

So let's keep it simple.

7. Respond to Your Followers Using Twit's Stream API

We searched for the tweets (GET) and then posted Tweets on our Twitter account (POST). Now, let's become more responsive.

How about we thank our followers every time they follow us?

This would be a nice gesture as our followers will not feel that we are taking them for granted.

At the same time, we need to make sure that our responding tweets should be unique so as to make sure that our automated tweets don't get rejected by Twitter.

Remember the rule that you cannot post same status updates or tweets consecutively?

So we'd need to get our followers' names and then add that with our tweet so that every responding tweet is unique. Also, did you know that you can buy real Twitter followers? That might be a good subject for another blog post.

Coming back to our point, to add some "responsiveness" in our twitter bot, we will use the Twit's Stream API.

stream(path, [param]) keeps the connection alive and returns an EventEmitter

The event binder, such as, on binds a triggering event with the endpoint.

For e.g. If you want to trigger an event every time when someone follows you (follow endpoint), you can bind an event trigger with the endpoint like this:

Binding Event on 'Follow' Endpoint

stream.on(‘follow', function([param])){
        //...
    };

Similarly, there are tons of other Endpoints on which you can bind an event using the Twit's Stream API such as Message, Delete, Tweet etc.

The complete Node.Js code to respond to each follow is:

//Configure Twit package with Twitter User
var stream = T.stream('user');

//Defining event when the bot should response
stream.on('follow', followed);


function followed(eventMsg) {
    //Twitter Name for e.g. The Usual Stuff in my case
    var name = eventMsg.source.name;      

    //Twitter username for e.g. theusualstuff17 in my case
    var screenName = eventMsg.source.screen_name;   
    
    //Response sent/tweeted to the followers
    tweetIt('Hi @'+screenName + ',\n' + 'Thanks for following #TheUsualStuff \n ');

    //Printed on the node command prompt
    console.log("Response has been posted to " + name);

}




Test if Your Twitter Bot is Running

Since we have now created a minimal but functioning Twitter bot, let us put it to test and see if it is really working.

  1. Start the command prompt.
  2. Type node followed by the file name. In our case, it is, server.js
  3. The command prompt will show a message, "The bot has started". This is an indication that the bot is now running and will post responses to your followers.
  4. With any other ID, you can ask your friend or use your second ID (in case you have one) to follow your main twitter account. The main twitter account is the one for which you generated the API Keys and the tokens above.
  5. As soon as you will follow, the bot will post a response from your main account to the account which followed it and a confirmation message will also show up on the command prompt.

Final Words

So that's how you can create a functioning Twitter bot for yourself. However, before concluding let me clarify few points that I think are worth noting.

  1. The purpose of this tutorial is just to give you guys a hang of how a basic twitter bot would work. Of course, this is not an ideal solution. Ultimately, you would need to create a database, store all your tweets and then post from there. Remember, we are talking about automation. You don't need to change the line of code every time you want to post a new tweet.
  2. Make sure that you do read the documentation of Twit package from its Github page. There are so many features that you can add in your twitter bot. This article has just scratched the surface of the vast ocean. So, go ahead, read the Twit package's documentation and get creative.
  3. Also make sure that you adhere to the Twitter's guidelines before you create a bot and start posting. Failing to comply could result in a ban from Twitter. So be careful about that.

One thought on “Create Twitter Bot Using Node.js Twit Package

  • Well, the stream API has been deprecated and blocked by twitter, so your tutorial is broken. Please update

Comments are closed.