Wednesday, December 16, 2009

Handling the Twitter Stream API with Ruby

I've been doing a lot of things with the Twitter API lately. More on that another time though. I started messing around with their stream API last night. It's pretty fun to play with and I wanted to put the code up somewhere so I can use it later. Right now it works, but it clearly isn't very robust. It needs retry logic and better error handling. Right now, it's just a toy :)

You'll need the json gem installed. Once you have that you can run the script like...
./twitter_stream.rb <username> <password>

#!/usr/bin/env ruby
require 'rubygems'
require 'net/http'
require 'json'
http = Net::HTTP.new('stream.twitter.com', 80)
get = Net::HTTP::Get.new("/1/statuses/filter.json?track=awesome")
get.basic_auth ARGV[0], ARGV[1]
http.request(get) do |response|
text = ""
response.read_body do |chunk|
chunk.each_byte do |c|
if c == 10
if text.length > 1
begin
json = JSON.parse(text)
puts "#{json['user']['screen_name']}: #{json['text']}"
rescue Exception => e
puts "Unable to parse JSON:: #{e}"
end
text = ""
end
text = ""
else
text += c.chr
end
end
end
end