Aucune description http://j1x-huginn.herokuapp.com

twilio_agent.rb 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. require 'twilio-ruby'
  2. module Agents
  3. class TwilioAgent < Agent
  4. default_schedule "every_10m"
  5. description <<-MD
  6. The TwilioAgent receives and collects events and sends them via text message when scheduled.
  7. It is assumed that events have a `:message`, `:text`, or `:sms` key, the value of which is sent as the content of the text message. You can use Event Formatting Agent if your event does not provide these keys.
  8. Set `receiver_cell` to the number to receive text messages and `sender_cell` to the number sending them.
  9. `expected_receive_period_in_days` is maximum number of days that you would expect to pass between events being received by this agent.
  10. MD
  11. def default_options
  12. {
  13. :account_sid => 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  14. :auth_token => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  15. :sender_cell => 'xxxxxxxxxx',
  16. :receiver_cell => 'xxxxxxxxxx',
  17. :expected_receive_period_in_days => 'x'
  18. }
  19. end
  20. def validate_options
  21. unless options[:account_sid].present? && options[:auth_token].present? && options[:sender_cell].present? && options[:receiver_cell].present? && options[:expected_receive_period_in_days].present?
  22. errors.add(:base, 'account_sid, auth_token, sender_cell, receiver_cell, and expected_receive_period_in_days are all required')
  23. end
  24. end
  25. def receive(incoming_events)
  26. memory[:queue] ||= []
  27. incoming_events.each do |event|
  28. memory[:queue] << event.payload
  29. end
  30. end
  31. def working?
  32. last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago
  33. end
  34. def send_message(client, message)
  35. client.account.sms.messages.create(:from => options[:sender_cell], :to => options[:receiver_cell], :body => message)
  36. end
  37. def check
  38. if memory[:queue] && memory[:queue].length > 0
  39. @client = Twilio::REST::Client.new(options[:account_sid], options[:auth_token])
  40. memory[:queue].each do |text|
  41. message = text[:message] || text[:text] || text[:sms]
  42. if message
  43. message.slice! 160, message.length
  44. send_message @client, message
  45. end
  46. end
  47. memory[:queue] = []
  48. end
  49. end
  50. end
  51. end