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.

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\":\"accept\"}";
                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;
        }
    }
}

Now call your Twilio phone number. When prompted, press one for Spanish. You should hear Twilio's default 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"?>
<Response>
  <Enqueue workflowSid="WW0123401234...">
    <Task>{"selected_language": "es"}</Task>
  </Enqueue>
</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. 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 »

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.