Leverage Twitter Features In Your Ruby Application With Twitter4R
Intro
A few years ago I integrated Twitter with a Ruby application, mainly to display a subset of my timeline.
Later I added the ability to post tweets. All this became possible using Susan Potter‘s “most-excellent” Twitter4R gem.
Back in late 2010, Twitter upgraded its API from simple id/password authentication to OAuth authentication. The Twitter4R gem was then also enhanced to leverage the OAuth-Ruby library. I had created a to-do item to go back and upgrade my apps so this past week I decided it was time to document the process in a quick tutorial!
Twitter4R Approach
When you register your client application with Twitter, you are assigned an App OAuth Token consisting of a consumer key and consumer secret pair. Your app will configure Twitter4R to use this app token during all API calls with Twitter.
Your app will also need to keep track of User OAuth Tokens and pass a specific user token through the API.
Behind the scene Twitter4R will perform REST calls to the actual Twitter API using JSON data.
If you only want your app to access your own account, you will create an Access Token for your Twitter account on your newly-registered app
Playing With Twitter4R In The Console
Installing Twitter4R
From a command window / shell, just run:
gem install oauth
Notice that both the Twitter4R and the OAuth gems are installed.
Registering Our App With Twitter
To obtain a consumer key and secret pair, we’ll need to register our application with Twitter at https://dev.twitter.com/apps. We will need to provide the following:
- The name of our app (which must be unique within Twitter’s app registry)
- A description
- The base url of our app
- The url to redirect authenticated users to in our app
- The type of access needed: read or read/write (if we want to be able to update our status)
Example:
Obtaining Your Own User OAuth Access Token
Once you have registered the app, if you click on the “My Access Token” button, Twitter will give your OAuth user key and secret token.
Example:
In another section we’ll see how to authorize a user and get its access token programmatically.
Testing Twitter4R In IRB
Let’s start a Ruby console using IRB and load Twitter4R:
gem 'twitter4r' require 'twitter' require 'twitter/console'
Now we can configure the Twitter4R client using the Twitter::Client.configure class method.
The block allows us to customize the application and its app OAuth token. Evaluate the following code snippet:
Twitter::Client.configure do |conf| # App configuration conf.application_name = 'BeaconPulse)))' conf.application_version = '1.0' conf.application_url = 'http://beaconpulse.heroku.com/' # App OAuth token key/secret pair conf.oauth_consumer_token = "***YourAppConsumerKeyFromYourTwitterAppRegistration***" conf.oauth_consumer_secret = "***YourAppConsumerSecretFromYourTwitterAppRegistration***" end
We can then inspect the resulting configuration using:
cfg = Twitter::Client.config
Instantiating A Twitter4RClient
We’ll use the user key/secret pair we looked up on the Twitter Access Token page earlier:
client = Twitter::Client.new(:oauth_access => { :key => "***YourUserOAuthAccessTokenKey***", :secret => "***YourUserOAuthAccessTokenPassword***" })
Taking Twitter Features For A Spin
Now that we have a client instance, we can exercise its various methods (see rdoc for details) such as:
- user information about a given account:
i = client.user 'techarch'
- my info / friends / followers:
fr = client.my :friends fo = client.my :followers
- timeline_for me / user / public / friends / :
tm = client.timeline_for :me tm1 = client.timeline_for :me, :count => 1 # my last tweet tu = client.timeline_for :user, :id => 'susanpotter' tp = client.timeline_for :public tf = client.timeline_for :friends
- post a status:
t = client.status :post, 'Posting tweets from IRB using the Twitter4R gem rocks!'
As you can see you can have a lot of fun with the client!
Authorizing A User And Getting Its Access Token
In an earlier section, we just looked up our own access token on the Twitter page for our app registration.
But to allow any user to access our app we would need to:
- Instantiate an OAuth Consumer (like Twitter4R does behind the scenes) with our app consumer key/secret pair:
# we reuse the cfg variable we set earlier since it contains our app configuration k = cfg.oauth_consumer_token s = cfg.oauth_consumer_secret u = "#{(cfg.protocol == :ssl ? :https : cfg.protocol).to_s}://#{cfg.host}:#{cfg.port}" oc = OAuth::Consumer.new(k ,s, :site=> u)
- Ask the OAuth consumer to:
- create an OAuth RequestToken (a temporary credential token used to authenticate our consumer app on Twitter)
- and give us an authorization url:
rt = oc.get_request_token auth_url = rt.authorize_url
We can actually paste this url in a browser.
- Redirect the user to the authorization url so that Twitter can prompt for authorization to access our app
- Once authorized, get the OAuth Verifier (a verification code which will be passed back to Twitter in subsequent requests)
- User the Request Token to retrieve an OAuth AccessToken (the actual authorized user token needed for all future API calls to Twitter) for the user based on the OAuth Verifier:
at = rt.get_access_token(:oauth_verifier=>'***ThePINnumberReturnedByTwitter***') user_key = at.token user_secret = at.secret
- Optionally store the user OAuth key/secret pair so we can instantiate a Twitter4R Client to invoke APIs on the user’s behalf:
client = Twitter::Client.new(:oauth_access => { :key => user_key, :secret => user_secret }) info = client.user 'techarch'
Approach For Integrating Twitter4R In Your App
Now that you have a handle on the basics using the Interactive Ruby Console, you can check out the full RDoc
and add Twitter support to your favorite Ruby app. In a future blog post I’ll cover the integration approach for a Ruby Camping web app.
Here is what the Twitter4R ecosystem looks like from 50,000 feet:
So What?
Since Twitter has moved to OAuth you need a robust and efficient library like Twitter4R to integrate Twitter in your application.
Twitter4R leverages the Twitter REST API using the JSON format to limit bandwith consumption.
The gem is “framework-neutral”, so it can be used in pure Ruby apps, as well as on top of frameworks such as Rails, Ruby-Camping, and Sinatra.
If you have not experimented with Twitter4R, hopefully this tutorial will get you started.
References and Resources
Twitter4R
- Twitter4R on GitHub
- Susan Potter’s blog
- “Configuring Your Twitter4R App With OAuth” by Susan Potter – on SlideShare
OAuth And My Other Related Posts:
- OAuth.net site
- OAuth Universe site
- OAuth Ruby on GitHub
- Transform Your Ruby Camping Web App Into An OAuth Provider (explains the OAuth “dance”!)
- Ruby Camping Framework