Rate this page:

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 when the caller selected their language, we weren't ready to handle that input. Let's fix that. Create a new endpoint called 'enqueue_call' and add the following code.

# -*- coding: latin-1 -*-

from flask import Flask, request, Response
from import Client
from twilio.twiml.voice_response import VoiceResponse, Gather, Enqueue

app = Flask(__name__)

# Your Account Sid and Auth Token from
account_sid = "{{ account_sid }}"
auth_token  = "{{ auth_token }}"
workspace_sid = "{{ workspace_sid }}"
workflow_sid = "{{ workflow_sid }}"

client = Client(account_sid, auth_token)

@app.route("/assignment_callback", methods=['GET', 'POST'])
def assignment_callback():
    """Respond to assignment callbacks with an acceptance and 200 response"""

    ret = '{"instruction": "accept"}'
    resp = Response(response=ret, status=200, mimetype='application/json')
    return resp

@app.route("/create_task", methods=['GET', 'POST'])
def create_task():
    """Creating a Task"""
    task = client.taskrouter.workspaces(workspace_sid) \
                 .tasks.create(workflow_sid=workflow_sid, attributes='{"selected_language":"es"}')

    resp = Response({}, status=200, mimetype='application/json')
    return resp

@app.route("/accept_reservation", methods=['GET', 'POST'])
def accept_reservation(task_sid, reservation_sid):
    """Accepting a Reservation"""
    task_sid = request.args.get('task_sid')
    reservation_sid = request.args.get('reservation_sid')

    reservation = client.taskrouter.workspaces(workspace_sid) \
                        .tasks(task_sid) \
                        .reservations(reservation_sid) \


    resp = Response({}, status=200, mimetype='application/json')
    return resp

@app.route("/incoming_call", methods=['GET', 'POST'])
def incoming_call():
    """Respond to incoming requests."""

    resp = VoiceResponse()
    gather = Gather(num_digits=1, action="/enqueue_call", method="POST", timeout=5)
    gather.say("Para Español oprime el uno.", language='es')
    gather.say("For English, please hold or press two.", language='en')

    return str(resp)

@app.route("/enqueue_call", methods=['GET', 'POST'])
def enqueue_call():
    digit_pressed = request.args.get('Digits')
    if digit_pressed == 1 :
        language = "es"
        language = "en"

    resp = VoiceResponse()
    enqueue = resp.enqueue(None, workflow_sid=workflow_sid)
    enqueue.task('{"selected_language":"' + language + '"}')

    return str(resp)

if __name__ == "__main__":

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

<?xml version="1.0" encoding="UTF-8"?>
  <Enqueue workflowSid="WW0123401234...">
    <Task>{"selected_language": "es"}</Task>

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. However, we don't yet have 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 »

Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

Loading Code Sample...

        Thank you for your feedback!

        Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!