Twitter Ruby Gem

I been playing around with writing my own Twitter bot and client to backup my tweet feed and other natural language processing experiments. The good thing is that there are a ton of Twitter libraries in a wide variety of programming languages. At first I picked up a Java library, Twitter4J, but then quickly opted for a Ruby version instead because I just didn’t want to create large enterprise application before I can process with my Twitter timeline. As of this writing, Ruby has two good Twitter gems, Twitter4R and Twitter. I opted to use Twitter since it also has support for identi.ca micro blogging service.

Before you can get started, you need to have the Twitter gem installed.

sudo gem install twitter

Require the Twitter gem to start using it in your Ruby scripts.

require 'rubygems'
require 'yaml'
require 'twitter'

To access your Twitter account you will need to log in via your Twitter account username and password. For this example, I keep the login information in a yaml file. If you are more security conscious you might want to prompt for the password at run time or maybe simply encrypt it instead of keeping in a plain text file. That said, here is how to sign in…

tweet = YAML::load(File.open('tweet.yml'))
twitter = Twitter::Base.new(tweet['username'], tweet['password'])

That is it, to get your 100 most recent followers you can do so with the following.

twitter.followers().each { |f|
  puts f.name
}

To get the second page, the next 100 most recent followers, just add the :page argument, such as the following

twitter.followers(:page => 2).each { |f|
  puts f.name
}

The #followers method returns a list of Twitter users. The following attributes are present for users, id, name, screen_name, location, description, url, and profile_image_url. Users may also have values for the following attributes such as profile_background_color, profile_text_color, profile_link_color, friends_count, followers_count, statuses_count, status, amongst others.

The Ruby Twitter gem exposes not just your followers but it allows you to query all replies and favorites, allows you to search twitter public stream, update your location, send direct message, and update your status.

The author of this gem has posted a ton of useful examples with functional sample code on his GitHub account. That should get any butting Twitter bot author up and running. It would also be a good idea to be familiar with the public and official Twitter API since this gem maps nicely on top of that public API.


10 Responses to “Twitter Ruby Gem”

Leave a Reply