ChirpUserStreamsをrubyで試す

Twitterの新しいStreaming API「ChirpUserStreams」がすごすぎる件 - すぎゃーんメモ
Page not found | Twitter Developers
を見て自分もrubyでやってみた.

以前書いたTwitter Streaming APIで日本語のつぶやきを取得 - YarmUIの日記
とほとんど変わらないのでブロック付き関数で,TLかイベントが流れてきたらブロックが実行されるようにした.

require 'net/http'
require 'uri'
require 'kconv'
require 'json'
Net::HTTP.version_1_2

def chirp(id, pass)
  uri  = URI('http://chirpstream.twitter.com/2b/user.json')
  buf = ""
  http = Net::HTTP.start(uri.host, uri.port)
  req = Net::HTTP::Get.new(uri.request_uri)
  req.basic_auth id, pass
  http.request(req) do |res|
    res.read_body do |body|
      buf += body
      until (i = buf.index("\r\n")).nil?
        str =  buf.slice!(0, i + 2).chomp
        yield(JSON.parse(str)) unless str.size == 0
      end
    end
  end
end

if $0 == __FILE__
  chirp('id', 'pass') do |h|
    puts "#{h['user']['screen_name']}:#{h['text']}" if h.key?('text')
    puts "#{h['event']}:#{h}" if h.key?('event')
  end
end

こんな感じで流れてきます.
f:id:YarmUI:20100423211512p:image

追記:2010年4月25日
require 'kconv'いらねー