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

January 3rd, 2016

A Lego astronaut remote-controlling a Lego robot 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 Lego spaceman making a "Wow!" expression at a laser lightshow

  • 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 functionality 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:

1brew install node
  1. 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.

  2. 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 for the type of simple bot app we’re going to build.

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

A large Lego space robot from the front of a Lego catalog

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, so that you can use the same name across across the app and in Heroku):

1mkdir our-twitterbot-name
2cd our-twitterbot-name
3git init
4heroku create our-twitterbot-name
5npm init
6npm install node-twitterbot --save
7touch bot.js
8touch Procfile
9git add .
10git commit -m "Initial commit"
11git 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 node-twitterbot and saved it 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

A Lego astronaut jumping up and saying "Yes!"

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:

1worker: 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, without having to wait until the next regularly scheduled interval we’ll be setting up our bot to tweet at.

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

1let TwitterBot = require(‘node-twitterbot’).TwitterBot;
2let Bot = new TwitterBot({
3 consumer_key: process.env.BOT_CONSUMER_KEY,
4 consumer_secret: process.env.BOT_CONSUMER_SECRET,
5 access_token: process.env.BOT_ACCESS_TOKEN,
6 access_token_secret: process.env.BOT_ACCESS_TOKEN_SECRET
7});
8
9let phraseArray = [
10 "hey twitter",
11 "im tweeting",
12 "tweet tweet",
13 "tweetstorm time... 1/22",
14 "plz RT v important",
15 "delete ur account",
16 "it me",
17 "same"
18];
19
20function chooseRandom(array) {
21 return array[Math.floor(Math.random() * array.length)];
22}
23
24let phrase =
25 chooseRandom(phraseArray)
26 + ", "
27 + chooseRandom(phraseArray);
28
29Bot.tweet(phrase);

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

First, we’re telling Node that we’ll be using the node-twitterbot module in our script file that we installed with NPM in Step 2, which makes it easy to build simple bots. If you’d like to dive deeper into this awesome module, check out 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…

1process.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 method.

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

1git add .
2git commit -m "Adds basic bot functionality to bot.js"
3git 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

A Lego astronaut controlling a Lego mecha robot

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:

1BOT_CONSUMER_KEY vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
2
3BOT_CONSUMER_SECRET vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
4
5BOT_ACCESS_TOKEN vbiy9fqwv9q8wmvwe7iv7nowemvoweqybvowe
6
7BOT_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. To be safe, and minimize the risk that you’ll accidentally push them to a public Git repository, it’s best to never write secrets like these into your code — always import them as environment variables instead.

Step 5: Scheduling Our Tweets

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

A Lego astronaut screaming "Spaceship!"

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:

1heroku 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:

1node 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

A Lego space base with many astronauts piloting rovers, spaceships, and other vehicles

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:

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.