Dynamic Call Center with Ruby and Rails

In this tutorial we will show how to automate the routing of calls from customers to your support agents. In this example customers would select a product, then be connected to a specialist for that product. If no one is available our customer's number will be saved so that our agent can call them back.

Create, Setup and Configure the Workspace

Before creating a workspace, we need to delete any others with the same friendly_name as the one we are trying to create. In order to create a workspace we need to provide a friendly_name and a callback_url where a requests will be made every time an event is triggered in our workspace.

See how to create a new workspace

We'll create two workers, Bob and Alice. They each have two attributes: contact_uri a phone number and products, a list of products each worker is specialized in. We also need to specify an activity_sid and a name for each worker. The selected activity will define the status of the worker.

A set of default activities is created with your workspace. We use the Idle activity to make a worker available for incoming calls.

assignment_callback_url and fallback_assignment_callback_url as the public URL where a request will be made when this Workflow assigns a Task to a Worker. We will learn how to implement it on the next steps.

task_reservation_timeout as the maximum time we want to wait until a Worker is available for handling a Task.

configuration which is a set of rules for placing Tasks into Task Queues. The routing configuration will take a Task's attribute and match this with Task Queues. This application's Workflow rules are defined as:

"selected_product==\ "ProgrammableSMS\"" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.

The endpoint will then process the request and generate a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.

moduleTwimlGeneratordefself.generate_gather_product(callback_url)response=Twilio::TwiML::VoiceResponse.newgather=Twilio::TwiML::Gather.new(num_digits:1,action:callback_url,method:'POST')gather.say'Welcome to the Twilio support line!'gather.say'To get specialized help with programmable voice press 1, '\'or press 2 for programmable SMS'response.append(gather)response.to_senddefself.generate_task_enqueue(selected_product)enqueue=Twilio::TwiML::Enqueue.new(nil,workflow_sid:WorkspaceInfo.instance.workflow_sid)enqueue.task"{\"selected_product\": \"#{selected_product}\"}"response=Twilio::TwiML::VoiceResponse.newresponse.append(enqueue)response.to_senddefself.generate_confirm_message(status)response=Twilio::TwiML::MessagingResponse.newresponse.message(body:"Your status has changed to #{status}")response.to_sendend

lib/twiml_generator.rb

Handle Incoming Call

lib/twiml_generator.rb

We just asked the caller to choose a product, next we will use their choice to create the appropiate Task.

This is the endpoint set as the action URL on the Gather verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits parameter that holds the pressed keys. A Task will be created based on the pressed digit with the selected_product as an attribute. The Workflow will take this Task's attributes and match them with the configured expressions in order to find a Task Queue for this Task, so an appropriate available Worker can be assigned to handle it.

We use the Enqueue verb with a WorkflowSid attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.

moduleTwimlGeneratordefself.generate_gather_product(callback_url)response=Twilio::TwiML::VoiceResponse.newgather=Twilio::TwiML::Gather.new(num_digits:1,action:callback_url,method:'POST')gather.say'Welcome to the Twilio support line!'gather.say'To get specialized help with programmable voice press 1, '\'or press 2 for programmable SMS'response.append(gather)response.to_senddefself.generate_task_enqueue(selected_product)enqueue=Twilio::TwiML::Enqueue.new(nil,workflow_sid:WorkspaceInfo.instance.workflow_sid)enqueue.task"{\"selected_product\": \"#{selected_product}\"}"response=Twilio::TwiML::VoiceResponse.newresponse.append(enqueue)response.to_senddefself.generate_confirm_message(status)response=Twilio::TwiML::MessagingResponse.newresponse.message(body:"Your status has changed to #{status}")response.to_sendend

lib/twiml_generator.rb

Create a Task

lib/twiml_generator.rb

After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.

At the same time the Reservation is created, a POST request is made to the Workflow's AssignmentCallbackURL, which was configured using the WorkspaceConfig class when the application is initialized. This request includes the full details of the Task, the selected Worker, and the Reservation.

Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, e-mail, push notifications or make a call.

Since we created this Task during a voice call with an Enqueue verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to parameter with a phone number, TaskRouter will pick the Worker's contact_uri attribute.

We also send a post_work_activity_sid which will tell TaskRouter which Activity to assign this worker after the call ends.

