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