Accessing Twitter via the Interactive Ruby Shell (irb)

Systems Development

I was looking for a simple Ruby solution for updating messages through irb. I found these Ruby class options:

  • Twitter by John Nunemaker — this is the most complete one.
  • Twittery, a very simple class that uploads photos through the TwitPic API. The project is maintained by Chris Ledet.

I used the class from the Twittery project as a learning starting point because I wanted a quick and simple solution, even though it doesn’t have the security of the OAuth authentication protocol already included in John Nunemaker’s project.

The idea was to have the Ruby code preloaded from the .irbrc file every time irb was launched from the shell.

After several attempts, here’s the final code:

# twitting by irb
require 'net/http'

class Object
  def twitter_config(username, password)
    @username = username
    @password = password
  end

# the message must be between 1 and 160 characters
  def twitter(status = nil, format = 'json')
     if status.empty? or status.length > 160
        puts "twitter 'message with spaces'             (IRB)"
        puts "Obs. (The message must been less than 160 characters and cannot be empty)"
     else
        api_url = 'http://twitter.com/statuses/update.' + format
        url = URI.parse(api_url)
        req = Net::HTTP::Post.new(url.path)
        req.basic_auth(@username, @password)
        req.set_form_data({ 'status'=> status }, ';')
        res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
        puts res
     end
 end
alias :twit :twitter
end

twitter_config('username', 'password')

The username and password are preloaded when irb starts. The advantage is that these details are hidden in the .irbrc file, giving you a little privacy if someone is standing next to you. ;)

To “tweet,” just use this command at any time inside irb:

irb> twitter "message via irb"

# or

irb> twit "another message via irb"
Note: This example uses the simplest form of authentication, over HTTP. Twitter is in the process of moving to authentication with OAuth. Basic HTTP authentication will probably stop being used, but that will still take a while. Until then, I'll keep “tweeting” with this script through irb. ;)

That’s all for now.

See you next time.