Build a Twitter Bot in Half an Hour with Node.js and Heroku

Photo credit: crises_crs via Flickr

They grab breaking news at lightning speed. They flit around correcting strangers’ grammar. They spit out nuggets of nonsensical yet weirdly fascinating gibberish.

These days, it seems like Twitter bots are taking over the world, serving up lots of weird, obscure, and mashed-together bits of information, and letting any Twitter user perform all kinds of tasks with a simple @-reply.

But for a beginning programmer looking to build one, it can be hard to know where to get started. There are some great tools for building simple bots, but as they’re built for non-programmers, their functionality is inherently limited. On the other end of the spectrum, most of the guides and tutorials out there have a fairly high learning curve and cover more ground than they need to.

This guide is aimed at developers who want to get a simple Twitter bot off the ground as fast as possible using Node.js, in a way that allows them to use it as a jumping-off point to build it into as complex and creative an app as they can imagine. By the end, we’ll have a simple bot.js file tweeting at a set interval that you can then expand and build upon by linking other .js files or calling APIs.

Enough chit-chat. Let’s get coding!

Step 1: Set Up Technologies and Accounts

There are a couple of core technologies we’ll need to get started:

  • A basic grasp of Git and familiarity with the command line are a must for working with Node and Heroku. If you’re not familiar with these technologies, here’s a tutorial on the command line and here’s how to install Git.
  • Node.js. Node is a platform for running JavaScript — a language designed to be used inside web browsers — on the server side instead. Helpully, it comes bundled with NPM, a simple installer that lets you add complex functions to your app with a single line of code. You can download Node here or, if you have Homebrew for Mac or Linux, just run:
brew install node
  • A Twitter account for your bot. Sign up for one here. Twitter accounts require a unique email address, but there are several ways to fake a unique address with your main email provider (try this for Gmail and this for Outlook). You’ll need to verify your phone number in the process (it’s optional during initial signup but will be required before you can request an API key). Don’t worry if you’ve already used your phone to verify another account — you can use the same number to verify multiple accounts (although you’ll have to reassign your original account as the main one associated with it afterward if you want to tweet by SMS).
  • A new Twitter app, which you can create here once you’ve followed the steps from the previous bullet point. If you’re not sure what to set as your website, just set your personal site or a page where you have an account somewhere. It’s not particularly important right now for the type of simple bot app we’re going to build.
  • And finally, a Heroku account. Heroku is an incredible platform that allows you to deploy simple apps quickly and easily, for free. Sign up here and then download Heroku Toolbelt, which allows you to deploy with the command line, here. Then login to Toolbelt by following these steps.

Step 2: Deploy Early and Often

Once we’ve gotten everything from Step 1 in order, we’ll need to make a directory for our new app and set up Node, Git, and Heroku in the directory.

Here’s the command line sequence. Replace our-twitterbot-name with whatever you’d like to name your bot (it’s best to stick to lowercase letters and dashes here, otherwise may not be able to use the same name across Heroku and NPM):

mkdir our-twitterbot-name
cd our-twitterbot-name
git init
heroku create our-twitterbot-name
npm init
npm install twit --save
npm install node-twitterbot --save
touch bot.js
touch Procfile
git add .
git commit -m "Initial commit"
git push heroku master

Whoa! All it took was a few simple lines of code to link our directory up to Git and Heroku, install our two core dependencies, and make our initial commit and deployment to Heroku.

Let’s break down exactly what we did here:

  • We made a directory and moved into it.
  • We initialized a Git repository, created a Heroku application, and created a package.json file with NPM, which will allow us to save our modules for deployment.
  • We installed two Node modules — twit and node-twitterbot — and saved them to our package.json file.
  • We made a script file — bot.js — that will serve as the core file controlling our bot, and a Procfile, which is how we will tell Heroku what to do with our script.
  • We saved our directory with Git and made our first deployment to Heroku.

Step 3: Getting our Files Ready to Tweet

Whew. That seems like a lot, and it was. With the basics out of the way, now we need to prepare our script file and Procfile. Open the directory in a text editor like Atom or Sublime Text.

Let’s get the Procfile out of the way first, because — believe it or not — we only need one line of code for it:

worker: node bot.js

This is simply the command Heroku will use to run our script file, bot.js, in Node as soon as it’s deployed. This isn’t absolutely necessary, as we’ll be scheduling our script to run regularly a different way, but it’s nice to run it once upon deployment so we know the deployment was successful.

We also need to make some additions to our script file, bot.js:

var Twit = require(‘twit’);
var TwitterBot = require(‘node-twitterbot’).TwitterBot;
var Bot = new TwitterBot({
consumer_key: process.env.BOT_CONSUMER_KEY,
consumer_secret: process.env.BOT_CONSUMER_SECRET,
access_token: process.env.BOT_ACCESS_TOKEN,
access_token_secret: process.env.BOT_ACCESS_TOKEN_SECRET
});
var phraseArray = [ "hey twitter",
"im tweeting",
"tweet tweet",
"tweetstorm time... 1/22",
"plz RT v important",
"delete ur account",
"it me",
"same",
"#dogpants go on 4 legs!!",
"#thedress is blue and black" ];
function chooseRandom(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)];
}
var phrase = chooseRandom(phraseArray) + ", " + chooseRandom(phraseArray);
Bot.tweet(phrase);

