Skip to contentSkip to navigationSkip to topbar
On this page

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(link takes you to an external page), 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"}

Ensure you use the E.164 format for the contact_uri. Or, as displayed in the web portal:

Alice's Worker Details.

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 the Twilio Dev Phone 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(link takes you to an external page), 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:

Create a WrapUp Activity.

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


TwilioTaskRouterServlet.java

twiliotaskrouterservletjava page anchor
1
import java.io.IOException;
2
import java.util.HashMap;
3
import java.util.Map;
4
5
import javax.servlet.http.HttpServlet;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8
9
import org.json.simple.JSONObject;
10
11
import com.twilio.Twilio;
12
import com.twilio.rest.taskrouter.v1.workspace.Task;
13
import com.twilio.rest.taskrouter.v1.workspace.task.Reservation;
14
import com.twilio.twiml.*;
15
16
public class TwilioTaskRouterServlet extends HttpServlet {
17
18
private String accountSid;
19
private String authToken;
20
private String workspaceSid;
21
private String workflowSid;
22
23
@Override
24
public void init() {
25
accountSid = this.getServletConfig().getInitParameter("AccountSid");
26
authToken = this.getServletConfig().getInitParameter("AuthToken");
27
workspaceSid = this.getServletConfig().getInitParameter("WorkspaceSid");
28
workflowSid = this.getServletConfig().getInitParameter("WorkflowSid");
29
30
Twilio.init(accountSid, authToken);
31
}
32
33
// service() responds to both GET and POST requests.
34
// You can also use doGet() or doPost()
35
@Override
36
public void service(final HttpServletRequest request, final HttpServletResponse response)
37
throws IOException {
38
if (request.getPathInfo() == null || request.getPathInfo().isEmpty()) {
39
return;
40
}
41
42
if (request.getPathInfo().equals("/assignment_callback")) {
43
response.setContentType("application/json");
44
45
Map<String, String> dequeueInstruction = new HashMap<String, String>();
46
dequeueInstruction.put("instruction", "dequeue");
47
dequeueInstruction.put("from", "<caller_number>");
48
dequeueInstruction.put("post_work_activity_sid", "WA0123401234...");
49
50
response.getWriter().print(JSONObject.toJSONString(dequeueInstruction));
51
} else if (request.getPathInfo().equals("/create_task")) {
52
response.setContentType("application/json");
53
response.getWriter().print(createTask());
54
} else if (request.getPathInfo().equals("/accept_reservation")) {
55
response.setContentType("application/json");
56
String taskSid = request.getParameter("TaskSid");
57
String reservationSid = request.getParameter("ReservationSid");
58
response.getWriter().print(acceptReservation(taskSid, reservationSid));
59
} else if (request.getPathInfo().equals("/incoming_call")) {
60
response.setContentType("application/xml");
61
response.getWriter().print(handleIncomingCall());
62
} else if (request.getPathInfo().equals("/enqueue_call")) {
63
response.setContentType("application/xml");
64
response.getWriter().print(enqueueTask());
65
}
66
}
67
68
public String createTask() {
69
String attributes = "{\"selected_language\":\"es\"}";
70
71
Task task = Task.creator(workspaceSid, attributes, workflowSid).create();
72
73
return "{\"task_sid\":\"" + task.getSid() + "\"}";
74
}
75
76
public String acceptReservation(final String taskSid, final String reservationSid) {
77
Reservation reservation = Reservation.updater(workspaceSid, taskSid, reservationSid)
78
.setReservationStatus(Reservation.Status.ACCEPTED).update();
79
80
return "{\"worker_name\":\"" + reservation.getWorkerName() + "\"}";
81
}
82
83
public String handleIncomingCall() {
84
VoiceResponse twiml =
85
new VoiceResponse.Builder()
86
.gather(new Gather.Builder()
87
.say(new Say.Builder("Para Español oprime el uno.").language(Say.Language.ES)
88
.build())
89
.say(new Say.Builder("For English, please hold or press two.")
90
.language(Say.Language.EN).build())
91
.numDigits(1).timeout(5).build())
92
.build();
93
94
try {
95
return twiml.toXml();
96
} catch (TwiMLException e) {
97
return "Error creating TwiML: " + e.getMessage();
98
}
99
}
100
101
public String enqueueTask() {
102
com.twilio.twiml.Task task =
103
new com.twilio.twiml.Task.Builder().data("{\"selected_language\":\"es\"}").build();
104
105
EnqueueTask enqueue = new EnqueueTask.Builder(task).workflowSid(workflowSid).build();
106
107
VoiceResponse twiml = new VoiceResponse.Builder().enqueue(enqueue).build();
108
109
try {
110
return twiml.toXml();
111
} catch (TwiMLException e) {
112
return "Error creating TwiML: " + e.getMessage();
113
}
114
}
115
}

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


{"instruction":"dequeue", "from": "<caller_number>", "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?

Terms of service

Copyright © 2024 Twilio Inc.