weibo_publish_agent.rb 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # encoding: utf-8
  2. module Agents
  3. class WeiboPublishAgent < Agent
  4. include WeiboConcern
  5. cannot_be_scheduled!
  6. description <<-MD
  7. #{'## Include `weibo_2` in your Gemfile to use this Agent!' if dependencies_missing?}
  8. The WeiboPublishAgent publishes tweets from the events it receives.
  9. You must first set up a Weibo app and generate an `acess_token` for the user to send statuses as.
  10. Include that in options, along with the `app_key` and `app_secret` for your Weibo app. It's useful to also include the Weibo user id of the person to publish 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['uid'].present? &&
  16. options['expected_update_period_in_days'].present?
  17. errors.add(:base, "expected_update_period_in_days and uid are required")
  18. end
  19. end
  20. def working?
  21. event_created_within?(interpolated['expected_update_period_in_days']) && most_recent_event.payload['success'] == true && !recent_error_logs?
  22. end
  23. def default_options
  24. {
  25. 'uid' => "",
  26. 'access_token' => "---",
  27. 'app_key' => "---",
  28. 'app_secret' => "---",
  29. 'expected_update_period_in_days' => "10",
  30. 'message_path' => "text"
  31. }
  32. end
  33. def receive(incoming_events)
  34. # if there are too many, dump a bunch to avoid getting rate limited
  35. if incoming_events.count > 20
  36. incoming_events = incoming_events.first(20)
  37. end
  38. incoming_events.each do |event|
  39. tweet_text = Utils.value_at(event.payload, interpolated(event)['message_path'])
  40. if event.agent.type == "Agents::TwitterUserAgent"
  41. tweet_text = unwrap_tco_urls(tweet_text, event.payload)
  42. end
  43. begin
  44. publish_tweet tweet_text
  45. create_event :payload => {
  46. 'success' => true,
  47. 'published_tweet' => tweet_text,
  48. 'agent_id' => event.agent_id,
  49. 'event_id' => event.id
  50. }
  51. rescue OAuth2::Error => e
  52. create_event :payload => {
  53. 'success' => false,
  54. 'error' => e.message,
  55. 'failed_tweet' => tweet_text,
  56. 'agent_id' => event.agent_id,
  57. 'event_id' => event.id
  58. }
  59. end
  60. end
  61. end
  62. def publish_tweet text
  63. weibo_client.statuses.update text
  64. end
  65. def unwrap_tco_urls text, tweet_json
  66. tweet_json[:entities][:urls].each do |url|
  67. text.gsub! url[:url], url[:expanded_url]
  68. end
  69. text
  70. end
  71. end
  72. end