classCallbackController<ApplicationControllerskip_before_filter:verify_authenticity_tokendefassignmentinstruction={instruction:'dequeue',post_work_activity_sid:WorkspaceInfo.instance.post_work_activity_sid}renderjson:instructionenddefeventsevent_type=params[:EventType]if['workflow.timeout','task.canceled'].include?(event_type)task_attributes=JSON.parse(params[:TaskAttributes])MissedCall.create(selected_product:task_attributes['selected_product'],phone_number:task_attributes['from'])redirect_to_voicemail(task_attributes['call_sid'])ifevent_type=='workflow.timeout'elsifevent_type=='worker.activity.update'&&params[:WorkerActivityName]=='Offline'worker_attributes=JSON.parse(params[:WorkerAttributes])notify_offline_status(worker_attributes['contact_uri'])endrendernothing:trueendprivatedefredirect_to_voicemail(call_sid)email=ENV['MISSED_CALLS_EMAIL_ADDRESS']message='Sorry, All agents are busy. Please leave a message. We\'ll call you as soon as possible'url_message={Message:message}.to_queryredirect_url="http://twimlets.com/voicemail?Email=#{email}&#{url_message}"client.calls(call_sid).update(url:redirect_url)enddefnotify_offline_status(phone_number)message='Your status has changed to Offline. Reply with '\'"On" to get back Online'client.messages.create(to:phone_number,from:ENV['TWILIO_NUMBER'],body:message)enddefclientTwilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'],ENV['TWILIO_AUTH_TOKEN'])endend

app/controllers/callback_controller.rb

Assign a Worker

app/controllers/callback_controller.rb

Now that our Tasks are routed properly, let's deal with missed calls in the next step.

This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.

Here we use TwilioRestClient to route this call to a Voicemail Twimlet. Twimlets are tiny web applications for voice. This one will generate a TwiML response using Say verb and record a message using Record verb. The recorded message will then be transcribed and sent to the email address configured.

Note that we are also listening for task.canceled. This is triggered when the customer hangs up before being assigned to an agent, therefore canceling the task. Capturing this event allows us to collect the information from the customers that hang up before the Workflow times out.

classCallbackController<ApplicationControllerskip_before_filter:verify_authenticity_tokendefassignmentinstruction={instruction:'dequeue',post_work_activity_sid:WorkspaceInfo.instance.post_work_activity_sid}renderjson:instructionenddefeventsevent_type=params[:EventType]if['workflow.timeout','task.canceled'].include?(event_type)task_attributes=JSON.parse(params[:TaskAttributes])MissedCall.create(selected_product:task_attributes['selected_product'],phone_number:task_attributes['from'])redirect_to_voicemail(task_attributes['call_sid'])ifevent_type=='workflow.timeout'elsifevent_type=='worker.activity.update'&&params[:WorkerActivityName]=='Offline'worker_attributes=JSON.parse(params[:WorkerAttributes])notify_offline_status(worker_attributes['contact_uri'])endrendernothing:trueendprivatedefredirect_to_voicemail(call_sid)email=ENV['MISSED_CALLS_EMAIL_ADDRESS']message='Sorry, All agents are busy. Please leave a message. We\'ll call you as soon as possible'url_message={Message:message}.to_queryredirect_url="http://twimlets.com/voicemail?Email=#{email}&#{url_message}"client.calls(call_sid).update(url:redirect_url)enddefnotify_offline_status(phone_number)message='Your status has changed to Offline. Reply with '\'"On" to get back Online'client.messages.create(to:phone_number,from:ENV['TWILIO_NUMBER'],body:message)enddefclientTwilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'],ENV['TWILIO_AUTH_TOKEN'])endend

Collect Missed Calls

We have created this endpoint, so a worker can send an SMS message to the support line with the command "On" or "Off" to change their availability status.

This is important as a worker's activity will change to Offline when they miss a call. When this happens, they receive an SMS letting them know that their activity has changed, and that they can reply with the On command to make themselves available for incoming calls again.

moduleTwimlGeneratordefself.generate_gather_product(callback_url)response=Twilio::TwiML::VoiceResponse.newgather=Twilio::TwiML::Gather.new(num_digits:1,action:callback_url,method:'POST')gather.say'Welcome to the Twilio support line!'gather.say'To get specialized help with programmable voice press 1, '\'or press 2 for programmable SMS'response.append(gather)response.to_senddefself.generate_task_enqueue(selected_product)enqueue=Twilio::TwiML::Enqueue.new(nil,workflow_sid:WorkspaceInfo.instance.workflow_sid)enqueue.task"{\"selected_product\": \"#{selected_product}\"}"response=Twilio::TwiML::VoiceResponse.newresponse.append(enqueue)response.to_senddefself.generate_confirm_message(status)response=Twilio::TwiML::MessagingResponse.newresponse.message(body:"Your status has changed to #{status}")response.to_sendend

