1
0

jabber_agent.rb 2.2 KB

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