1
0

jabber_agent.rb 2.1 KB

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