Deploy a Node.js Twitter bot on Heroku

So you've made a Twitter bot, and got it running locally, but you don't want to leave the connection open and host it yourself. Heroku is a platform that will let you deploy and host your bot for free, and this post will walk you through the steps.

Heroku's guide has a lot of relevant instructions, but we need to do a couple of things differently.

First, head over to Heroku and create an account. Then follow the Set up section.

Create a Heroku app

Back in your terminal, create a new app, which prepares Heroku to receive your source code:

heroku create

When you do this, a Git remote (called heroku) is also created and associated with your local Git repository.

Heroku generates a random name for your app, or you can pass a parameter to specify your own app name. The name of the app in this case won't be visible to anyone interacting with your bot so there's no need to change it.

Deploy to Heroku

Now deploy your code:

git push heroku master

If that completes successfully, your bot will be deployed. In fact, this is the only command you need to run to deploy a new version of your bot at any point in the future. There's more work to do for the initial deployment yet though.

Process types

Heroku can run different types of processes. By default, you have a web process that's expected to listen on port 80, which is needed for most web apps. However, this won't work in our case because our bot doesn't make HTTP requests - it runs purely in Node.js - which will cause the bot to timeout and crash.

We need a worker process type, which we can define with a Procfile. This file will contain our process type, and the command you run to start your bot. Create the file and add this to it:

worker: node bot.js

Now we need to tell Heroku to use just the worker, and not to expect a web process. Run this in your terminal:

heroku ps:scale web=0 worker=1

Environment variables

The final thing preventing our bot from working is the use of environment variables for the API keys. You set these locally for development, but Heroku doesn't know about them yet. Run this command, inserting the correct values where necessary:

heroku config:set CONSUMER_KEY=youruniquecode CONSUMER_SECRET=youruniquecode ACCESS_TOKEN_KEY=youruniquecode ACCESS_TOKEN_SECRET=youruniquecode

To check everything is working correctly, type:

heroku ps

Your output should look something like this:

=== worker (1X): node bot.js
worker.1: up 2014/12/10 13:12:35 -0800 (~ 2h ago)

If so, great! Send a Tweet to your bot and see if you get a response. If not, something didn't go quite as expected. Running heroku logs --tail will show you any errors that occurred. Try Googling them if you're still not sure what went wrong, or re-trace your steps and check you didn't miss anything.