Create Tasks from Phone Calls using TwiML: Create a TaskRouter Task using <Enqueue>
In the previous step we received a call to a Twilio phone number and prompted the caller to select a preferred language, but the app wasn't ready to handle that input. To handle the caller's selection, create a new endpoint called enqueue_call and add the following code.
1# -*- coding: latin-1 -*-23from flask import Flask, request, Response4from twilio.rest import Client5from twilio.twiml.voice_response import VoiceResponse, Gather, Enqueue67app = Flask(__name__)89# Find your Account SID at twilio.com/console10# Provision API Keys at twilio.com/console/runtime/api-keys11account_sid = "{{ account_sid }}"12api_key = "{{ api_key }}"13api_secret = "{{ api_secret }}"14workspace_sid = "{{ workspace_sid }}"15workflow_sid = "{{ workflow_sid }}"1617client = Client(api_key, api_secret, account_sid)1819@app.route("/assignment_callback", methods=['GET', 'POST'])20def assignment_callback():21"""Respond to assignment callbacks with an acceptance and 200 response"""2223ret = '{"instruction": "accept"}'24resp = Response(response=ret, status=200, mimetype='application/json')25return resp2627@app.route("/create_task", methods=['GET', 'POST'])28def create_task():29"""Creating a Task"""30task = client.taskrouter.workspaces(workspace_sid) \31.tasks.create(workflow_sid=workflow_sid, attributes='{"selected_language":"es"}')3233print(task.attributes)34resp = Response({}, status=200, mimetype='application/json')35return resp3637@app.route("/accept_reservation", methods=['GET', 'POST'])38def accept_reservation(task_sid, reservation_sid):39"""Accepting a Reservation"""40task_sid = request.args.get('task_sid')41reservation_sid = request.args.get('reservation_sid')4243reservation = client.taskrouter.workspaces(workspace_sid) \44.tasks(task_sid) \45.reservations(reservation_sid) \46.update(reservation_status='accepted')4748print(reservation.reservation_status)49print(reservation.worker_name)5051resp = Response({}, status=200, mimetype='application/json')52return resp5354@app.route("/incoming_call", methods=['GET', 'POST'])55def incoming_call():56"""Respond to incoming requests."""5758resp = VoiceResponse()59gather = Gather(num_digits=1, action="/enqueue_call", method="POST", timeout=5)60gather.say("Para Español oprime el uno.", language='es')61gather.say("For English, please hold or press two.", language='en')62resp.append(gather)6364return str(resp)6566@app.route("/enqueue_call", methods=['GET', 'POST'])67def enqueue_call():68digit_pressed = request.args.get('Digits')69if digit_pressed == 1 :70language = "es"71else:72language = "en"7374resp = VoiceResponse()75enqueue = resp.enqueue(None, workflow_sid=workflow_sid)76enqueue.task('{"selected_language":"' + language + '"}')77resp.append(enqueue)7879return str(resp)8081if __name__ == "__main__":82app.run(debug=True)
Now call your Twilio phone number. When prompted, press one for Spanish. You should hear Twilio's default <Queue> hold music. Congratulations! You just added yourself to the 'Customer Care Requests - Spanish' Task Queue based on your selected language. To clarify how exactly this happened, look more closely at what is returned from enqueue_call to Twilio when our caller presses one:
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Enqueue workflowSid="WW0123401234...">4<Task>{"selected_language": "es"}</Task>5</Enqueue>6</Response>
Just like when we created a Task using the TaskRouter REST API (via curl), a Task has been created with an attribute field selected_language of value "es". This instructs the Workflow to add the Task to the 'Customer Care Requests - Spanish' TaskQueue based on the Routing Configurations we defined when we set up our Workflow. TaskRouter then starts monitoring for an available Worker to handle the Task.
Looking in the TaskRouter web portal, you will see the newly created Task in the Tasks section, and if you make an eligible Worker available, you should see them assigned to handle the Task. The app still needs a way to bridge the caller to the Worker when the Worker becomes available.
In the next section, we'll use a special Assignment Instruction to easily dequeue the call and route it to an eligible Worker - our good friend Alice. For now, you can hang up the call on hold.