eric buth

Getting an OAuth Token for your Twitter Bot

If you run a Twitter bot that uses a non-OAuth login pathway, you are going to be out of luck this coming August. With a web application that needs to publish or read from Twitter, OAuth is a good idea anyway because it keeps un-encrypted passwords out of your database and gives access control to the user on the service provider’s end. The burden of security in this scenario is mostly on Twitter, which is good for everyone.

The hangup, if you aren’t running a web application, is that the process involves several redirects with form data to exchange your application’s identifying information, prompt the Twitter user to allow access, and receive and store the resulting token. With no web application to handle such requests, a CLI bot needs an alternative (though one-time) method of obtaining a valid token.

After looking around for a while, I found this Ruby script (cleaned up below) which uses the twitter_oauth gem to walk you through the process.

require 'twitter_oauth'

client = TwitterOAuth::Client.new(
  :consumer_key     => 'TWITTER_CONSUMER_KEY',
  :consumer_secret  => 'TWITTER_CONSUMER_SECRET'
)
request_token = client.request_token

puts "#{request_token.authorize_url}\n"
puts "Hit enter when you have completed authorization."
pin = STDIN.readline.chomp

access_token = client.authorize(
  request_token.token,
  request_token.secret,
  :o auth_verifier => pin
)

puts access_token.inspect

When running the script, navigate to the URL it prints out and follow the on-screen instructions to obtain a PIN. Then return to the script, paste in the PIN, and press enter. The resulting variable dump will contain both a valid token and token secret that can be used in conjuction with your consumer information to connect to Twitter.

For example, you could now use grackle to make Twitter API calls:

require 'grackle'

TWITTER_AUTH = {
  :type             => :o auth,
  :consumer_key     => 'TWITTER_CONSUMER_KEY',
  :consumer_secret  => 'TWITTER_CONSUMER_SECRET',
  :token            => 'TOKEN',
  :token_secret     => 'TOKEN_SECRET'
}

client = Grackle::Client.new(:auth=>TWITTER_AUTH)

… and you’re set.