Twitter Bot On Heroku

I made a twitter bot a week or two ago, and it has been a lot of fun watching people’s reactions to it. I won’t tell you what my triggers are or who the bot is because I think that’s part of the game. The bot lives entirely on it’s own. What I will tell you is how to host a Twitter bot on Heroku.

The Bot Code

You’ll use the Streaming API to search for stuff, and then the REST API to post “responses”. I followed this example.

require 'rubygems'
require 'bundler/setup'
Bundler.require

class Bot
  def self.go
    while true
      begin
        config = {
          :consumer_key        => ENV['TWITTER_CONSUMER_KEY'],
          :consumer_secret     => ENV['TWITTER_CONSUMER_SECRET'],
          :access_token        => ENV['TWITTER_ACCESS_TOKEN'],
          :access_token_secret => ENV['TWITTER_ACCESS_TOKEN_SECRET']
        }
        rClient = Twitter::REST::Client.new(config)
        sClient = Twitter::Streaming::Client.new(config)

        # topics to watch
        topics = ['hello', 'world', '#helloworld']
        sClient.filter(:track => topics.join(',')) do |tweet|
          next if tweet.text.match(/#{rClient.user.screen_name}/i)
          if tweet.is_a?(Twitter::Tweet) && !tweet.text.match(/^RT/) && tweet.lang == 'en'
            p "@#{tweet.user.screen_name}: #{tweet.text} (ID: #{tweet.id}) (#{tweet.lang})"
            rClient.update("@#{tweet.user.screen_name} Pithy response", in_reply_to_status_id: tweet.id)
          end
        end
      rescue Exception => e
        puts 'error occurred, waiting for 5 seconds' + e.class.to_s
        sleep 5
      end
    end
  end
end

I put the bot in a class, so it’s a classy bot. It also is a bot that will run FOREVER. I am also using a Gemfile and I set some environment variables for all the secret stuff. You can set those from the command line:

heroku config:set TWITTER_CONSUMER_KEY=SOSEKRET
etc…

Gemfile

The Gemfile is really simple. You just need the Twitter gem.

source "https://rubygems.org"
ruby '2.1.4'

gem "twitter"

bundle init is a quick and easy way to get a basic Gemfile that you can start adding stuff to. Those first 3 lines at the top of the script is how you require the contents of the Gemfile in a plain old ruby script. There is a big world that exists off-rails, and I recommend you check it out.

Make It Go

You now have everything that you need to make it go. You can do it in irb to see how it performs. I would recommend you comment out the line that makes the response until you’re sure it does what you want.

To run it in irb, set your environment variables, or copy the secret stuff into your script, and then run:

irb -r ./bot.rb

That’ll put you at the command prompt in irb where you can run Bot.go and watch it go.

What About Heroku?

Right, Heroku. If you push this as it is to Heroku, it won’t do anything. You need a Procfile. It looks like this:

bundle exec rake

Yes really.

Rake is awesome, and custom rake tasks are the bee’s knees. So let’s make one.

require './bot.rb'

desc "Bot!"
task :bot do
  Bot.go
end

task :default => 'bot'

There is a rake task bot, and the default rake task is set to that, so if you simply run bundle exec rake you get a running bot.

Push those 4 files to Heroku, and you’ve got yourself a twitter bot!

Leave a Comment

Filed under programming, ruby