Before you go, check out these stories!

0
Hackernoon logoHow to Build a Twitter bot using NodeJs by@rathore

How to Build a Twitter bot using NodeJs

Author profile picture

@rathoreDeven

Founder @ dunebook.com and CodeSource.io

Building a Twitter bot using their API is one of the fundamental applications of the Twitter API. To build a Twitter bot with Nodejs, you’ll need to take these steps below before proceeding:

  • Create a new account for the bot
  • Apply for API access at developer.twitter.com
  • Ensure you have NodeJS and NPM installed on your machine

We’ll be building a Twitter bot with Nodejs to track a specific hashtag then like and retweet every post containing that hashtag.

Getting up and running

Firstly you’ll need to initialize your node app by running npm init and filling the required parameters. Next, we install Twit, an NPM package that makes it easy to interact with the Twitter API.

$ npm install twit --save

Now, go to your Twitter developer dashboard to create a new app so you can obtain the consumer key, consumer secret, access token key and access token secret. After that, you need to set up these keys as environment variables to use in the app.

Building the bot

Now in the app’s entry file, initialize Twit with the secret keys from your Twitter app.

// index.js
const Twit = require('twit');
const T = new Twit({
  consumer_key: process.env.APPLICATION_CONSUMER_KEY_HERE,
  consumer_secret: process.env.APPLICATION_CONSUMER_SECRET_HERE,
  access_token: process.env.ACCESS_TOKEN_HERE,
  access_token_secret: process.env.ACCESS_TOKEN_SECRET_HERE
});

Listening for events

Twitter’s streaming API gives access to two streams, the user stream and the public stream, we’ll be using the public stream which is a stream of all public tweets, you can read more on them in the documentation.

We’re going to be tracking a keyword from the stream of public tweets, so the bot is going to track tweets that contain “#JavaScript” (not case sensitive).

// index.js
const Twit = require('twit');
const T = new Twit({
  consumer_key: process.env.APPLICATION_CONSUMER_KEY_HERE,
  consumer_secret: process.env.APPLICATION_CONSUMER_SECRET_HERE,
  access_token: process.env.ACCESS_TOKEN_HERE,
  access_token_secret: process.env.ACCESS_TOKEN_SECRET_HERE
});

// start stream and track tweets
const stream = T.stream('statuses/filter', {track: '#JavaScript'});

// event handler
stream.on('tweet', tweet => {
// perform some action here
});

Responding to events

Now that we’ve been able to track keywords, we can now perform some magic with tweets that contain such keywords in our event handler function.

The Twitter API allows interacting with the platform as you would normally, you can create new tweets, like, retweet, reply, follow, delete and more. We’re going to be using only two functionalities which is the like and retweet.

// index.js
const Twit = require('twit');
const T = new Twit({
  consumer_key: APPLICATION_CONSUMER_KEY_HERE,
  consumer_secret: APPLICATION_CONSUMER_SECRET_HERE,
  access_token: ACCESS_TOKEN_HERE,
  access_token_secret: ACCESS_TOKEN_SECRET_HERE
});

// start stream and track tweets
const stream = T.stream('statuses/filter', {track: '#JavaScript'});

// use this to log errors from requests
function responseCallback (err, data, response) {
 console.log(err);
}

// event handler
stream.on('tweet', tweet => {
   // retweet
  T.post('statuses/retweet/:id', {id: tweet.id_str}, responseCallback);
  // like
  T.post('favorites/create', {id: tweet.id_str}, responseCallback);
});

Retweet

To retweet, we simply post to the statuses/retweet/:id also passing in an object which contains the id of the tweet, the third argument is a callback function that gets called after a response is sent, though optional, it is still a good idea to get notified when an error comes in.

Like

To like a tweet, we send a post request to the favourites/create endpoint, also passing in the object with the id and an optional callback function.

Deployment

Now the bot is ready to be deployed, I use Heroku to deploy node apps so I’ll give a brief walkthrough below.

Firstly, you need to download the Heroku CLI tool, here’s the documentation. The tool requires git in order to deploy, there are other ways but deployment from git seems easier, here’s the documentation.

There’s a feature in Heroku where your app goes to sleep after some time of inactivity, this may be seen as a bug to some persons, see the fix here.

You can read more on the Twitter documentation to build larger apps, It has every information you need to know about.

Here is the source code in case you might be interested.

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!