Saturday, June 26, 2010

Twitter XAuth for Ruby scripts

This post explains very well what is going on:

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 = consumer_key, consumer_secret, {:site => ''}
hash.each do |k, v|
puts k
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}'
puts "exception: #{$!.message}"
puts '-----'
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 =, consumer_secret)
auth.authorize_from_access(@opts[:oauth_access_token], @opts[:oauth_access_secret])
twitter =