Saturday, June 26, 2010

Twitter XAuth for Ruby scripts

This post explains very well what is going on:
http://www.reynoldsftw.com/2010/03/using-xauth-an-alternate-oauth-from-twitter/

Now, if you have a script to post to Twitter everytime an item is added in your Ruby CMS, you are wondering how to apply what Steve Reynolds suggests, aren't you?

1. register a Twitter application,
2. ask Twitter team to enable XAuth in such application. They'll enable it for a limited period of time.
3. use XAuth to create as many OAuth access tokens you need:
require 'oauth'
consumer = OAuth::Consumer.new consumer_key, consumer_secret, {:site => 'https://api.twitter.com'}
hash.each do |k, v|
puts k
begin
token = consumer.get_access_token(nil, {},
:x_auth_username => v[:username], :x_auth_password => v[:password], :x_auth_mode => client_auth')
puts %Q(
:oauth_access_token => '#{token.token}',
:oauth_access_secret => '#{token.secret}'
)
rescue
puts "exception: #{$!.message}"
end
puts '-----'
end
4. store the tokens everywhere you like (I casted them in an initializers)
5. initialize your Twitter client using OAuth and the stored tokens, for example:
auth = Twitter::OAuth.new(consumer_key, consumer_secret)
auth.authorize_from_access(@opts[:oauth_access_token], @opts[:oauth_access_secret])
twitter = Twitter::Base.new(auth)