Skip to contentSkip to navigationSkip to topbar
Page tools
Useful for sharing or LLM

On this page
Looking for more inspiration?Visit the

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.


run.py

runpy page anchor

run.py

runpy-1 page anchor
1
# -*- coding: latin-1 -*-
2
3
from flask import Flask, request, Response
4
from twilio.rest import Client
5
from twilio.twiml.voice_response import VoiceResponse, Gather, Enqueue
6
7
app = Flask(__name__)
8
9
# Find your Account SID at twilio.com/console
10
# Provision API Keys at twilio.com/console/runtime/api-keys
11
account_sid = "{{ account_sid }}"
12
api_key = "{{ api_key }}"
13
api_secret = "{{ api_secret }}"
14
workspace_sid = "{{ workspace_sid }}"
15
workflow_sid = "{{ workflow_sid }}"
16
17
client = Client(api_key, api_secret, account_sid)
18
19
@app.route("/assignment_callback", methods=['GET', 'POST'])
20
def assignment_callback():
21
"""Respond to assignment callbacks with an acceptance and 200 response"""
22
23
ret = '{"instruction": "accept"}'
24
resp = Response(response=ret, status=200, mimetype='application/json')
25
return resp
26
27
@app.route("/create_task", methods=['GET', 'POST'])
28
def create_task():
29
"""Creating a Task"""
30
task = client.taskrouter.workspaces(workspace_sid) \
31
.tasks.create(workflow_sid=workflow_sid, attributes='{"selected_language":"es"}')
32
33
print(task.attributes)
34
resp = Response({}, status=200, mimetype='application/json')
35
return resp
36
37
@app.route("/accept_reservation", methods=['GET', 'POST'])
38
def accept_reservation(task_sid, reservation_sid):
39
"""Accepting a Reservation"""
40
task_sid = request.args.get('task_sid')
41
reservation_sid = request.args.get('reservation_sid')
42
43
reservation = client.taskrouter.workspaces(workspace_sid) \
44
.tasks(task_sid) \
45
.reservations(reservation_sid) \
46
.update(reservation_status='accepted')
47
48
print(reservation.reservation_status)
49
print(reservation.worker_name)
50
51
resp = Response({}, status=200, mimetype='application/json')
52
return resp
53
54
@app.route("/incoming_call", methods=['GET', 'POST'])
55
def incoming_call():
56
"""Respond to incoming requests."""
57
58
resp = VoiceResponse()
59
gather = Gather(num_digits=1, action="/enqueue_call", method="POST", timeout=5)
60
gather.say("Para Español oprime el uno.", language='es')
61
gather.say("For English, please hold or press two.", language='en')
62
resp.append(gather)
63
64
return str(resp)
65
66
@app.route("/enqueue_call", methods=['GET', 'POST'])
67
def enqueue_call():
68
digit_pressed = request.args.get('Digits')
69
if digit_pressed == 1 :
70
language = "es"
71
else:
72
language = "en"
73
74
resp = VoiceResponse()
75
enqueue = resp.enqueue(None, workflow_sid=workflow_sid)
76
enqueue.task('{"selected_language":"' + language + '"}')
77
resp.append(enqueue)
78
79
return str(resp)
80
81
if __name__ == "__main__":
82
app.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:


enqueue_call - TwiML Output

enqueue_call---twiml-output page anchor

enqueue_call TwiML output

enqueue_call-twiml-output page anchor
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.

Next: Dequeue a Call to a Worker »