Create Tasks from Phone Calls using TwiML: Dequeue a Call to a Worker

In the previous step we created a Task from an incoming phone call using <Enqueue workflowSid="WW0123401234..">. In this step we will create another call and dequeue it to an eligible Worker when one becomes available.

Back in Part 1 of the Quickstart we created a Worker named Alice that is capable of handling both English and Spanish inquiries. With your Workspace open in the TaskRouter web portal, click 'Workers' and click to edit the details of our Worker Alice. Ensure that Alice is set to a non-available Activity state such as 'Offline'. Next, edit Alice's JSON attributes and add a "contact_uri" field. Replace the dummy 555 number below with your own phone number.

Alice's modified JSON attributes:

{"languages": ["en", "es"], "contact_uri": "+15555555555"}

Or, as displayed in the web portal:

In this step, we again use <Enqueue> to create a Task from an incoming phone call. When an eligible Worker (in this case Alice) becomes available, TaskRouter will make a request to our Assignment Callback URL. This time, we will respond with a special 'dequeue' instruction; this tells Twilio to call Alice at her 'contact_uri' and bridge to the caller.

For this part of the Quickstart, although not totally necessary it will be useful to have two phones available - one to call your Twilio number, and one to receive a call as Alice. Experienced Twilio users might consider using Twilio Client as one of the endpoints.

Before we add the 'dequeue' assignment instruction we need to create a new Activity in our TaskRouter Workspace. One of the nice things about integrating TaskRouter with TwiML is that our Worker will automatically transition through various Activities as the call is assigned, answered and even hung up. We need an Activity for our Worker to transition to when the call ends.

With your Workspace open in the TaskRouter web portal, click 'Activities' and then 'Create Activity'. Give the new Activity a name of 'WrapUp' and a value of 'unavailable'. Once you've saved it, make a note of the Activity Sid:

To return the 'dequeue' assignment instruction, modify Program.cs assignment_callback endpoint to now issue a dequeue instruction, substituting your new WrapUp ActivitySid between the curly braces:

Program.cs

using System;
using System.Net;
using SimpleWebServer;
using Twilio;
using Twilio.Rest.Taskrouter.V1.Workspace;
using Twilio.Rest.Taskrouter.V1.Workspace.Task;
using Twilio.TwiML;

namespace taskroutercsharp
{
    class MainClass
    {
        // Find your Account Sid and Auth Token at twilio.com/user/account
        const string AccountSid = "{{ account_sid }}";
        const string AuthToken = "{{ auth_token }}";
        const string WorkspaceSid = "{{ workspace_sid }}";
        const string WorkflowSid = "{{ workflow_sid }}";

        public static void Main (string[] args)
        {
            // Initialize the Twilio client
            TwilioClient.Init(AccountSid, AuthToken);

            WebServer ws = new WebServer (SendResponse, "http://localhost:8080/");
            ws.Run ();
            Console.WriteLine ("A simple webserver. Press a key to quit.");
            Console.ReadKey ();
            ws.Stop ();
        }

        public static HttpListenerResponse SendResponse(HttpListenerContext ctx)
        {
            HttpListenerRequest request = ctx.Request;
            HttpListenerResponse response = ctx.Response;

            String endpoint = request.RawUrl;

            if (endpoint.EndsWith("assignment_callback")) {
                response.StatusCode = (int) HttpStatusCode.OK;
                response.ContentType = "application/json";
                response.StatusDescription = "{\"instruction\":\"dequeue\", \"from\":\"+15556667777\", \"post_work_activity_sid\":\"WA0123401234...\"}";
                return response;
            } else if (endpoint.EndsWith ("create_task")) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.ContentType = "application/json";
                TaskResource task = TaskResource.Create(
                    WorkspaceSid,
                    attributes: "{\"selected_language\":\"es\"}",
                    workflowSid: WorkflowSid);

                response.StatusDescription = task.Attributes;
                return response;
            } else if (endpoint.EndsWith ("accept_reservation")) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.ContentType = "application/json";
                var taskSid = request.QueryString ["TaskSid"];
                var reservationSid = request.QueryString ["ReservationSid"];
                ReservationResource reservation = ReservationResource.Update(
                    WorkspaceSid,
                    taskSid,
                    reservationSid,
                    ReservationResource.StatusEnum.Accepted);

                response.StatusDescription = "{\"reservation_status\":\"" + reservation.ReservationStatus + "\"}";
                return response;
            } else if (endpoint.EndsWith ("incoming_call")) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.ContentType = "application/xml";
                var twiml = new VoiceResponse();
                twiml.Gather(new Gather(numDigits: 1, action: "enqueue_call")
                    .Say("Para Espanol oprima el uno.", language: "es")
                    .Say("For English, please hold or press two.", language: "en"));

                response.StatusDescription = twiml.ToString();
                return response;
            } else if (endpoint.Contains("enqueue_call")) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.ContentType = "application/xml";

                int digitPressed = 0;
                var language = "";
                var digitsQuery = request.QueryString["Digits"];
                if(digitsQuery != null) {
                    try
                    {
                        digitPressed = Int32.Parse(request.QueryString ["Digits"]);
                    } catch (FormatException e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                if (digitPressed == 1) {
                    language = "es";
                } else {
                    language = "en";
                }

                var twiml = new VoiceResponse();
                twiml.Enqueue(
                    "{\"selected_language\":" + language + "\"}", 
                    workflowSid: WorkflowSid);

                response.StatusDescription = twiml.ToString();
                return response;
            }
            response.StatusCode = (int) HttpStatusCode.OK;
            return response;
        }
    }
}

This returns a very simple JSON object from the Assignment Callback URL:

JSON Output

{"instruction":"dequeue", "from": "+15556667777", "post_work_activity_sid": "WA01234012340123401234"}

The JSON instructs Twilio to dequeue the waiting call and, because we don't include an explicit "to" field in our JSON, connect it to our Worker at their "contact_uri". This is convenient default behavior provided by TaskRouter.

In the next step, we test our incoming call flow from end-to-end.

Next: End-to-End Phone Call Task Assignment »

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 browsing the Twilio tag on Stack Overflow.