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
_54require 'rubygems'_54require 'twilio-ruby'_54require 'sinatra'_54require 'json'_54_54set :port, 8080_54_54# Get your Account Sid and Auth Token from twilio.com/user/account_54account_sid = 'AC99ba7b61fbdb6c039698505dea5f044c'_54auth_token = '{{ auth_token }}'_54workspace_sid = '{{ workspace_sid }}'_54workflow_sid = '{{ workflow_sid }}'_54_54client = Twilio::REST::Client.new(account_sid, auth_token)_54_54post '/assignment_callback' do_54 # Respond to assignment callbacks with accept instruction_54 content_type :json_54 {"instruction": "accept"}.to_json_54end_54_54get '/create-task' do_54 # Create a task_54 task = client.taskrouter.workspaces(workspace_sid)_54 .tasks_54 .create(_54 attributes: {_54 'selected_language' => 'es'_54 }.to_json,_54 workflow_sid: workflow_sid_54 )_54 task.attributes_54end_54_54get '/accept_reservation' do_54 # Accept a Reservation_54 task_sid = params[:task_sid]_54 reservation_sid = params[:reservation_sid]_54_54 reservation = client.taskrouter.workspaces(workspace_sid)_54 .tasks(task_sid)_54 .reservations(reservation_sid)_54 .update(reservation_status: 'accepted')_54 reservation.worker_name_54end_54_54get '/incoming_call' do_54 Twilio::TwiML::VoiceResponse.new do |r|_54 r.gather(action: '/enqueue_call', method: 'POST', timeout: 5, num_digits: 1) do |gather|_54 gather.say(message: 'Para Español oprime el uno.', language: 'es')_54 gather.say(message: 'For English, please hold or press two.', language: 'en')_54 end_54 end.to_s_54end
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.