moduleTwimlGeneratordefself.generate_gather_product(callback_url)response=Twilio::TwiML::VoiceResponse.newgather=Twilio::TwiML::Gather.new(num_digits:1,action:callback_url,method:'POST')gather.say'Welcome to the Twilio support line!'gather.say'To get specialized help with programmable voice press 1, '\'or press 2 for programmable SMS'response.append(gather)response.to_senddefself.generate_task_enqueue(selected_product)enqueue=Twilio::TwiML::Enqueue.new(nil,workflow_sid:WorkspaceInfo.instance.workflow_sid)enqueue.task"{\"selected_product\": \"#{selected_product}\"}"response=Twilio::TwiML::VoiceResponse.newresponse.append(enqueue)response.to_senddefself.generate_confirm_message(status)response=Twilio::TwiML::MessagingResponse.newresponse.message(body:"Your status has changed to #{status}")response.to_sendend

classCallbackController<ApplicationControllerskip_before_filter:verify_authenticity_tokendefassignmentinstruction={instruction:'dequeue',post_work_activity_sid:WorkspaceInfo.instance.post_work_activity_sid}renderjson:instructionenddefeventsevent_type=params[:EventType]if['workflow.timeout','task.canceled'].include?(event_type)task_attributes=JSON.parse(params[:TaskAttributes])MissedCall.create(selected_product:task_attributes['selected_product'],phone_number:task_attributes['from'])redirect_to_voicemail(task_attributes['call_sid'])ifevent_type=='workflow.timeout'elsifevent_type=='worker.activity.update'&&params[:WorkerActivityName]=='Offline'worker_attributes=JSON.parse(params[:WorkerAttributes])notify_offline_status(worker_attributes['contact_uri'])endrendernothing:trueendprivatedefredirect_to_voicemail(call_sid)email=ENV['MISSED_CALLS_EMAIL_ADDRESS']message='Sorry, All agents are busy. Please leave a message. We\'ll call you as soon as possible'url_message={Message:message}.to_queryredirect_url="http://twimlets.com/voicemail?Email=#{email}&#{url_message}"client.calls(call_sid).update(url:redirect_url)enddefnotify_offline_status(phone_number)message='Your status has changed to Offline. Reply with '\'"On" to get back Online'client.messages.create(to:phone_number,from:ENV['TWILIO_NUMBER'],body:message)enddefclientTwilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'],ENV['TWILIO_AUTH_TOKEN'])endend

classCallbackController<ApplicationControllerskip_before_filter:verify_authenticity_tokendefassignmentinstruction={instruction:'dequeue',post_work_activity_sid:WorkspaceInfo.instance.post_work_activity_sid}renderjson:instructionenddefeventsevent_type=params[:EventType]if['workflow.timeout','task.canceled'].include?(event_type)task_attributes=JSON.parse(params[:TaskAttributes])MissedCall.create(selected_product:task_attributes['selected_product'],phone_number:task_attributes['from'])redirect_to_voicemail(task_attributes['call_sid'])ifevent_type=='workflow.timeout'elsifevent_type=='worker.activity.update'&&params[:WorkerActivityName]=='Offline'worker_attributes=JSON.parse(params[:WorkerAttributes])notify_offline_status(worker_attributes['contact_uri'])endrendernothing:trueendprivatedefredirect_to_voicemail(call_sid)email=ENV['MISSED_CALLS_EMAIL_ADDRESS']message='Sorry, All agents are busy. Please leave a message. We\'ll call you as soon as possible'url_message={Message:message}.to_queryredirect_url="http://twimlets.com/voicemail?Email=#{email}&#{url_message}"client.calls(call_sid).update(url:redirect_url)enddefnotify_offline_status(phone_number)message='Your status has changed to Offline. Reply with '\'"On" to get back Online'client.messages.create(to:phone_number,from:ENV['TWILIO_NUMBER'],body:message)enddefclientTwilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'],ENV['TWILIO_AUTH_TOKEN'])endend