Nenhuma Descrição http://j1x-huginn.herokuapp.com

twitter_stream.rb 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. require 'cgi'
  2. require 'json'
  3. require 'twitter/json_stream'
  4. require 'em-http-request'
  5. require 'pp'
  6. class TwitterStream
  7. def initialize
  8. @running = true
  9. end
  10. def stop
  11. @running = false
  12. EventMachine::stop_event_loop if EventMachine.reactor_running?
  13. end
  14. def stream!(filters, agent, &block)
  15. stream = Twitter::JSONStream.connect(
  16. :path => "/1/statuses/#{(filters && filters.length > 0) ? 'filter' : 'sample'}.json#{"?track=#{filters.map {|f| CGI::escape(f) }.join(",")}" if filters && filters.length > 0}",
  17. :ssl => true,
  18. :oauth => {
  19. :consumer_key => agent.twitter_consumer_key,
  20. :consumer_secret => agent.twitter_consumer_secret,
  21. :access_key => agent.twitter_oauth_token,
  22. :access_secret => agent.twitter_oauth_token_secret
  23. }
  24. )
  25. stream.each_item do |status|
  26. status = JSON.parse(status) if status.is_a?(String)
  27. next unless status
  28. next if status.has_key?('delete')
  29. next unless status['text']
  30. status['text'] = status['text'].gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/[\t\n\r]/, ' ')
  31. block.call(status)
  32. end
  33. stream.on_error do |message|
  34. STDERR.puts " --> Twitter error: #{message} <--"
  35. end
  36. stream.on_no_data do |message|
  37. STDERR.puts " --> Got no data for awhile; trying to reconnect."
  38. EventMachine::stop_event_loop
  39. end
  40. stream.on_max_reconnects do |timeout, retries|
  41. STDERR.puts " --> Oops, tried too many times! <--"
  42. EventMachine::stop_event_loop
  43. end
  44. end
  45. def load_and_run(agents)
  46. agents.group_by { |agent| agent.twitter_oauth_token }.each do |oauth_token, agents|
  47. filter_to_agent_map = agents.map { |agent| agent.options[:filters] }.flatten.uniq.compact.map(&:strip).inject({}) { |m, f| m[f] = []; m }
  48. agents.each do |agent|
  49. agent.options[:filters].flatten.uniq.compact.map(&:strip).each do |filter|
  50. filter_to_agent_map[filter] << agent
  51. end
  52. end
  53. recent_tweets = []
  54. stream!(filter_to_agent_map.keys, agents.first) do |status|
  55. if status["retweeted_status"].present? && status["retweeted_status"].is_a?(Hash)
  56. puts "Skipping retweet: #{status["text"]}"
  57. elsif recent_tweets.include?(status["id_str"])
  58. puts "Skipping duplicate tweet: #{status["text"]}"
  59. else
  60. recent_tweets << status["id_str"]
  61. recent_tweets.shift if recent_tweets.length > DUPLICATE_DETECTION_LENGTH
  62. puts status["text"]
  63. filter_to_agent_map.keys.each do |filter|
  64. if (filter.downcase.split(SEPARATOR) - status["text"].downcase.split(SEPARATOR)).reject(&:empty?) == [] # Hacky McHackerson
  65. filter_to_agent_map[filter].each do |agent|
  66. puts " -> #{agent.name}"
  67. agent.process_tweet(filter, status)
  68. end
  69. end
  70. end
  71. end
  72. end
  73. end
  74. end
  75. RELOAD_TIMEOUT = 10.minutes
  76. DUPLICATE_DETECTION_LENGTH = 1000
  77. SEPARATOR = /[^\w_\-]+/
  78. def run
  79. while @running
  80. begin
  81. agents = Agents::TwitterStreamAgent.all
  82. EventMachine::run do
  83. EventMachine.add_periodic_timer(RELOAD_TIMEOUT) {
  84. puts "Reloading EventMachine and all Agents..."
  85. EventMachine::stop_event_loop
  86. }
  87. if agents.length == 0
  88. puts "No agents found. Will look again in a minute."
  89. sleep 60
  90. EventMachine::stop_event_loop
  91. else
  92. puts "Found #{agents.length} agent(s). Loading them now..."
  93. load_and_run agents
  94. end
  95. end
  96. print "Pausing..."; STDOUT.flush
  97. sleep 1
  98. puts "done."
  99. rescue SignalException, SystemExit
  100. @running = false
  101. EventMachine::stop_event_loop if EventMachine.reactor_running?
  102. rescue StandardError => e
  103. STDERR.puts "\nException #{e.message}:\n#{e.backtrace.join("\n")}\n\n"
  104. STDERR.puts "Waiting for a couple of minutes..."
  105. sleep 120
  106. end
  107. end
  108. end
  109. end