2012-01-07 127 views
2

我想知道是否有使用Twitter流媒体API(https://dev.twitter.com/docs/streaming-api)的宝石?Rails的宝石Twitter的流媒体API

感谢

我发现这个宝石(https://github.com/jnunemaker/twitter),它看起来非常好,但不支持流API,不是吗?

回答

2

我在过去使用OAuth gem和EventMachine的组合来完成此操作。

require 'eventmachine' 
require 'em-http' 
require 'json' 
require 'oauth' 
require 'oauth/client/em_http' 

# Edit in your details. 
CONSUMER_KEY = your_key 
CONSUMER_SECRET = your_secret 
ACCESS_TOKEN = your_token 
ACCESS_TOKEN_SECRET = your_token_secret 

def twitter_oauth_consumer 
    @twitter_oauth_consumer ||= OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, :site => "http://twitter.com") 
end 

def twitter_oauth_access_token 
    @twitter_oauth_access_token ||= OAuth::AccessToken.new(twitter_oauth_consumer, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) 
end 

EventMachine.run do 
      toFollow=[twitter_id1, twitter_id2] 
     http = EventMachine::HttpRequest.new('http://stream.twitter.com/1/statuses/filter.json' 
).post(:body=>{"follow"=>toFollow.join(",")}, 
      :head => {"Content-Type" => "application/x-www-form-urlencoded"}, 
      :timeout => -1) do |client| 
      twitter_oauth_consumer.sign!(client, twitter_oauth_access_token) 
     end 

     buffer = "" 

     http.stream do |chunk| 
      buffer += chunk 
      while line = buffer.slice!(/.+\r?\n/) 
       puts "handling a new event:"+line 
      end 
     end 
     http.errback { puts "Error" } 
     http.disconnect { puts "Lost Connection" } 

end 

编辑 我修改基于this博客文章我的代码。

+0

顶部,你可以请加“捆绑安装....”行。我错过了一些宝石,不能测试你的脚本。谢谢 – fabian 2012-01-07 22:26:45

+0

'gem install eventmachine && gem install oauth'应该是你所需要的。如果它仍然不起作用,那么你也需要em-http-request。 – Gazler 2012-01-07 23:08:10

+1

非常感谢。但是,你发现这个宝石更加舒适https://github.com/intridea/tweetstream – fabian 2012-01-08 09:13:01