jabber_agent.rb 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module Agents
  2. class JabberAgent < Agent
  3. include LiquidInterpolatable
  4. cannot_be_scheduled!
  5. cannot_create_events!
  6. description <<-MD
  7. The JabberAgent will send any events it receives to your Jabber/XMPP IM account.
  8. Specify the `jabber_server` and `jabber_port` for your Jabber server.
  9. The `message` is sent from `jabber_sender` to `jaber_receiver`. This message
  10. can contain any keys found in the source's payload, escaped using double curly braces.
  11. ex: `"News Story: {{title}}: {{url}}"`
  12. Have a look at the [Wiki](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to learn more about liquid templating.
  13. MD
  14. def default_options
  15. {
  16. 'jabber_server' => '127.0.0.1',
  17. 'jabber_port' => '5222',
  18. 'jabber_sender' => 'huginn@localhost',
  19. 'jabber_receiver' => 'muninn@localhost',
  20. 'jabber_password' => '',
  21. 'message' => 'It will be {{temp}} out tomorrow',
  22. 'expected_receive_period_in_days' => "2"
  23. }
  24. end
  25. def working?
  26. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  27. end
  28. def receive(incoming_events)
  29. incoming_events.each do |event|
  30. log "Sending IM to #{options['jabber_receiver']} with event #{event.id}"
  31. deliver body(event)
  32. end
  33. end
  34. def validate_options
  35. errors.add(:base, "server and username is required") unless credentials_present?
  36. end
  37. def deliver(text)
  38. client.send Jabber::Message::new(options['jabber_receiver'], text).set_type(:chat)
  39. end
  40. private
  41. def client
  42. Jabber::Client.new(Jabber::JID::new(options['jabber_sender'])).tap do |sender|
  43. sender.connect(options['jabber_server'], (options['jabber_port'] || '5222'))
  44. sender.auth(options['jabber_password'])
  45. end
  46. end
  47. def credentials_present?
  48. options['jabber_server'].present? && options['jabber_sender'].present? && options['jabber_receiver'].present?
  49. end
  50. def body(event)
  51. interpolate_string(options['message'], event.payload)
  52. end
  53. end
  54. end