2012-01-07 163 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