Friday, August 12, 2011

A "Hello World" Twitter client with OAuth

Last year I wrote a Twitter client that allows you to tweet on any webpage in the browser. Shortly after I released it, Twitter abolished BASIC authentication and my Twitter client was not working any longer because of it. The age of OAuth has come, but I haven't done anything about it.

Now I've started working on OAuth stuff again. I took a look at some blog entries and tried to build my first "Hello World" progarm for Twitter API with OAuth. This looked simple but it took me some time to write it. I will show you a few steps on how to write a Twitter client with OAuth in Ruby.

As a prerequisite, you need to have two Ruby gem packages installed on your system. If not, run the following commands on the terminal:

sudo gem install oauth
sudo gem install twitter

1. Get a consumer key and a consumer secret by registering your client at Twitter's website.

2. Have the users authorize your Twitter client to use their account

Type "irb" to start irb on the terminal. Copy and paste the below(double-click on the pane and you can copy and paste more easily):

require 'rubygems'
require 'oauth'

CONSUMER_KEY = "(your consumer key)"
CONSUMER_SECRET = "(your consumer secret)" 

consumer =, CONSUMER_SECRET, :site => "")

request_token = consumer.get_request_token 

Navigate to the URL for user authorization and have users to authorize your client to access to their account information.(Most likely, your client's first user is yourself. If so, authorize your client to access to your own Twitter account).

3. Get OAuth token and secret to access to the account information of your Twitter client users.

Keep entering the below on the irb session:

require 'twitter'

oauth_verifier = "(a number shown on the user authorization screen)" 

access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier )
token = access_token.token
secret = access_token.secret

Twitter.configure do |config|
  config.consumer_key = CONSUMER_KEY 
  config.consumer_secret = CONSUMER_SECRET
  config.oauth_token = token
  config.oauth_token_secret = secret 

Twitter.update("Hello World!")

Congratulations! Now you should be able to see a tweet with "Hello World" posted to the authorized account.

1 comment:

Anonymous said...

Thanks a lot for this tutorial, literally saved me hours of frustration!