twitter_publish_agent.rb 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. require "twitter"
  2. module Agents
  3. class TwitterPublishAgent < Agent
  4. include TwitterConcern
  5. cannot_be_scheduled!
  6. description <<-MD
  7. The TwitterPublishAgent publishes tweets from the events it receives.
  8. You [must set up a Twitter app](https://github.com/cantino/huginn/wiki/Getting-a-twitter-oauth-token) and provide it's `consumer_key`, `consumer_secret`, `oauth_token` and `oauth_token_secret`,
  9. (also knows as "Access token" on the Twitter developer's site), along with the `username` of the Twitter user to publish as.
  10. The `oauth_token` and `oauth_token_secret` determine which user the tweet will be sent as.
  11. You must also specify a `message_path` parameter: a [JSONPaths](http://goessner.net/articles/JsonPath/) to the value to tweet.
  12. 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.
  13. MD
  14. def validate_options
  15. unless options['username'].present? &&
  16. options['expected_update_period_in_days'].present?
  17. errors.add(:base, "username and expected_update_period_in_days are required")
  18. end
  19. end
  20. def working?
  21. event_created_within?(options['expected_update_period_in_days']) && most_recent_event.payload['success'] == true && !recent_error_logs?
  22. end
  23. def default_options
  24. {
  25. 'username' => "",
  26. 'expected_update_period_in_days' => "10",
  27. 'consumer_key' => "---",
  28. 'consumer_secret' => "---",
  29. 'oauth_token' => "---",
  30. 'oauth_token_secret' => "---",
  31. 'message_path' => "text"
  32. }
  33. end
  34. def receive(incoming_events)
  35. # if there are too many, dump a bunch to avoid getting rate limited
  36. if incoming_events.count > 20
  37. incoming_events = incoming_events.first(20)
  38. end
  39. incoming_events.each do |event|
  40. tweet_text = Utils.value_at(event.payload, options['message_path'])
  41. begin
  42. publish_tweet tweet_text
  43. create_event :payload => {
  44. 'success' => true,
  45. 'published_tweet' => tweet_text,
  46. 'agent_id' => event.agent_id,
  47. 'event_id' => event.id
  48. }
  49. rescue Twitter::Error => e
  50. create_event :payload => {
  51. 'success' => false,
  52. 'error' => e.message,
  53. 'failed_tweet' => tweet_text,
  54. 'agent_id' => event.agent_id,
  55. 'event_id' => event.id
  56. }
  57. end
  58. end
  59. end
  60. def publish_tweet text
  61. Twitter.update(text)
  62. end
  63. end
  64. end