We've seen how to create Tasks using the TaskRouter REST API and how to accept a Task Reservation using both the REST API and Assignment Callback instructions. TaskRouter also introduces new TwiML instructions that you can use to create a Task from a Twilio phone call.
To receive an incoming phone call, we first need a Twilio phone number. In this example we'll use a US toll-free number, but you can use a Voice capable number from any country.
Before purchasing or setting up the phone number, we need to add on to our server.rb
to handle incoming calls:
server.rb
1require 'rubygems'2require 'twilio-ruby'3require 'sinatra'4require 'json'56set :port, 808078# Get your Account Sid and Auth Token from twilio.com/user/account9account_sid = 'AC99ba7b61fbdb6c039698505dea5f044c'10auth_token = '{{ auth_token }}'11workspace_sid = '{{ workspace_sid }}'12workflow_sid = '{{ workflow_sid }}'1314client = Twilio::REST::Client.new(account_sid, auth_token)1516post '/assignment_callback' do17# Respond to assignment callbacks with accept instruction18content_type :json19{"instruction": "accept"}.to_json20end2122get '/create-task' do23# Create a task24task = client.taskrouter.workspaces(workspace_sid)25.tasks26.create(27attributes: {28'selected_language' => 'es'29}.to_json,30workflow_sid: workflow_sid31)32task.attributes33end3435get '/accept_reservation' do36# Accept a Reservation37task_sid = params[:task_sid]38reservation_sid = params[:reservation_sid]3940reservation = client.taskrouter.workspaces(workspace_sid)41.tasks(task_sid)42.reservations(reservation_sid)43.update(reservation_status: 'accepted')44reservation.worker_name45end4647get '/incoming_call' do48Twilio::TwiML::VoiceResponse.new do |r|49r.gather(action: '/enqueue_call', method: 'POST', timeout: 5, num_digits: 1) do |gather|50gather.say(message: 'Para Español oprime el uno.', language: 'es')51gather.say(message: 'For English, please hold or press two.', language: 'en')52end53end.to_s54end
You can use the Buy Numbers section of the Twilio Voice and Messaging web portal to purchase a new phone number, or use an existing Twilio phone number. Open the phone number details page and point the Voice Request URL at your new endpoint:
Using any phone, call the Twilio number. You will be prompted to press one for Spanish or two for English. However, when you press a digit, you'll hear an error message. That's because our <Gather>
verb is pointing to another endpoint, /enqueue_call
, which we haven't implemented yet. In the next step, we'll add the required endpoint and use it to create a new Task based on the language selected by the caller.