twitter_stream.rb 4.0KB

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