twitter_publish_agent.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. 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 specify a `message` parameter, you can use [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to format the message.
  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. def validate_options
  16. errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present?
  17. end
  18. def working?
  19. event_created_within?(interpolated['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs?
  20. end
  21. def default_options
  22. {
  23. 'expected_update_period_in_days' => "10",
  24. 'message' => "{{text}}"
  25. }
  26. end
  27. def receive(incoming_events)
  28. # if there are too many, dump a bunch to avoid getting rate limited
  29. if incoming_events.count > 20
  30. incoming_events = incoming_events.first(20)
  31. end
  32. incoming_events.each do |event|
  33. tweet_text = interpolated(event.payload)['message']
  34. begin
  35. tweet = publish_tweet tweet_text
  36. create_event :payload => {
  37. 'success' => true,
  38. 'published_tweet' => tweet_text,
  39. 'tweet_id' => tweet.id,
  40. 'agent_id' => event.agent_id,
  41. 'event_id' => event.id
  42. }
  43. rescue Twitter::Error => e
  44. create_event :payload => {
  45. 'success' => false,
  46. 'error' => e.message,
  47. 'failed_tweet' => tweet_text,
  48. 'agent_id' => event.agent_id,
  49. 'event_id' => event.id
  50. }
  51. end
  52. end
  53. end
  54. def publish_tweet(text)
  55. twitter.update(text)
  56. end
  57. end
  58. end