Aucune description http://j1x-huginn.herokuapp.com

twitter_stream.rb 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #!/usr/bin/env ruby
  2. unless defined?(Rails)
  3. puts
  4. puts "Please run me with rails runner, for example:"
  5. puts " RAILS_ENV=production bundle exec rails runner bin/twitter_stream.rb"
  6. puts
  7. exit 1
  8. end
  9. require 'cgi'
  10. require 'json'
  11. require 'twitter/json_stream'
  12. require 'em-http-request'
  13. require 'pp'
  14. def stream!(filters, options = {}, &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. :oauth => {
  18. :consumer_key => options[:consumer_key],
  19. :consumer_secret => options[:consumer_secret],
  20. :access_key => options[:oauth_token] || options[:access_key],
  21. :access_secret => options[:oauth_token_secret] || options[:access_secret]
  22. },
  23. :ssl => true
  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.options[:twitter_username] }.each do |twitter_username, 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. options = agents.first.options.slice(:consumer_key, :consumer_secret, :access_key, :oauth_token, :access_secret, :oauth_token_secret)
  54. recent_tweets = []
  55. stream!(filter_to_agent_map.keys, options) do |status|
  56. if status["retweeted_status"].present? && status["retweeted_status"].is_a?(Hash)
  57. puts "Skipping retweet: #{status["text"]}"
  58. elsif recent_tweets.include?(status["id_str"])
  59. puts "Skipping duplicate tweet: #{status["text"]}"
  60. else
  61. recent_tweets << status["id_str"]
  62. recent_tweets.shift if recent_tweets.length > DUPLICATE_DETECTION_LENGTH
  63. puts status["text"]
  64. filter_to_agent_map.keys.each do |filter|
  65. if (filter.downcase.split(SEPARATOR) - status["text"].downcase.split(SEPARATOR)).reject(&:empty?) == [] # Hacky McHackerson
  66. filter_to_agent_map[filter].each do |agent|
  67. puts " -> #{agent.name}"
  68. agent.process_tweet(filter, status)
  69. end
  70. end
  71. end
  72. end
  73. end
  74. end
  75. end
  76. RELOAD_TIMEOUT = 10.minutes
  77. DUPLICATE_DETECTION_LENGTH = 1000
  78. SEPARATOR = /[^\w_\-]+/
  79. while true
  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 5
  98. puts "done."
  99. rescue SignalException, SystemExit
  100. EventMachine::stop_event_loop if EventMachine.reactor_running?
  101. exit
  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