简体   繁体   中英

Rails gem for Twitter Streaming API

I was wondering if there is a gem for using the Twitter Streaming API (https://dev.twitter.com/docs/streaming-api)?

Thanks

I found this gem (https://github.com/jnunemaker/twitter) which looks really good, but does not support the streaming api, does it?

您可以使用此方法:位于em-twitter上的Tweetstream

I have done this in the past using a combination of the OAuth gem and 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

EDIT I modified my code based on this blog post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM