Skip to contentSkip to navigationSkip to topbar
On this page

Control Worker Activities using Worker.js: Add an Agent UI to our Project


Let's get started on our agent UI. Assuming you've followed the conventions so far in this tutorial, the UI we create will be accessible using your web browser at:

http://localhost:8080/agents?WorkerSid=WK01234012340123401234 (substitute your Alice's WorkerSid)

We pass the WorkerSid in the URL to avoid implementing complex user management in our demo. In reality, you are likely to store a user's WorkerSid in your database alongside other User attributes.

Let's add on our to our server.rb file to add an endpoint to generate a page based on a template.


server.rb

serverrb page anchor
1
require 'rubygems'
2
require 'twilio-ruby'
3
require 'sinatra'
4
require 'json'
5
6
set :port, 8080
7
8
# Get your Account Sid and Auth Token from twilio.com/user/account
9
account_sid = '{{ account_sid }}'
10
auth_token = '{{ auth_token }}'
11
workspace_sid = '{{ workspace_sid }}'
12
workflow_sid = '{{ workflow_sid }}'
13
14
@client = Twilio::REST::Client.new(account_sid, auth_token)
15
16
post '/assignment_callback' do
17
# Respond to assignment callbacks with accept instruction
18
content_type :json
19
# from must be a verified phone number from your twilio account
20
{
21
"instruction" => "dequeue",
22
"from" => "+15556667777",
23
"post_work_activity_sid" => "WA0123401234..."
24
}.to_json
25
end
26
27
get '/create-task' do
28
# Create a task
29
task = @client.taskrouter.workspaces(workspace_sid)
30
.tasks
31
.create(
32
attributes: {
33
'selected_language' => 'es'
34
}.to_json,
35
workflow_sid: workflow_sid
36
)
37
task.attributes
38
end
39
40
get '/accept_reservation' do
41
# Accept a Reservation
42
task_sid = params[:task_sid]
43
reservation_sid = params[:reservation_sid]
44
45
reservation = @client.taskrouter.workspaces(workspace_sid)
46
.tasks(task_sid)
47
.reservations(reservation_sid)
48
.update(reservation_status: 'accepted')
49
reservation.worker_name
50
end
51
52
get '/incoming_call' do
53
Twilio::TwiML::VoiceResponse.new do |r|
54
r.gather(action: '/enqueue_call', method: 'POST', timeout: 5, num_digits: 1) do |gather|
55
gather.say('Para Español oprime el uno.', language: 'es')
56
gather.say('For English, please hold or press two.', language: 'en')
57
end
58
end.to_s
59
end
60
61
post '/enqueue_call' do
62
digit_pressed = params[:Digits]
63
if digit_pressed == 1
64
language = "es"
65
else
66
language = "en"
67
end
68
69
attributes = '{"selected_language":"'+language+'"}'
70
71
Twilio::TwiML::Response.new do |r|
72
r.Enqueue workflowSid: workflow_sid do |e|
73
e.Task attributes
74
end
75
end.text
76
end
77
78
get '/agents' do
79
worker_sid = params['WorkerSid']
80
81
capability = Twilio::JWT::TaskRouterCapability.new(
82
account_sid, auth_token,
83
workspace_sid, worker_sid
84
)
85
86
allow_activity_updates = Twilio::JWT::TaskRouterCapability::Policy.new(
87
Twilio::JWT::TaskRouterCapability::TaskRouterUtils
88
.all_activities(workspace_sid), 'POST', true
89
)
90
capability.add_policy(allow_activity_updates)
91
92
allow_reservation_updates = Twilio::JWT::TaskRouterCapability::Policy.new(
93
Twilio::JWT::TaskRouterCapability::TaskRouterUtils
94
.all_reservations(workspace_sid, worker_sid), 'POST', true
95
)
96
capability.add_policy(allow_reservation_updates)
97
98
worker_token = capability.to_s
99
100
erb :agent, :locals => {:worker_token => worker_token}
101
end

Now create a folder called views. Inside that folder, create an ERB template file that will be rendered when the URL is requested:


1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title>Customer Care - Voice Agent Screen</title>
5
<link rel="stylesheet" href="//media.twiliocdn.com/taskrouter/quickstart/agent.css"/>
6
<script src="https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>
7
<script type="text/javascript">
8
/* Subscribe to a subset of the available TaskRouter.js events for a worker */
9
function registerTaskRouterCallbacks() {
10
worker.on('ready', function(worker) {
11
agentActivityChanged(worker.activityName);
12
logger("Successfully registered as: " + worker.friendlyName)
13
logger("Current activity is: " + worker.activityName);
14
});
15
16
worker.on('activity.update', function(worker) {
17
agentActivityChanged(worker.activityName);
18
logger("Worker activity changed to: " + worker.activityName);
19
});
20
21
worker.on("reservation.created", function(reservation) {
22
logger("-----");
23
logger("You have been reserved to handle a call!");
24
logger("Call from: " + reservation.task.attributes.from);
25
logger("Selected language: " + reservation.task.attributes.selected_language);
26
logger("-----");
27
});
28
29
worker.on("reservation.accepted", function(reservation) {
30
logger("Reservation " + reservation.sid + " accepted!");
31
});
32
33
worker.on("reservation.rejected", function(reservation) {
34
logger("Reservation " + reservation.sid + " rejected!");
35
});
36
37
worker.on("reservation.timeout", function(reservation) {
38
logger("Reservation " + reservation.sid + " timed out!");
39
});
40
41
worker.on("reservation.canceled", function(reservation) {
42
logger("Reservation " + reservation.sid + " canceled!");
43
});
44
}
45
46
/* Hook up the agent Activity buttons to TaskRouter.js */
47
48
function bindAgentActivityButtons() {
49
// Fetch the full list of available Activities from TaskRouter. Store each
50
// ActivitySid against the matching Friendly Name
51
var activitySids = {};
52
worker.activities.fetch(function(error, activityList) {
53
var activities = activityList.data;
54
var i = activities.length;
55
while (i--) {
56
activitySids[activities[i].friendlyName] = activities[i].sid;
57
}
58
});
59
60
/* For each button of class 'change-activity' in our Agent UI, look up the
61
ActivitySid corresponding to the Friendly Name in the button's next-activity
62
data attribute. Use Worker.js to transition the agent to that ActivitySid
63
when the button is clicked.*/
64
var elements = document.getElementsByClassName('change-activity');
65
var i = elements.length;
66
while (i--) {
67
elements[i].onclick = function() {
68
var nextActivity = this.dataset.nextActivity;
69
var nextActivitySid = activitySids[nextActivity];
70
worker.update({"ActivitySid":nextActivitySid});
71
}
72
}
73
}
74
75
/* Update the UI to reflect a change in Activity */
76
77
function agentActivityChanged(activity) {
78
hideAgentActivities();
79
showAgentActivity(activity);
80
}
81
82
function hideAgentActivities() {
83
var elements = document.getElementsByClassName('agent-activity');
84
var i = elements.length;
85
while (i--) {
86
elements[i].style.display = 'none';
87
}
88
}
89
90
function showAgentActivity(activity) {
91
activity = activity.toLowerCase();
92
var elements = document.getElementsByClassName(('agent-activity ' + activity));
93
elements.item(0).style.display = 'block';
94
}
95
96
/* Other stuff */
97
98
function logger(message) {
99
var log = document.getElementById('log');
100
log.value += "\n> " + message;
101
log.scrollTop = log.scrollHeight;
102
}
103
104
window.onload = function() {
105
// Initialize TaskRouter.js on page load using window.workerToken -
106
// a Twilio Capability token that was set from rendering the template with agents endpoint
107
logger("Initializing...");
108
window.worker = new Twilio.TaskRouter.Worker("{{ worker_token }}");
109
110
registerTaskRouterCallbacks();
111
bindAgentActivityButtons();
112
};
113
</script>
114
</head>
115
<body>
116
<div class="content">
117
<section class="agent-activity offline">
118
<p class="activity">Offline</p>
119
<button class="change-activity" data-next-activity="Idle">Go Available</button>
120
</section>
121
<section class="agent-activity idle">
122
<p class="activity"><span>Available</span></p>
123
<button class="change-activity" data-next-activity="Offline">Go Offline</button>
124
</section>
125
<section class="agent-activity reserved">
126
<p class="activity">Reserved</p>
127
</section>
128
<section class="agent-activity busy">
129
<p class="activity">Busy</p>
130
</section>
131
<section class="agent-activity wrapup">
132
<p class="activity">Wrap-Up</p>
133
<button class="change-activity" data-next-activity="Idle">Go Available</button>
134
<button class="change-activity" data-next-activity="Offline">Go Offline</button>
135
</section>
136
<section class="log">
137
<textarea id="log" readonly="true"></textarea>
138
</section>
139
</div>
140
</body>
141
</html>

You'll notice that we included two external files:

  • taskrouter.min.js is the primary TaskRouter.js JavaScript file that communicates with TaskRouter's infrastructure on our behalf. You can use this URL to include Worker.js in your production application, but first check the reference documentation to ensure that you include the latest version number.
  • agent.css is a simple CSS file created for the purpose of this Quickstart. It saves us having to type out some simple pre-defined styles.

And that's it! Open http://localhost:8080/agents?WorkerSid=WK012340123401234 in your browser and you should see the screen below. If you make the same phone call as we made in Part 3, you should see Alice's Activity transition on screen as she is reserved and assigned to handle the Task.

If you see "Initializing..." and no progress, make sure that you have included the correct WorkerSid in the "WorkerSid" request parameter of the URL.

For more details, refer to the TaskRouter JavaScript SDK documentation.


  • This simple PoC has been tested in the latest version of popular browsers, including IE 11. *
Completed Agent UI.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.