twitter_publish_agent.rb 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. require "twitter"
  2. module Agents
  3. class TwitterPublishAgent < Agent
  4. include TwitterConcern
  5. include LiquidInterpolatable
  6. cannot_be_scheduled!
  7. description <<-MD
  8. The TwitterPublishAgent publishes tweets from the events it receives.
  9. Twitter credentials must be supplied as either [credentials](/user_credentials) called
  10. `twitter_consumer_key`, `twitter_consumer_secret`, `twitter_oauth_token`, and `twitter_oauth_token_secret`,
  11. or as options to this Agent called `consumer_key`, `consumer_secret`, `oauth_token`, and `oauth_token_secret`.
  12. To get oAuth credentials for Twitter, [follow these instructions](https://github.com/cantino/huginn/wiki/Getting-a-twitter-oauth-token).
  13. You must also specify a `message` parameter, you can use [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to format the message.
  14. 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.
  15. MD
  16. def validate_options
  17. errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present?
  18. end
  19. def working?
  20. event_created_within?(options['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs?
  21. end
  22. def default_options
  23. {
  24. 'expected_update_period_in_days' => "10",
  25. 'message' => "{{text}}"
  26. }
  27. end
  28. def receive(incoming_events)
  29. # if there are too many, dump a bunch to avoid getting rate limited
  30. if incoming_events.count > 20
  31. incoming_events = incoming_events.first(20)
  32. end
  33. incoming_events.each do |event|
  34. tweet_text = interpolate_string(options['message'], event.payload)
  35. begin
  36. tweet = publish_tweet tweet_text
  37. create_event :payload => {
  38. 'success' => true,
  39. 'published_tweet' => tweet_text,
  40. 'tweet_id' => tweet.id,
  41. 'agent_id' => event.agent_id,
  42. 'event_id' => event.id
  43. }
  44. rescue Twitter::Error => e
  45. create_event :payload => {
  46. 'success' => false,
  47. 'error' => e.message,
  48. 'failed_tweet' => tweet_text,
  49. 'agent_id' => event.agent_id,
  50. 'event_id' => event.id
  51. }
  52. end
  53. end
  54. end
  55. def publish_tweet(text)
  56. twitter.update(text)
  57. end
  58. end
  59. end