Create Tasks from Phone Calls using TwiML: Receive an Incoming Call
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:
1require 'rubygems'2require 'twilio-ruby'3require 'sinatra'4require 'json'56set :port, 808078# Find your Account SID at twilio.com/console9# Provision API Keys at twilio.com/console/runtime/api-keys10account_sid = 'AC99ba7b61fbdb6c039698505dea5f044c'11api_key = '{{ api_key }}'12api_secret = '{{ api_secret }}'13workspace_sid = '{{ workspace_sid }}'14workflow_sid = '{{ workflow_sid }}'1516client = Twilio::REST::Client.new(api_key, api_secret, account_sid)1718post '/assignment_callback' do19# Respond to assignment callbacks with accept instruction20content_type :json21{"instruction": "accept"}.to_json22end2324get '/create-task' do25# Create a task26task = client.taskrouter.workspaces(workspace_sid)27.tasks28.create(29attributes: {30'selected_language' => 'es'31}.to_json,32workflow_sid: workflow_sid33)34task.attributes35end3637get '/accept_reservation' do38# Accept a Reservation39task_sid = params[:task_sid]40reservation_sid = params[:reservation_sid]4142reservation = client.taskrouter.workspaces(workspace_sid)43.tasks(task_sid)44.reservations(reservation_sid)45.update(reservation_status: 'accepted')46reservation.worker_name47end4849get '/incoming_call' do50Twilio::TwiML::VoiceResponse.new do |r|51r.gather(action: '/enqueue_call', method: 'POST', timeout: 5, num_digits: 1) do |gather|52gather.say(message: 'Para Español oprime el uno.', language: 'es')53gather.say(message: 'For English, please hold or press two.', language: 'en')54end55end.to_s56end
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.