require 'twilio-ruby'
require 'sanitize'
class TwilioController < ApplicationController
def ivr_welcome
response = Twilio::TwiML::VoiceResponse.new do |r|
phrase = "Welcome, Please Enter Survey Number"
r.say(phrase, voice: 'alice', language: 'en-GB')
gather = Twilio::TwiML::Gather.new(num_digits: '1', action: ivr_survey_path)
r.append(gather)
end
render xml: response.to_s
end
def survey
survey_id = params[:Digits]
@survey = Survey.find_by(id: survey_id)
if @survey.present?
session[params[:Caller]] = {}
questions = @survey.questions.unanswered
phrase = "All the questions will be asked one bye one, Please punch in your response"
questions.each do |question|
session[params[:Caller]][question.id] = question.question
end
response = Twilio::TwiML::VoiceResponse.new do |r|
r.say(phrase, voice: 'alice', language: 'en-GB')
r.redirect(ivr_questions_path)
end
else
phrase = "We can't find any survey with given number, Goodbye"
return twiml_say_and_hangup(phrase)
end
render xml: response.to_s
end
def questions
questions = session[params[:Caller]]
if questions.present? && questions.count > 0
question = questions.first
message = "#{question[1]}. Press 1 for yes, Press 2 for 'no'"
response = Twilio::TwiML::VoiceResponse.new do |r|
gather = Twilio::TwiML::Gather.new(num_digits: '1', action: ivr_answer_path(question_id: question[0]))
gather.say(message, voice: 'alice', language: 'en-GB', loop: 10)
r.append(gather)
end
else
phrase = "Thank you, The survey has been ended, Goodbye."
reset_session
return twiml_say_and_hangup(phrase)
end
render xml: response.to_s
end
def answer
question = Question.find_by(id: params[:question_id])
case params[:Digits]
when '1'
question.yes!
session[params[:Caller]].delete(question.id.to_s)
when '2'
question.no!
session[params[:Caller]].delete(question.id.to_s)
else
message = "Please Enter Valid Input"
end
response = Twilio::TwiML::VoiceResponse.new do |r|
r.redirect(ivr_questions_path)
end
render xml: response.to_s
end
end
private
def twiml_say_and_hangup(phrase)
response = Twilio::TwiML::VoiceResponse.new do |r|
r.say(phrase, voice: 'alice', language: 'en-GB')
r.hangup
end
render xml: response.to_s
end
end