Tuesday, July 12, 2011

Twitter OAuth authentication in Ruby

The hardest part of building this Twitter bot was getting it authenticated via OAuth. This is partly because the Ruby twitter gem is really easy to use. But this is mostly because the documentation and blog posts talking about authentication that I found were all incomplete or out of date. Therefore, I would like to present: how to connect to a Twitter account in Ruby, as of July 2011.

Essentially, you need to provide Twitter (or any OAuth-based service) with four things: your consumer key and secret, which identify your app; and a user's oauth token and secret, which identify a user who has authorized your app. In this case, that authorizing user will be the Twitter account the bot is posting from.

So first, you need your consumer key and secret. You get them by registering your app with Twitter at their developer site. The author of Chatterbot, a Twitter bot framework that unfortunately didn't do what I needed for this case, has a great walkthrough of the process.

Once that's set up, you can get your bot account's oauth token and secret. I'll walk it through using irb so it's more obvious what's going on.

First, install the relevant gems.
$ gem install oauth twitter
  
$ irb

Then, sign in to your bot account and get an authorization url.
irb> require "oauth"
  
irb> consumer = OAuth::Consumer.new("*your consumer key*", "*your consumer secret*", {:site => "https://twitter.com/"})
irb> request_token = consumer.get_request_token
irb> puts request_token.authorize_url

Go there and authorize your app! Once that's taken care of, you can finally get your bot account's oauth token and secret:

irb> access_token = request_token.get_access_token
irb> puts access_token.token
irb> puts access_token.secret

And now that you have all the information you need, you can set up a Twitter client with a minimum of fuss:

irb> require "twitter"
  
irb> Twitter.configure do |config|
irb>   config.consumer_key = "*your consumer key*"
irb>   config.consumer_secret = "*your consumer secret*"
irb>   config.oauth_token = "*your oauth token*"
irb>   config.oauth_token_secret = "*your oauth token secret*"
irb> end
  
irb> client = Twitter::Client.new

Now you can easily do lots of Twitter-related things with the client, like the awesome examples here.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.