Keine Beschreibung http://j1x-huginn.herokuapp.com

twitter_action_agent.rb 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. module Agents
  2. class TwitterActionAgent < Agent
  3. include TwitterConcern
  4. cannot_be_scheduled!
  5. description <<-MD
  6. The Twitter Action Agent is able to retweet or favorite tweets from the events it receives.
  7. #{ twitter_dependencies_missing if dependencies_missing? }
  8. It expects to consume events generated by twitter agents where the payload is a hash of tweet information. The existing TwitterStreamAgent is one example of a valid event producer for this Agent.
  9. To be able to use this Agent you need to authenticate with Twitter in the [Services](/services) section first.
  10. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent.
  11. Set `retweet` to either true or false.
  12. Set `favorite` to either true or false.
  13. MD
  14. def validate_options
  15. unless options['expected_receive_period_in_days'].present?
  16. errors.add(:base, "expected_receive_period_in_days is required")
  17. end
  18. unless retweet? || favorite?
  19. errors.add(:base, "at least one action must be true")
  20. end
  21. end
  22. def working?
  23. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  24. end
  25. def default_options
  26. {
  27. 'expected_receive_period_in_days' => '2',
  28. 'favorite' => 'false',
  29. 'retweet' => 'true',
  30. }
  31. end
  32. def retweet?
  33. boolify(options['retweet'])
  34. end
  35. def favorite?
  36. boolify(options['favorite'])
  37. end
  38. def receive(incoming_events)
  39. tweets = tweets_from_events(incoming_events)
  40. begin
  41. twitter.favorite(tweets) if favorite?
  42. twitter.retweet(tweets) if retweet?
  43. rescue Twitter::Error => e
  44. create_event :payload => {
  45. 'success' => false,
  46. 'error' => e.message,
  47. 'tweets' => Hash[tweets.map { |t| [t.id, t.text] }],
  48. 'agent_ids' => incoming_events.map(&:agent_id),
  49. 'event_ids' => incoming_events.map(&:id)
  50. }
  51. end
  52. end
  53. def tweets_from_events(events)
  54. events.map do |e|
  55. Twitter::Tweet.new(id: e.payload["id"], text: e.payload["text"])
  56. end
  57. end
  58. end
  59. end