Writing a Node.js Twitter Bot Part 2

Published on Dec 25, 2016

5 min read


If you read the first part of my tutorial, you already know how to make a Twitter Bot with Node.js that retweets and favorites tweets using the Twitter API.

In the second part of the Twitter Bot tutorial, we will continue to extend our Bot by adding functionality that will tweet back to any Twitter user who follows our bot.

Before starting this, make sure your directory structure includes:

  • package.json (the configuration file for our Node.js application)
  • config.js (the configuration file of our Twitter application that contains both consumer and access key & tokens)
  • bot.js (our main application file)

The representation would be:

|- bot.js
|- config.js
|- package.json

You can take a look at the complete bot.js file from the first part of this tutorial.

Also, make sure you have the twit npm module installed.

How to make a Twitter bot that replies


After setting up the dependencies and loading/requiring the configuration related to our application, we are going to develop a functionality that is going to tweet back to a Twitter user who follows the Bot's Twitter Handler.

We are going to use Twitter's Streaming API to interact with our followers.

Setting up the Streams API


First, we have to set up a stream. Fortunately, the third party npm dependency twit provides an API function .stream() to do this task.

1// Use Streams API for interacting with a USER
2// set up a user stream
4var stream = Twitter.stream('user');

.stream() keeps the connection alive, and returns an EventEmitter.

twit provides a list of stream events to listen on, such as 'follow', 'unfollow', 'favorite' and 'unfavorite'.

Right now we are only interested in the follow event, however the basic syntax is similar to every event.

1// when someone follows
2stream.on('follow', followed);

When a user follows our Twitter Bot, the follow event will trigger the callback associated with it, in our case followed.

1// ...trigger the callback
2function followed(event) {
3 console.log('Follow Event is running');
4 //get user's twitter handler (screen name)
5 var name = event.source.name,
6 var screenName = event.source.screen_name;
7 // function that replies back to the user who followed
8 tweetNow('@' + screenName + ' Thank you for the follow up.');

Replying with tweetnow()


In the followed callback, we pass an event argument which gets the Twitter handle and the screen name of the user. In the last line, we invoke a tweetnow() function that replies back to the user who followed our bot.

The tweetnow() function takes a string as an argument and updates our bots status. In other terms, it tweets by using .post()function provided by the twit API to post to the statuses/updateTwitter API endpoint.

This endpoint gets called whenever you tweet from your Twitter account.

If you noticed in the previous tutorial when retweeting or to favorite a tweet, we used .post() to update our status.

1function tweetNow(tweetTxt) {
2 var tweet = {
3 status: tweetTxt
4 };
5 Twitter.post('statuses/update', tweet, function (err, data, response) {
6 if (err) {
7 console.log('Error in Replying');
8 } else {
9 console.log('Gratitude shown successfully');
10 }
11 });

Unlike in the previous tutorial, we don't need JavaScripts Timer function this time, since we are using the Streaming API which helps to keep the connection alive.

Here comes the complete code of our bot:

1// Use Streams API for interacting with a USER ==========
2// set up a user stream
4var stream = Twitter.stream('user');
6// FOLLOW-Reply BOT ===========================
8// when someone follows
9stream.on('follow', followed);
11// ...trigger the callback
12function followed(event) {
13 console.log('Follow Event is running');
14 //get their twitter handler (screen name)
15 var name = event.source.name,
16 screenName = event.source.screen_name;
17 // function that replies back to the user who followed
18 tweetNow('@' + screenName + ' Thank you for the follow up.');
21// function definition to tweet back to user who followed
22function tweetNow(tweetTxt) {
23 var tweet = {
24 status: tweetTxt
25 };
26 Twitter.post('statuses/update', tweet, function (err, data, response) {
27 if (err) {
28 console.log('Error in Replying');
29 } else {
30 console.log('Gratitude shown successfully');
31 }
32 });

Running the Twitter Bot


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

If you are planning to deploy on Heroku, make sure to include a Procfile in the root of your directory structure and add the following line to the file:

worker: node bot.js

If you are using npm scripts, make sure you edit the scripts attribute in thepackage.json file:

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

Then to run from terminal:

$ npm start

Next up


To do further smart things with your bot, go and check out the twit documentation for other RESTful API methods and Streaming API events.

If you are interested in Twitter Bots, check Botwiki.org - as they have the vast collection of Twitter Bots in different programming languages.

The sole purpose of Bot as a web application is automation. For example, when I created my first Twitter Bot @nodejstweets, the whole idea was to remain up to date with the most recent happenings.

You can do a lot of things with a Twitter Bot, whether for your own sole purpose or to solve a purpose for a community. See @100DaysOfCode as a great example.

Originally Published at RisingStack.com

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.