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.
1import java.io.IOException;23import javax.servlet.ServletException;4import javax.servlet.http.HttpServlet;5import javax.servlet.http.HttpServletRequest;6import javax.servlet.http.HttpServletResponse;78import com.twilio.Twilio;9import com.twilio.rest.taskrouter.v1.workspace.Task;10import com.twilio.rest.taskrouter.v1.workspace.task.Reservation;11import com.twilio.twiml.*;12import com.twilio.twiml.voice.*;1314public class TwilioTaskRouterServlet extends HttpServlet {1516private String accountSid;17private String apiKey;18private String apiSecret;19private String workspaceSid;20private String workflowSid;2122@Override23public void init() {24accountSid = this.getServletConfig().getInitParameter("AccountSid");25apiKey = this.getServletConfig().getInitParameter("ApiKey");26apiSecret = this.getServletConfig().getInitParameter("ApiSecret");27workspaceSid = this.getServletConfig().getInitParameter("WorkspaceSid");28workflowSid = this.getServletConfig().getInitParameter("WorkflowSid");2930Twilio.init(apiKey, apiSecret, accountSid);31}3233// service() responds to both GET and POST requests.34// You can also use doGet() or doPost()35@Override36public void service(final HttpServletRequest request, final HttpServletResponse response)37throws IOException, ServletException {38if (request.getPathInfo() == null || request.getPathInfo().isEmpty()) {39return;40}4142if (request.getPathInfo().equals("/assignment_callback")) {43response.setContentType("application/json");44response.getWriter().print("{\"instruction\":\"accept\"}");45} else if (request.getPathInfo().equals("/create_task")) {46response.setContentType("application/json");47final String taskAttributes = createTask();48response.getWriter().print(createTask());49} else if (request.getPathInfo().equals("/accept_reservation")) {50response.setContentType("application/json");51final String taskSid = request.getParameter("TaskSid");52final String reservationSid = request.getParameter("ReservationSid");53response.getWriter().print(acceptReservation(taskSid, reservationSid));54} else if (request.getPathInfo().equals("/incoming_call")) {55response.setContentType("application/xml");56response.getWriter().print(handleIncomingCall());57} else if (request.getPathInfo().equals("/enqueue_call")) {58response.setContentType("application/xml");59response.getWriter().print(enqueueTask());60}6162}6364public String createTask() {65String attributes = "{\"selected_language\":\"es\"}";6667Task task = Task.creator(workspaceSid).setAttributes(attributes).setWorkflowSid(workflowSid).create();6869return "{\"task_sid\":\"" + task.getSid() + "\"}";70}7172public String acceptReservation(final String taskSid, final String reservationSid) {73Reservation reservation = Reservation.updater(workspaceSid, taskSid, reservationSid)74.setReservationStatus(Reservation.Status.ACCEPTED).update();7576return "{\"worker_name\":\"" + reservation.getWorkerName() + "\"}";77}7879public String handleIncomingCall() {80VoiceResponse twiml =81new VoiceResponse.Builder()82.gather(new Gather.Builder()83.say(new Say.Builder("Para Español oprime el uno.").language(Say.Language.ES_MX)84.build())85.say(new Say.Builder("For English, please hold or press two.")86.language(Say.Language.EN_US).build())87.numDigits(1).timeout(5).build())88.build();8990try {91return twiml.toXml();92} catch (TwiMLException e) {93return "Error creating TwiML: " + e.getMessage();94}95}9697public String enqueueTask() {98com.twilio.twiml.voice.Task task = new com.twilio.twiml.voice.Task.Builder("{\"selected_language\":\"es\"}").build();99100Enqueue enqueue = new Enqueue.Builder().task(task).workflowSid(workflowSid).build();101102VoiceResponse twiml = new VoiceResponse.Builder().enqueue(enqueue).build();103104try {105return twiml.toXml();106} catch (TwiMLException e) {107return "Error creating TwiML: " + e.getMessage();108}109}110}
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:
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. However, you still need 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.