twitter_user_agent.rb 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. require "twitter"
  2. module Agents
  3. class TwitterUserAgent < Agent
  4. include TwitterConcern
  5. cannot_receive_events!
  6. description <<-MD
  7. The TwitterUserAgent follows the timeline of a specified Twitter user.
  8. Twitter credentials must be supplied as either [credentials](/user_credentials) called
  9. `twitter_consumer_key`, `twitter_consumer_secret`, `twitter_oauth_token`, and `twitter_oauth_token_secret`,
  10. or as options to this Agent called `consumer_key`, `consumer_secret`, `oauth_token`, and `oauth_token_secret`.
  11. To get oAuth credentials for Twitter, [follow these instructions](https://github.com/cantino/huginn/wiki/Getting-a-twitter-oauth-token).
  12. You must also provide the `username` of the Twitter user to monitor.
  13. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent.
  14. MD
  15. event_description <<-MD
  16. Events are the raw JSON provided by the Twitter API. Should look something like:
  17. {
  18. ... every Tweet field, including ...
  19. "text": "something",
  20. "user": {
  21. "name": "Mr. Someone",
  22. "screen_name": "Someone",
  23. "location": "Vancouver BC Canada",
  24. "description": "...",
  25. "followers_count": 486,
  26. "friends_count": 1983,
  27. "created_at": "Mon Aug 29 23:38:14 +0000 2011",
  28. "time_zone": "Pacific Time (US & Canada)",
  29. "statuses_count": 3807,
  30. "lang": "en"
  31. },
  32. "retweet_count": 0,
  33. "entities": ...
  34. "lang": "en"
  35. }
  36. MD
  37. default_schedule "every_1h"
  38. def validate_options
  39. unless options['username'].present? &&
  40. options['expected_update_period_in_days'].present?
  41. errors.add(:base, "username and expected_update_period_in_days are required")
  42. end
  43. end
  44. def working?
  45. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  46. end
  47. def default_options
  48. {
  49. 'username' => "tectonic",
  50. 'expected_update_period_in_days' => "2"
  51. }
  52. end
  53. def check
  54. since_id = memory['since_id'] || nil
  55. opts = {:count => 200, :include_rts => true, :exclude_replies => false, :include_entities => true, :contributor_details => true}
  56. opts.merge! :since_id => since_id unless since_id.nil?
  57. tweets = twitter.user_timeline(options['username'], opts)
  58. tweets.each do |tweet|
  59. memory['since_id'] = tweet.id if !memory['since_id'] || (tweet.id > memory['since_id'])
  60. create_event :payload => tweet.attrs
  61. end
  62. save!
  63. end
  64. end
  65. end