How To Make A Twitter Bot With Node JS For Beginners – PART 2

How To Make A Twitter Bot With Node JS For Beginners – PART 2

In this tutorial we’ll be making a fully functional Twitter Bot. The Bot will be hosted on our computer and not on a server online. To host the bot online on Heroku check out part 3 of this tutorial series. If you haven’t seen Part 1, go check it out here. There we will set up all the requirements for our project.

Alright, let’s get on with the coding ( Finally yay ! … 🙂 )


Open your bot.js file on a text editor. If you don’t have one download Sublime Text Here

1. Importing the modules

// Import Node Modules
let TWIT = require('twit'),

// Import Config File
let config = require('./config');

The first line of code imports the Twit module and assigns it to the ‘Twit’ variable. Similarly the second line of code imports the config.js file on our Folder. Make sure you have added all the required consumer keys and access tokens on the config.js file.

Note: config.js is our own custom module on our directory which is why we have added './' 
before 'config' to import it.

2. Creating a Twit Instance

We now create a Twit Instance.

// Create a Twit Instance
var Twit = new TWIT(config);

The variable Twit holds the TWIT instance. ( Note: Twit and TWIT are different . We’ll be using only ‘Twit’ from now on)

The Twit instance has a function called ‘post’ which enables us to make a tweet. This post function takes 3 different arguments

  • method
  • input
  • callback function
// tweet 'hello world!' 
Twit.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
  if (err)
     console.log(data);
  else
     console.log('Successfully tweeted');
});

Let’s breakdown and understand this code.

a. The first argument:

statuses/update’ means we want to update the status. There are other various methods like ‘media/upload’ to upload a media, ‘favorites/create’ to favorite a tweet,  ‘direct_messages/new’ to send direct messages, and many more. Read more about Twitter API here.

b. The second argument: –

{ status: ‘hello world!’ } is a JavaScript object with a property ‘status’ and a value of ‘hello world!’. This means we want to make a tweet ‘hello world’. To make any other tweets just edit the ‘hello world!’ part like this { status: ‘Best bot ever’ } , { status: ‘I love Twitter Bots’ } …

c. The Third Argument:-

This argument is a function or more specifically a callback function.

So now what our function does is updates the status ‘hello world!’ right? As soon as the post function makes the tweet or if there occurs any error while tweeting, this callback function is invoked!

Inside this function we have three variables ‘error’, ‘data’ and ‘response’. If any error occurs while tweeting, this error variable will contain the information of the error, if everything goes right then we’ll get a response.

Now your bot.js file should look something like this

Code Snippet
Code Snippet

Great ! With these lines of code we can already make a tweet. Open up your command line and navigate to your project folder. Now run the command

node bot.js

This should make a tweet! Go check your bot’s twitter account.

First tweet from our Twiter Bot
First tweet from our Twiter Bot

3. Wrapping up in a function

It’s tedious to write that long string of function to make a tweet. Let’s wrap that Twit.post function in our own custom function.

Now everytime we need to make a tweet we can just call the makeTweet() function and pass in the tweet like this

tweet('I am tweeting from my command line and it's awesome');

4. Automating Tweets

This is great but what’s the fun if we need to run a command everytime we need to make a tweet? Let’s automate the process so that our bot will make a tweet in certain time interval. We can achieve this by using the setInterval()  function in JavaScript that runs a task in a certain set of intervals. Add this line of code at the bottom

setInterval(makeTweet, 60000, Math.random() * 20)

This code runs the makeTweet() function every 60 seconds ( 60,000 milliseconds). If you run the bot from your command line the bot will tweet a random number every minute.

Do not spam and post every few seconds or so. Twitter will block your app! But you can make new one again.

5. Streaming Tweets

Alright so until now we made a bot that just posts tweet. Now we want to stream tweets. For example, we can track certain words like ‘Donald Trump’ such that whenever someone makes a tweet with the word ‘Donald Trump’ anywhere in the tweet, we’ll get notified. We can track twitter accounts, words, hashtags, etc with this method.

Alright, let’s create a trackTweet() function. This function takes a keyword that we want to track as a parameter. Once someone makes a tweet with that keyword, our bot will print the tweet in the command line.

Let’s track ‘trump’. The last line calls the function and the bot will start tracking every tweets with ‘trump’

6. Track tweets and favorite the tweet

Currently the trackTweet() function  tracks tweet and prints it on the command line. Let’s modify it so that we can not only track tweets but also follow the ones we like.

We’ll create a favoriteTweet() function that will favorite tweets and then put it inside the trackTweet()  function. This function is almost identical to the makeTweet() except for its function.

As a bonus I have also added a new followUser()function. Pass it the username and your bot will follow the user.


So basically this is all our coding part. We have created a twitter bot that tracks a keyword and favorites the tweet if it finds one. I know it’s not the most exciting bot. I tried to focus this tutorial mainly for beginners. To summarize this tutorial, We have learnt to

  • Track Tweets
  • Make Tweets
  • Follow User
  • Favorite Tweet

IThere’s still so much more to explore. Visit the Twitter API Documentation page and try doing more on your own.

About the Author