What’s going on here? A couple important things.

First, we’re telling Node that we’ll be using the twit and node-twitterbot modules in our script file that we installed with NPM in Step 2. The twit module provides a set of JavaScript functions that make it easy for our app to communicate with Twitter — the AJAX calls to Twitter’s API are handled by twit under the hood. While twit is very powerful, its complexity is beyond the scope of what we’re trying to build here. So we’re also using node-twitterbot, which adds further refinements on top of twit’s functionality that make it easy to build simple bots. If you’d like to dive deeper into these awesome modules, check out the twit documentation here and the node-twitterbot documentation here.

Next, we’re telling node-twitterbot to use Heroku config variables that we’ll be setting up in Step 4 as our access tokens to pass to Twitter. That’s what…

process.env.BOT_CONSUMER_KEY

…and the three lines under it are doing. (Don’t worry about this too much just yet.)

Next, we’re instantiating an array with a number of phrases as the variable ‘phraseArray’, using a function called ‘chooseRandom’ to pick a random phrase from the array, and saving it as variable ‘phrase’. (This element of randomness is important — our bot won’t function if we try to just tweet the same thing over and over again. I’ll explain why at the end of this guide.)

And finally, we’re setting up a simple command — tweet that random phrase we just chose, using node-twitterbot’s Bot.tweet function.

Let’s save our work and deploy it to Heroku again:

git add .
git commit -m "Adds basic bot functionality to bot.js"
git push heroku master

Now that our files are set up, we’re almost ready! We just need to set up our config variables with Heroku and schedule our tweets.

Step 4: Configuring Heroku

To communicate with Twitter, we’ll be using four secret codes that Twitter provides us with so we can link our app to Twitter. To retrieve them, we need to go to our apps page and click on the bot app we created in Step 1, then click the ‘Keys and Access Tokens’ tab.

Your ‘Access Level’ should say ‘Read and write’. If it says ‘Read only’, click ‘(modify app permissions)’ to change it.

Our four secret codes are on this page — ‘Consumer Key (API Key)’ and ‘Consumer Secret (API Secret)’ are near the top, and you can click the button under ‘Your Access Token’ near the bottom to generate your ‘Access Token’ and ‘Access Token Secret’.

Look familiar? These correspond to the four process.env values from Step 3. But it’s extremely important that we don’t just drop them into our bot.js file. To keep them safe and secure so no one can hack our bot, we have to set them up as config variables using the Heroku dashboard.

Click here to visit the Heroku dashboard, then click the name of your bot app (it should appear automatically because we have already deployed). Click ‘Settings’ near the top right, then click the ‘Reveal Config Vars’ button.

Now, in each set of ‘Key’/ ‘Value’ input boxes, we need to set the names we gave the config variables in Step 3 as each Key and the corresponding secret code Twitter has given us as each respective Value. It should look something this:

BOT_CONSUMER_KEY         vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
BOT_CONSUMER_SECRET      vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
BOT_ACCESS_TOKEN         vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
BOT_ACCESS_TOKEN_SECRET  vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe

…except, of course, that all the Values will look different, because they’re all unique. You should NEVER reveal these publicly in any way, including writing them directly into the code unless you know how to properly hide them (i.e., with a .gitignore and env.js).

Step 5: Scheduling Our Tweets

We’ve got everything set up and we’re ready to start scheduling our tweets! WOOHOO, SO EXCITING!

Let’s not get carried away, though. Our access to Twitter’s API is rate limited, meaning if we tweet too much with our bot Twitter will prevent more tweets from going through. We also don’t want to tweet so often that we’re spamming. What we need to do is set an interval so we can tweet every so often. As it turns out, Heroku provides a method of doing just that.

Let’s go back into our local directory and, using the command line, install a Heroku add-on called Scheduler:

heroku addons:create scheduler:standard

Now, let’s revisit our Heroku dashboard and click on our app again. See the new bar that’s just appeared? Next to the clock icon, click Heroku Scheduler. Once there, click ‘Add new job’.

In the input box next to the dollar sign, enter:

node bot.js

And then under ‘Frequency’, choose how often you want the bot to tweet. Then click ‘Save’.

And that’s it! You’ve just completed a fully autonomous, self-tweeting bot that will continue to tweet random phrases indefinitely.

Step 6: Above and Beyond the Basics

Of course, our bot right now isn’t particularly interesting. So why not replace the random phrase choosing mechanism in bot.js with something more creative? Here are a couple sources of inspiration:

  • This list of the 25 ‘Most Ridiculous’ Twitter bots:

One word of warning: make sure that whatever kind of bot you make, it’s tweeting something distinct every time it tweets. Twitter watches apps that use its API and will prevent tweets from being posted if they’re identical to a tweet the app recently posted. That’s why this example uses a simple random phrase generator rather than tweeting “Hello world!” over and over again.

Other than that, get creative and happy tweeting! If you create something cool, let me know on Twitter and I’ll give you a shout-out.

Show your support

Clapping shows how much you appreciated Matt Popovich’s story.