twitter_publish_agent.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Agents
  2. class TwitterPublishAgent < Agent
  3. include TwitterConcern
  4. cannot_be_scheduled!
  5. description <<-MD
  6. #{twitter_dependencies_missing if dependencies_missing?}
  7. The TwitterPublishAgent publishes tweets from the events it receives.
  8. To be able to use this Agent you need to authenticate with Twitter in the [Services](/services) section first.
  9. 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.
  10. 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.
  11. MD
  12. def validate_options
  13. errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present?
  14. end
  15. def working?
  16. event_created_within?(interpolated['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs?
  17. end
  18. def default_options
  19. {
  20. 'expected_update_period_in_days' => "10",
  21. 'message' => "{{text}}"
  22. }
  23. end
  24. def receive(incoming_events)
  25. # if there are too many, dump a bunch to avoid getting rate limited
  26. if incoming_events.count > 20
  27. incoming_events = incoming_events.first(20)
  28. end
  29. incoming_events.each do |event|
  30. tweet_text = interpolated(event)['message']
  31. begin
  32. tweet = publish_tweet tweet_text
  33. create_event :payload => {
  34. 'success' => true,
  35. 'published_tweet' => tweet_text,
  36. 'tweet_id' => tweet.id,
  37. 'agent_id' => event.agent_id,
  38. 'event_id' => event.id
  39. }
  40. rescue Twitter::Error => e
  41. create_event :payload => {
  42. 'success' => false,
  43. 'error' => e.message,
  44. 'failed_tweet' => tweet_text,
  45. 'agent_id' => event.agent_id,
  46. 'event_id' => event.id
  47. }
  48. end
  49. end
  50. end
  51. def publish_tweet(text)
  52. twitter.update(text)
  53. end
  54. end
  55. end