From bd11e43dbcf464060ef526754deeb174bb0b9fa4 Mon Sep 17 00:00:00 2001 From: Rishabh Jain Date: Sat, 4 May 2013 18:55:02 +0530 Subject: [PATCH] Twilio Agent --- Gemfile | 1 + app/models/agents/twilio_agent.rb | 49 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 app/models/agents/twilio_agent.rb diff --git a/Gemfile b/Gemfile index 3678b948..9eabe41c 100644 --- a/Gemfile +++ b/Gemfile @@ -9,6 +9,7 @@ gem 'bootstrap-kaminari-views' gem "rufus-scheduler", :require => false gem 'json', '>= 1.7.7' gem 'jsonpath' +gem 'twilio-ruby' gem 'delayed_job', :git => 'https://github.com/wok/delayed_job' # Until the YAML issues are fixed in master. gem 'delayed_job_active_record', "~> 0.3.3" # newer was giving a strange MySQL error diff --git a/app/models/agents/twilio_agent.rb b/app/models/agents/twilio_agent.rb new file mode 100644 index 00000000..19781602 --- /dev/null +++ b/app/models/agents/twilio_agent.rb @@ -0,0 +1,49 @@ +require 'rubygems' +require 'twilio-ruby' + +module Agents + class TwilioAgent < Agent + + default_schedule "every_10m" + + description <<-MD + The TwilioAgent collects any events sent to it and send them via text message. + Add more info + MD + + def default_options + { + :account_sid => "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + :auth_token => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + :senderscell => "xxxxxxxxxx", + :receiverscell => "xxxxxxxxxx", + :expected_receive_period_in_days => "x" + } + end + + def validate_options + errors.add(:base, "account_sid,auth_token,senderscell,receiverscell are all required") unless options[:account_sid].present? && options[:auth_token].present? && options[:senderscell].present? && options[:receiverscell].present? && options[:expected_receive_period_in_days].present? + end + + def receive(incoming_events) + incoming_events.each do |event| + self.memory[:queue] ||= [] # If memory[:queue] is not true, assign [] to it, a || a = b + self.memory[:queue] << event.payload # Append + end + end + + def working? + last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago + end + + def check + if self.memory[:queue] && self.memory[:queue].length > 0 + @client = Twilio::REST::Client.new options[:account_sid],options[:auth_token] + self.memory[:queue].each do |text| + @client.account.sms.messages.create(:from=>options[:senderscell],:to=>options[:receiverscell],:body=>"#{text[:message]}") + end + self.memory[:queue] = [] + end + end + end +end \ No newline at end of file