Skip to contentSkip to navigationSkip to topbar
On this page

Dynamic Call Center with Python and Django


In this tutorial we will show how to automate the routing of calls from customers to your support agents. In this example customers would select a product, then be connected to a specialist for that product. If no one is available our customer's number will be saved so that our agent can call them back.


This is what the application does at a high level

this-is-what-the-application-does-at-a-high-level page anchor
  • Configure a workspace using the Twilio TaskRouter REST API .
  • Listen for incoming calls and let the user select a product with the dial pad.
  • Create a Task with the selected product and let TaskRouter handle it.
  • Store missed calls so agents can return the call to customers.
  • Redirect users to a voice mail when no one answers the call.
  • Allow agents to change their status (Available/Offline) via SMS.

In order to instruct TaskRouter to handle the Tasks, we need to configure a Workspace. We can do this in the TaskRouter Console(link takes you to an external page) or programmatically using the TaskRouter REST API.

In this Django application we'll do this setup when we start up the app.

A Workspace is the container element for any TaskRouter application. The elements are:

  • Tasks - Represents a customer trying to contact an agent
  • Workers - The agents responsible for handling Tasks
  • Task Queues - Holds Tasks to be consumed by a set of Workers
  • Workflows - Responsible for placing Tasks into Task Queues
  • Activities - Possible states of a Worker. Eg: idle, offline, busy

In order to build a client for this API, we need a TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN which you can find on Twilio Console. The function build_client configures and returns a TwilioTaskRouterClient, which is provided by the Twilio Python library.

Create, Setup and Configure the Workspace

create-setup-and-configure-the-workspace page anchor

task_router/workspace.py

1
import json
2
3
from django.conf import settings
4
from twilio.rest import Client
5
6
HOST = settings.HOST
7
ALICE_NUMBER = settings.ALICE_NUMBER
8
BOB_NUMBER = settings.BOB_NUMBER
9
WORKSPACE_NAME = 'Twilio Workspace'
10
11
12
def first(items):
13
return items[0] if items else None
14
15
16
def build_client():
17
account_sid = settings.TWILIO_ACCOUNT_SID
18
auth_token = settings.TWILIO_AUTH_TOKEN
19
return Client(account_sid, auth_token)
20
21
22
CACHE = {}
23
24
25
def activities_dict(client, workspace_sid):
26
activities = client.taskrouter.workspaces(workspace_sid)\
27
.activities.list()
28
29
return {activity.friendly_name: activity for activity in activities}
30
31
32
class WorkspaceInfo:
33
34
def __init__(self, workspace, workflow, activities, workers):
35
self.workflow_sid = workflow.sid
36
self.workspace_sid = workspace.sid
37
self.activities = activities
38
self.post_work_activity_sid = activities['Available'].sid
39
self.workers = workers
40
41
42
def setup():
43
client = build_client()
44
if 'WORKSPACE_INFO' not in CACHE:
45
workspace = create_workspace(client)
46
activities = activities_dict(client, workspace.sid)
47
workers = create_workers(client, workspace, activities)
48
queues = create_task_queues(client, workspace, activities)
49
workflow = create_workflow(client, workspace, queues)
50
CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
51
return CACHE['WORKSPACE_INFO']
52
53
54
def create_workspace(client):
55
try:
56
workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
57
client.taskrouter.workspaces(workspace.sid).delete()
58
except Exception:
59
pass
60
61
events_callback = HOST + '/events/'
62
63
return client.taskrouter.workspaces.create(
64
friendly_name=WORKSPACE_NAME,
65
event_callback_url=events_callback,
66
template=None)
67
68
69
def create_workers(client, workspace, activities):
70
alice_attributes = {
71
"products": ["ProgrammableVoice"],
72
"contact_uri": ALICE_NUMBER
73
}
74
75
alice = client.taskrouter.workspaces(workspace.sid)\
76
.workers.create(friendly_name='Alice',
77
attributes=json.dumps(alice_attributes))
78
79
bob_attributes = {
80
"products": ["ProgrammableSMS"],
81
"contact_uri": BOB_NUMBER
82
}
83
84
bob = client.taskrouter.workspaces(workspace.sid)\
85
.workers.create(friendly_name='Bob',
86
attributes=json.dumps(bob_attributes))
87
88
return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}
89
90
91
def create_task_queues(client, workspace, activities):
92
default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
93
.create(friendly_name='Default',
94
assignment_activity_sid=activities['Unavailable'].sid,
95
target_workers='1==1')
96
97
sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
98
.create(friendly_name='SMS',
99
assignment_activity_sid=activities['Unavailable'].sid,
100
target_workers='"ProgrammableSMS" in products')
101
102
voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
103
.create(friendly_name='Voice',
104
assignment_activity_sid=activities['Unavailable'].sid,
105
target_workers='"ProgrammableVoice" in products')
106
107
return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}
108
109
110
def create_workflow(client, workspace, queues):
111
defaultTarget = {
112
'queue': queues['sms'].sid,
113
'priority': 5,
114
'timeout': 30
115
}
116
117
smsTarget = {
118
'queue': queues['sms'].sid,
119
'priority': 5,
120
'timeout': 30
121
}
122
123
voiceTarget = {
124
'queue': queues['voice'].sid,
125
'priority': 5,
126
'timeout': 30
127
}
128
129
default_filter = {
130
'filter_friendly_name': 'Default Filter',
131
'queue': queues['default'].sid,
132
'Expression': '1==1',
133
'priority': 1,
134
'timeout': 30
135
}
136
137
voiceFilter = {
138
'filter_friendly_name': 'Voice Filter',
139
'expression': 'selected_product=="ProgrammableVoice"',
140
'targets': [voiceTarget, defaultTarget]
141
}
142
143
smsFilter = {
144
'filter_friendly_name': 'SMS Filter',
145
'expression': 'selected_product=="ProgrammableSMS"',
146
'targets': [smsTarget, defaultTarget]
147
}
148
149
config = {
150
'task_routing': {
151
'filters': [voiceFilter, smsFilter],
152
'default_filter': default_filter
153
}
154
}
155
156
callback_url = HOST + '/assignment/'
157
158
return client.taskrouter.workspaces(workspace.sid)\
159
.workflows.create(friendly_name='Sales',
160
assignment_callback_url=callback_url,
161
fallback_assignment_callback_url=callback_url,
162
task_reservation_timeout=15,
163
configuration=json.dumps(config))

Now let's look in more detail at all the steps, starting with the creation of the workspace itself.


Before creating a workspace, we need to delete any others with the same friendly_name as the one we are trying to create. In order to create a workspace we need to provide a friendly_name and a event_callback_url where a requests will be made every time an event is triggered in our workspace.

task_router/workspace.py

1
import json
2
3
from django.conf import settings
4
from twilio.rest import Client
5
6
HOST = settings.HOST
7
ALICE_NUMBER = settings.ALICE_NUMBER
8
BOB_NUMBER = settings.BOB_NUMBER
9
WORKSPACE_NAME = 'Twilio Workspace'
10
11
12
def first(items):
13
return items[0] if items else None
14
15
16
def build_client():
17
account_sid = settings.TWILIO_ACCOUNT_SID
18
auth_token = settings.TWILIO_AUTH_TOKEN
19
return Client(account_sid, auth_token)
20
21
22
CACHE = {}
23
24
25
def activities_dict(client, workspace_sid):
26
activities = client.taskrouter.workspaces(workspace_sid)\
27
.activities.list()
28
29
return {activity.friendly_name: activity for activity in activities}
30
31
32
class WorkspaceInfo:
33
34
def __init__(self, workspace, workflow, activities, workers):
35
self.workflow_sid = workflow.sid
36
self.workspace_sid = workspace.sid
37
self.activities = activities
38
self.post_work_activity_sid = activities['Available'].sid
39
self.workers = workers
40
41
42
def setup():
43
client = build_client()
44
if 'WORKSPACE_INFO' not in CACHE:
45
workspace = create_workspace(client)
46
activities = activities_dict(client, workspace.sid)
47
workers = create_workers(client, workspace, activities)
48
queues = create_task_queues(client, workspace, activities)
49
workflow = create_workflow(client, workspace, queues)
50
CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
51
return CACHE['WORKSPACE_INFO']
52
53
54
def create_workspace(client):
55
try:
56
workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
57
client.taskrouter.workspaces(workspace.sid).delete()
58
except Exception:
59
pass
60
61
events_callback = HOST + '/events/'
62
63
return client.taskrouter.workspaces.create(
64
friendly_name=WORKSPACE_NAME,
65
event_callback_url=events_callback,
66
template=None)
67
68
69
def create_workers(client, workspace, activities):
70
alice_attributes = {
71
"products": ["ProgrammableVoice"],
72
"contact_uri": ALICE_NUMBER
73
}
74
75
alice = client.taskrouter.workspaces(workspace.sid)\
76
.workers.create(friendly_name='Alice',
77
attributes=json.dumps(alice_attributes))
78
79
bob_attributes = {
80
"products": ["ProgrammableSMS"],
81
"contact_uri": BOB_NUMBER
82
}
83
84
bob = client.taskrouter.workspaces(workspace.sid)\
85
.workers.create(friendly_name='Bob',
86
attributes=json.dumps(bob_attributes))
87
88
return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}
89
90
91
def create_task_queues(client, workspace, activities):
92
default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
93
.create(friendly_name='Default',
94
assignment_activity_sid=activities['Unavailable'].sid,
95
target_workers='1==1')
96
97
sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
98
.create(friendly_name='SMS',
99
assignment_activity_sid=activities['Unavailable'].sid,
100
target_workers='"ProgrammableSMS" in products')
101
102
voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
103
.create(friendly_name='Voice',
104
assignment_activity_sid=activities['Unavailable'].sid,
105
target_workers='"ProgrammableVoice" in products')
106
107
return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}
108
109
110
def create_workflow(client, workspace, queues):
111
defaultTarget = {
112
'queue': queues['sms'].sid,
113
'priority': 5,
114
'timeout': 30
115
}
116
117
smsTarget = {
118
'queue': queues['sms'].sid,
119
'priority': 5,
120
'timeout': 30
121
}
122
123
voiceTarget = {
124
'queue': queues['voice'].sid,
125
'priority': 5,
126
'timeout': 30
127
}
128
129
default_filter = {
130
'filter_friendly_name': 'Default Filter',
131
'queue': queues['default'].sid,
132
'Expression': '1==1',
133
'priority': 1,
134
'timeout': 30
135
}
136
137
voiceFilter = {
138
'filter_friendly_name': 'Voice Filter',
139
'expression': 'selected_product=="ProgrammableVoice"',
140
'targets': [voiceTarget, defaultTarget]
141
}
142
143
smsFilter = {
144
'filter_friendly_name': 'SMS Filter',
145
'expression': 'selected_product=="ProgrammableSMS"',
146
'targets': [smsTarget, defaultTarget]
147
}
148
149
config = {
150
'task_routing': {
151
'filters': [voiceFilter, smsFilter],
152
'default_filter': default_filter
153
}
154
}
155
156
callback_url = HOST + '/assignment/'
157
158
return client.taskrouter.workspaces(workspace.sid)\
159
.workflows.create(friendly_name='Sales',
160
assignment_callback_url=callback_url,
161
fallback_assignment_callback_url=callback_url,
162
task_reservation_timeout=15,
163
configuration=json.dumps(config))

We have a brand new workspace, now we need workers. Let's create them on the next step.


We'll create two workers: Bob and Alice. They each have two attributes: contact_uri a phone number and products, a list of products each worker is specialized in. We also need to specify an activity_sid and a name for each worker. The selected activity will define the status of the worker.

A set of default activities is created with your workspace. We use the Idle activity to make a worker available for incoming calls.

task_router/workspace.py

1
import json
2
3
from django.conf import settings
4
from twilio.rest import Client
5
6
HOST = settings.HOST
7
ALICE_NUMBER = settings.ALICE_NUMBER
8
BOB_NUMBER = settings.BOB_NUMBER
9
WORKSPACE_NAME = 'Twilio Workspace'
10
11
12
def first(items):
13
return items[0] if items else None
14
15
16
def build_client():
17
account_sid = settings.TWILIO_ACCOUNT_SID
18
auth_token = settings.TWILIO_AUTH_TOKEN
19
return Client(account_sid, auth_token)
20
21
22
CACHE = {}
23
24
25
def activities_dict(client, workspace_sid):
26
activities = client.taskrouter.workspaces(workspace_sid)\
27
.activities.list()
28
29
return {activity.friendly_name: activity for activity in activities}
30
31
32
class WorkspaceInfo:
33
34
def __init__(self, workspace, workflow, activities, workers):
35
self.workflow_sid = workflow.sid
36
self.workspace_sid = workspace.sid
37
self.activities = activities
38
self.post_work_activity_sid = activities['Available'].sid
39
self.workers = workers
40
41
42
def setup():
43
client = build_client()
44
if 'WORKSPACE_INFO' not in CACHE:
45
workspace = create_workspace(client)
46
activities = activities_dict(client, workspace.sid)
47
workers = create_workers(client, workspace, activities)
48
queues = create_task_queues(client, workspace, activities)
49
workflow = create_workflow(client, workspace, queues)
50
CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
51
return CACHE['WORKSPACE_INFO']
52
53
54
def create_workspace(client):
55
try:
56
workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
57
client.taskrouter.workspaces(workspace.sid).delete()
58
except Exception:
59
pass
60
61
events_callback = HOST + '/events/'
62
63
return client.taskrouter.workspaces.create(
64
friendly_name=WORKSPACE_NAME,
65
event_callback_url=events_callback,
66
template=None)
67
68
69
def create_workers(client, workspace, activities):
70
alice_attributes = {
71
"products": ["ProgrammableVoice"],
72
"contact_uri": ALICE_NUMBER
73
}
74
75
alice = client.taskrouter.workspaces(workspace.sid)\
76
.workers.create(friendly_name='Alice',
77
attributes=json.dumps(alice_attributes))
78
79
bob_attributes = {
80
"products": ["ProgrammableSMS"],
81
"contact_uri": BOB_NUMBER
82
}
83
84
bob = client.taskrouter.workspaces(workspace.sid)\
85
.workers.create(friendly_name='Bob',
86
attributes=json.dumps(bob_attributes))
87
88
return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}
89
90
91
def create_task_queues(client, workspace, activities):
92
default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
93
.create(friendly_name='Default',
94
assignment_activity_sid=activities['Unavailable'].sid,
95
target_workers='1==1')
96
97
sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
98
.create(friendly_name='SMS',
99
assignment_activity_sid=activities['Unavailable'].sid,
100
target_workers='"ProgrammableSMS" in products')
101
102
voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
103
.create(friendly_name='Voice',
104
assignment_activity_sid=activities['Unavailable'].sid,
105
target_workers='"ProgrammableVoice" in products')
106
107
return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}
108
109
110
def create_workflow(client, workspace, queues):
111
defaultTarget = {
112
'queue': queues['sms'].sid,
113
'priority': 5,
114
'timeout': 30
115
}
116
117
smsTarget = {
118
'queue': queues['sms'].sid,
119
'priority': 5,
120
'timeout': 30
121
}
122
123
voiceTarget = {
124
'queue': queues['voice'].sid,
125
'priority': 5,
126
'timeout': 30
127
}
128
129
default_filter = {
130
'filter_friendly_name': 'Default Filter',
131
'queue': queues['default'].sid,
132
'Expression': '1==1',
133
'priority': 1,
134
'timeout': 30
135
}
136
137
voiceFilter = {
138
'filter_friendly_name': 'Voice Filter',
139
'expression': 'selected_product=="ProgrammableVoice"',
140
'targets': [voiceTarget, defaultTarget]
141
}
142
143
smsFilter = {
144
'filter_friendly_name': 'SMS Filter',
145
'expression': 'selected_product=="ProgrammableSMS"',
146
'targets': [smsTarget, defaultTarget]
147
}
148
149
config = {
150
'task_routing': {
151
'filters': [voiceFilter, smsFilter],
152
'default_filter': default_filter
153
}
154
}
155
156
callback_url = HOST + '/assignment/'
157
158
return client.taskrouter.workspaces(workspace.sid)\
159
.workflows.create(friendly_name='Sales',
160
assignment_callback_url=callback_url,
161
fallback_assignment_callback_url=callback_url,
162
task_reservation_timeout=15,
163
configuration=json.dumps(config))

After creating our workers, let's set up the Task Queues.


Next, we set up the Task Queues. Each with a friendly_name and a targetWorkers, which is an expression to match Workers. Our Task Queues are:

  1. SMS - Will target Workers specialized in Programmable SMS, such as Bob, using the expression '"ProgrammableSMS" in products' .
  2. Voice - Will do the same for Programmable Voice Workers, such as Alice, using the expression '"ProgrammableVoice" in products' .
  3. Default - This queue targets all users and can be used when there are no specialist around for the chosen product. We can use the "1==1" expression here.

task_router/workspace.py

1
import json
2
3
from django.conf import settings
4
from twilio.rest import Client
5
6
HOST = settings.HOST
7
ALICE_NUMBER = settings.ALICE_NUMBER
8
BOB_NUMBER = settings.BOB_NUMBER
9
WORKSPACE_NAME = 'Twilio Workspace'
10
11
12
def first(items):
13
return items[0] if items else None
14
15
16
def build_client():
17
account_sid = settings.TWILIO_ACCOUNT_SID
18
auth_token = settings.TWILIO_AUTH_TOKEN
19
return Client(account_sid, auth_token)
20
21
22
CACHE = {}
23
24
25
def activities_dict(client, workspace_sid):
26
activities = client.taskrouter.workspaces(workspace_sid)\
27
.activities.list()
28
29
return {activity.friendly_name: activity for activity in activities}
30
31
32
class WorkspaceInfo:
33
34
def __init__(self, workspace, workflow, activities, workers):
35
self.workflow_sid = workflow.sid
36
self.workspace_sid = workspace.sid
37
self.activities = activities
38
self.post_work_activity_sid = activities['Available'].sid
39
self.workers = workers
40
41
42
def setup():
43
client = build_client()
44
if 'WORKSPACE_INFO' not in CACHE:
45
workspace = create_workspace(client)
46
activities = activities_dict(client, workspace.sid)
47
workers = create_workers(client, workspace, activities)
48
queues = create_task_queues(client, workspace, activities)
49
workflow = create_workflow(client, workspace, queues)
50
CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
51
return CACHE['WORKSPACE_INFO']
52
53
54
def create_workspace(client):
55
try:
56
workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
57
client.taskrouter.workspaces(workspace.sid).delete()
58
except Exception:
59
pass
60
61
events_callback = HOST + '/events/'
62
63
return client.taskrouter.workspaces.create(
64
friendly_name=WORKSPACE_NAME,
65
event_callback_url=events_callback,
66
template=None)
67
68
69
def create_workers(client, workspace, activities):
70
alice_attributes = {
71
"products": ["ProgrammableVoice"],
72
"contact_uri": ALICE_NUMBER
73
}
74
75
alice = client.taskrouter.workspaces(workspace.sid)\
76
.workers.create(friendly_name='Alice',
77
attributes=json.dumps(alice_attributes))
78
79
bob_attributes = {
80
"products": ["ProgrammableSMS"],
81
"contact_uri": BOB_NUMBER
82
}
83
84
bob = client.taskrouter.workspaces(workspace.sid)\
85
.workers.create(friendly_name='Bob',
86
attributes=json.dumps(bob_attributes))
87
88
return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}
89
90
91
def create_task_queues(client, workspace, activities):
92
default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
93
.create(friendly_name='Default',
94
assignment_activity_sid=activities['Unavailable'].sid,
95
target_workers='1==1')
96
97
sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
98
.create(friendly_name='SMS',
99
assignment_activity_sid=activities['Unavailable'].sid,
100
target_workers='"ProgrammableSMS" in products')
101
102
voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
103
.create(friendly_name='Voice',
104
assignment_activity_sid=activities['Unavailable'].sid,
105
target_workers='"ProgrammableVoice" in products')
106
107
return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}
108
109
110
def create_workflow(client, workspace, queues):
111
defaultTarget = {
112
'queue': queues['sms'].sid,
113
'priority': 5,
114
'timeout': 30
115
}
116
117
smsTarget = {
118
'queue': queues['sms'].sid,
119
'priority': 5,
120
'timeout': 30
121
}
122
123
voiceTarget = {
124
'queue': queues['voice'].sid,
125
'priority': 5,
126
'timeout': 30
127
}
128
129
default_filter = {
130
'filter_friendly_name': 'Default Filter',
131
'queue': queues['default'].sid,
132
'Expression': '1==1',
133
'priority': 1,
134
'timeout': 30
135
}
136
137
voiceFilter = {
138
'filter_friendly_name': 'Voice Filter',
139
'expression': 'selected_product=="ProgrammableVoice"',
140
'targets': [voiceTarget, defaultTarget]
141
}
142
143
smsFilter = {
144
'filter_friendly_name': 'SMS Filter',
145
'expression': 'selected_product=="ProgrammableSMS"',
146
'targets': [smsTarget, defaultTarget]
147
}
148
149
config = {
150
'task_routing': {
151
'filters': [voiceFilter, smsFilter],
152
'default_filter': default_filter
153
}
154
}
155
156
callback_url = HOST + '/assignment/'
157
158
return client.taskrouter.workspaces(workspace.sid)\
159
.workflows.create(friendly_name='Sales',
160
assignment_callback_url=callback_url,
161
fallback_assignment_callback_url=callback_url,
162
task_reservation_timeout=15,
163
configuration=json.dumps(config))

We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!


Finally, we create the Workflow using the following parameters:

  1. friendly_name as the name of a Workflow.
  2. assignment_callback_url and fallback_assignment_callback_url as the public URL where a request will be made when this Workflow assigns a Task to a Worker. We will learn how to implement it on the next steps.
  3. task_reservation_timeout as the maximum time we want to wait until a Worker is available for handling a Task.
  4. configuration which is a set of rules for placing Tasks into Task Queues. The routing configuration will take a Task attribute and match it with Task Queues. This application's Workflow rules are defined as:

    • "selected_product==\ "ProgrammableSMS\"" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.
    • "selected_product==\ "ProgrammableVoice\"" expression for Voice Task Queue.

task_router/workspace.py

1
import json
2
3
from django.conf import settings
4
from twilio.rest import Client
5
6
HOST = settings.HOST
7
ALICE_NUMBER = settings.ALICE_NUMBER
8
BOB_NUMBER = settings.BOB_NUMBER
9
WORKSPACE_NAME = 'Twilio Workspace'
10
11
12
def first(items):
13
return items[0] if items else None
14
15
16
def build_client():
17
account_sid = settings.TWILIO_ACCOUNT_SID
18
auth_token = settings.TWILIO_AUTH_TOKEN
19
return Client(account_sid, auth_token)
20
21
22
CACHE = {}
23
24
25
def activities_dict(client, workspace_sid):
26
activities = client.taskrouter.workspaces(workspace_sid)\
27
.activities.list()
28
29
return {activity.friendly_name: activity for activity in activities}
30
31
32
class WorkspaceInfo:
33
34
def __init__(self, workspace, workflow, activities, workers):
35
self.workflow_sid = workflow.sid
36
self.workspace_sid = workspace.sid
37
self.activities = activities
38
self.post_work_activity_sid = activities['Available'].sid
39
self.workers = workers
40
41
42
def setup():
43
client = build_client()
44
if 'WORKSPACE_INFO' not in CACHE:
45
workspace = create_workspace(client)
46
activities = activities_dict(client, workspace.sid)
47
workers = create_workers(client, workspace, activities)
48
queues = create_task_queues(client, workspace, activities)
49
workflow = create_workflow(client, workspace, queues)
50
CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
51
return CACHE['WORKSPACE_INFO']
52
53
54
def create_workspace(client):
55
try:
56
workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
57
client.taskrouter.workspaces(workspace.sid).delete()
58
except Exception:
59
pass
60
61
events_callback = HOST + '/events/'
62
63
return client.taskrouter.workspaces.create(
64
friendly_name=WORKSPACE_NAME,
65
event_callback_url=events_callback,
66
template=None)
67
68
69
def create_workers(client, workspace, activities):
70
alice_attributes = {
71
"products": ["ProgrammableVoice"],
72
"contact_uri": ALICE_NUMBER
73
}
74
75
alice = client.taskrouter.workspaces(workspace.sid)\
76
.workers.create(friendly_name='Alice',
77
attributes=json.dumps(alice_attributes))
78
79
bob_attributes = {
80
"products": ["ProgrammableSMS"],
81
"contact_uri": BOB_NUMBER
82
}
83
84
bob = client.taskrouter.workspaces(workspace.sid)\
85
.workers.create(friendly_name='Bob',
86
attributes=json.dumps(bob_attributes))
87
88
return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}
89
90
91
def create_task_queues(client, workspace, activities):
92
default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
93
.create(friendly_name='Default',
94
assignment_activity_sid=activities['Unavailable'].sid,
95
target_workers='1==1')
96
97
sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
98
.create(friendly_name='SMS',
99
assignment_activity_sid=activities['Unavailable'].sid,
100
target_workers='"ProgrammableSMS" in products')
101
102
voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\
103
.create(friendly_name='Voice',
104
assignment_activity_sid=activities['Unavailable'].sid,
105
target_workers='"ProgrammableVoice" in products')
106
107
return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}
108
109
110
def create_workflow(client, workspace, queues):
111
defaultTarget = {
112
'queue': queues['sms'].sid,
113
'priority': 5,
114
'timeout': 30
115
}
116
117
smsTarget = {
118
'queue': queues['sms'].sid,
119
'priority': 5,
120
'timeout': 30
121
}
122
123
voiceTarget = {
124
'queue': queues['voice'].sid,
125
'priority': 5,
126
'timeout': 30
127
}
128
129
default_filter = {
130
'filter_friendly_name': 'Default Filter',
131
'queue': queues['default'].sid,
132
'Expression': '1==1',
133
'priority': 1,
134
'timeout': 30
135
}
136
137
voiceFilter = {
138
'filter_friendly_name': 'Voice Filter',
139
'expression': 'selected_product=="ProgrammableVoice"',
140
'targets': [voiceTarget, defaultTarget]
141
}
142
143
smsFilter = {
144
'filter_friendly_name': 'SMS Filter',
145
'expression': 'selected_product=="ProgrammableSMS"',
146
'targets': [smsTarget, defaultTarget]
147
}
148
149
config = {
150
'task_routing': {
151
'filters': [voiceFilter, smsFilter],
152
'default_filter': default_filter
153
}
154
}
155
156
callback_url = HOST + '/assignment/'
157
158
return client.taskrouter.workspaces(workspace.sid)\
159
.workflows.create(friendly_name='Sales',
160
assignment_callback_url=callback_url,
161
fallback_assignment_callback_url=callback_url,
162
task_reservation_timeout=15,
163
configuration=json.dumps(config))

Our workspace is completely setup. Now it's time to see how we use it to route calls.


Handle Twilio's Request

handle-twilios-request page anchor

Right after receiving a call, Twilio will send a request to the URL specified on the number's configuration.

The endpoint will then process the request and generate a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.

Handling Twilio's Requests

handling-twilios-requests page anchor

task_router/views.py

1
import json
2
from urllib.parse import quote_plus
3
4
from django.conf import settings
5
from django.http import HttpResponse, JsonResponse
6
from django.shortcuts import render
7
from django.urls import reverse
8
from django.views.decorators.csrf import csrf_exempt
9
from twilio.rest import Client
10
from twilio.twiml.messaging_response import MessagingResponse
11
from twilio.twiml.voice_response import VoiceResponse
12
13
from . import sms_sender, workspace
14
from .models import MissedCall
15
16
if not getattr(settings, 'TESTING', False):
17
WORKSPACE_INFO = workspace.setup()
18
else:
19
WORKSPACE_INFO = None
20
21
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
22
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
23
TWILIO_NUMBER = settings.TWILIO_NUMBER
24
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS
25
26
27
def root(request):
28
""" Renders a missed calls list, with product and phone number """
29
missed_calls = MissedCall.objects.order_by('-created')
30
return render(request, 'index.html', {
31
'missed_calls': missed_calls
32
})
33
34
35
@csrf_exempt
36
def incoming_sms(request):
37
""" Changes worker activity and returns a confirmation """
38
client = Client(ACCOUNT_SID, AUTH_TOKEN)
39
activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
40
activity_sid = WORKSPACE_INFO.activities[activity].sid
41
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
42
workspace_sid = WORKSPACE_INFO.workspace_sid
43
44
client.workspaces(workspace_sid)\
45
.workers(worker_sid)\
46
.update(activity_sid=activity_sid)
47
48
resp = MessagingResponse()
49
message = 'Your status has changed to ' + activity
50
resp.message(message)
51
return HttpResponse(resp)
52
53
54
@csrf_exempt
55
def incoming_call(request):
56
""" Returns TwiML instructions to Twilio's POST requests """
57
resp = VoiceResponse()
58
gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")
59
gather.say("For Programmable SMS, press one. For Voice, press any other key.")
60
61
return HttpResponse(resp)
62
63
64
@csrf_exempt
65
def enqueue(request):
66
""" Parses a selected product, creating a Task on Task Router Workflow """
67
resp = VoiceResponse()
68
digits = request.POST['Digits']
69
selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
70
task = {'selected_product': selected_product}
71
72
enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)
73
enqueue.task(json.dumps(task))
74
75
return HttpResponse(resp)
76
77
78
@csrf_exempt
79
def assignment(request):
80
""" Task assignment """
81
response = {'instruction': 'dequeue',
82
'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}
83
return JsonResponse(response)
84
85
86
@csrf_exempt
87
def events(request):
88
""" Events callback for missed calls """
89
POST = request.POST
90
event_type = POST.get('EventType')
91
task_events = ['workflow.timeout', 'task.canceled']
92
worker_event = 'worker.activity.update'
93
94
if event_type in task_events:
95
task_attributes = json.loads(POST['TaskAttributes'])
96
_save_missed_call(task_attributes)
97
if event_type == 'workflow.timeout':
98
_voicemail(task_attributes['call_sid'])
99
elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
100
message = 'Your status has changed to Offline. Reply with '\
101
'"On" to get back Online'
102
worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
103
sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)
104
105
return HttpResponse('')
106
107
108
def _voicemail(call_sid):
109
msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
110
route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
111
route_call(call_sid, route_url)
112
113
114
def route_call(call_sid, route_url):
115
client = Client(ACCOUNT_SID, AUTH_TOKEN)
116
client.api.calls(call_sid).update(url=route_url)
117
118
119
def _save_missed_call(task_attributes):
120
MissedCall.objects.create(
121
phone_number=task_attributes['from'],
122
selected_product=task_attributes['selected_product'])
123
124
125
# Only used by the tests in order to patch requests before any call is made
126
def setup_workspace():
127
global WORKSPACE_INFO
128
WORKSPACE_INFO = workspace.setup()

We just asked the caller to choose a product, next we will use their choice to create the appropriate Task.


This is the endpoint set as the action URL on the Gather verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits parameter that holds the pressed keys. A Task will be created based on the pressed digit with the selected_product as an attribute. The Workflow will take this Task's attributes and match with the configured expressions in order to find a Task Queue for this Task, so an appropriate available Worker can be assigned to handle it.

We use the Enqueue verb with a WorkflowSid attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.

task_router/views.py

1
import json
2
from urllib.parse import quote_plus
3
4
from django.conf import settings
5
from django.http import HttpResponse, JsonResponse
6
from django.shortcuts import render
7
from django.urls import reverse
8
from django.views.decorators.csrf import csrf_exempt
9
from twilio.rest import Client
10
from twilio.twiml.messaging_response import MessagingResponse
11
from twilio.twiml.voice_response import VoiceResponse
12
13
from . import sms_sender, workspace
14
from .models import MissedCall
15
16
if not getattr(settings, 'TESTING', False):
17
WORKSPACE_INFO = workspace.setup()
18
else:
19
WORKSPACE_INFO = None
20
21
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
22
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
23
TWILIO_NUMBER = settings.TWILIO_NUMBER
24
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS
25
26
27
def root(request):
28
""" Renders a missed calls list, with product and phone number """
29
missed_calls = MissedCall.objects.order_by('-created')
30
return render(request, 'index.html', {
31
'missed_calls': missed_calls
32
})
33
34
35
@csrf_exempt
36
def incoming_sms(request):
37
""" Changes worker activity and returns a confirmation """
38
client = Client(ACCOUNT_SID, AUTH_TOKEN)
39
activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
40
activity_sid = WORKSPACE_INFO.activities[activity].sid
41
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
42
workspace_sid = WORKSPACE_INFO.workspace_sid
43
44
client.workspaces(workspace_sid)\
45
.workers(worker_sid)\
46
.update(activity_sid=activity_sid)
47
48
resp = MessagingResponse()
49
message = 'Your status has changed to ' + activity
50
resp.message(message)
51
return HttpResponse(resp)
52
53
54
@csrf_exempt
55
def incoming_call(request):
56
""" Returns TwiML instructions to Twilio's POST requests """
57
resp = VoiceResponse()
58
gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")
59
gather.say("For Programmable SMS, press one. For Voice, press any other key.")
60
61
return HttpResponse(resp)
62
63
64
@csrf_exempt
65
def enqueue(request):
66
""" Parses a selected product, creating a Task on Task Router Workflow """
67
resp = VoiceResponse()
68
digits = request.POST['Digits']
69
selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
70
task = {'selected_product': selected_product}
71
72
enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)
73
enqueue.task(json.dumps(task))
74
75
return HttpResponse(resp)
76
77
78
@csrf_exempt
79
def assignment(request):
80
""" Task assignment """
81
response = {'instruction': 'dequeue',
82
'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}
83
return JsonResponse(response)
84
85
86
@csrf_exempt
87
def events(request):
88
""" Events callback for missed calls """
89
POST = request.POST
90
event_type = POST.get('EventType')
91
task_events = ['workflow.timeout', 'task.canceled']
92
worker_event = 'worker.activity.update'
93
94
if event_type in task_events:
95
task_attributes = json.loads(POST['TaskAttributes'])
96
_save_missed_call(task_attributes)
97
if event_type == 'workflow.timeout':
98
_voicemail(task_attributes['call_sid'])
99
elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
100
message = 'Your status has changed to Offline. Reply with '\
101
'"On" to get back Online'
102
worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
103
sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)
104
105
return HttpResponse('')
106
107
108
def _voicemail(call_sid):
109
msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
110
route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
111
route_call(call_sid, route_url)
112
113
114
def route_call(call_sid, route_url):
115
client = Client(ACCOUNT_SID, AUTH_TOKEN)
116
client.api.calls(call_sid).update(url=route_url)
117
118
119
def _save_missed_call(task_attributes):
120
MissedCall.objects.create(
121
phone_number=task_attributes['from'],
122
selected_product=task_attributes['selected_product'])
123
124
125
# Only used by the tests in order to patch requests before any call is made
126
def setup_workspace():
127
global WORKSPACE_INFO
128
WORKSPACE_INFO = workspace.setup()

After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.


When TaskRouter selects a Worker, it does the following:

  1. The Task's Assignment Status is set to 'reserved'.
  2. A Reservation instance is generated, linking the Task to the selected Worker.
  3. At the same time the Reservation is created, a POST request is made to the Workflow's AssignmentCallbackURL, which was configured while creating the Workflow. This request includes the full details of the Task, the selected Worker, and the Reservation.

Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, email, push notifications or make a call.

Since we created this Task during a voice call with an Enqueue verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to parameter with a phone number, TaskRouter will pick the Worker's contact_uri attribute.

We also send a post_work_activity_sid which will tell TaskRouter which Activity to assign this worker after the call ends.

task_router/views.py

1
import json
2
from urllib.parse import quote_plus
3
4
from django.conf import settings
5
from django.http import HttpResponse, JsonResponse
6
from django.shortcuts import render
7
from django.urls import reverse
8
from django.views.decorators.csrf import csrf_exempt
9
from twilio.rest import Client
10
from twilio.twiml.messaging_response import MessagingResponse
11
from twilio.twiml.voice_response import VoiceResponse
12
13
from . import sms_sender, workspace
14
from .models import MissedCall
15
16
if not getattr(settings, 'TESTING', False):
17
WORKSPACE_INFO = workspace.setup()
18
else:
19
WORKSPACE_INFO = None
20
21
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
22
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
23
TWILIO_NUMBER = settings.TWILIO_NUMBER
24
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS
25
26
27
def root(request):
28
""" Renders a missed calls list, with product and phone number """
29
missed_calls = MissedCall.objects.order_by('-created')
30
return render(request, 'index.html', {
31
'missed_calls': missed_calls
32
})
33
34
35
@csrf_exempt
36
def incoming_sms(request):
37
""" Changes worker activity and returns a confirmation """
38
client = Client(ACCOUNT_SID, AUTH_TOKEN)
39
activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
40
activity_sid = WORKSPACE_INFO.activities[activity].sid
41
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
42
workspace_sid = WORKSPACE_INFO.workspace_sid
43
44
client.workspaces(workspace_sid)\
45
.workers(worker_sid)\
46
.update(activity_sid=activity_sid)
47
48
resp = MessagingResponse()
49
message = 'Your status has changed to ' + activity
50
resp.message(message)
51
return HttpResponse(resp)
52
53
54
@csrf_exempt
55
def incoming_call(request):
56
""" Returns TwiML instructions to Twilio's POST requests """
57
resp = VoiceResponse()
58
gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")
59
gather.say("For Programmable SMS, press one. For Voice, press any other key.")
60
61
return HttpResponse(resp)
62
63
64
@csrf_exempt
65
def enqueue(request):
66
""" Parses a selected product, creating a Task on Task Router Workflow """
67
resp = VoiceResponse()
68
digits = request.POST['Digits']
69
selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
70
task = {'selected_product': selected_product}
71
72
enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)
73
enqueue.task(json.dumps(task))
74
75
return HttpResponse(resp)
76
77
78
@csrf_exempt
79
def assignment(request):
80
""" Task assignment """
81
response = {'instruction': 'dequeue',
82
'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}
83
return JsonResponse(response)
84
85
86
@csrf_exempt
87
def events(request):
88
""" Events callback for missed calls """
89
POST = request.POST
90
event_type = POST.get('EventType')
91
task_events = ['workflow.timeout', 'task.canceled']
92
worker_event = 'worker.activity.update'
93
94
if event_type in task_events:
95
task_attributes = json.loads(POST['TaskAttributes'])
96
_save_missed_call(task_attributes)
97
if event_type == 'workflow.timeout':
98
_voicemail(task_attributes['call_sid'])
99
elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
100
message = 'Your status has changed to Offline. Reply with '\
101
'"On" to get back Online'
102
worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
103
sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)
104
105
return HttpResponse('')
106
107
108
def _voicemail(call_sid):
109
msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
110
route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
111
route_call(call_sid, route_url)
112
113
114
def route_call(call_sid, route_url):
115
client = Client(ACCOUNT_SID, AUTH_TOKEN)
116
client.api.calls(call_sid).update(url=route_url)
117
118
119
def _save_missed_call(task_attributes):
120
MissedCall.objects.create(
121
phone_number=task_attributes['from'],
122
selected_product=task_attributes['selected_product'])
123
124
125
# Only used by the tests in order to patch requests before any call is made
126
def setup_workspace():
127
global WORKSPACE_INFO
128
WORKSPACE_INFO = workspace.setup()

Now that our Tasks are routed properly, let's deal with missed calls in the next step.


This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.

Here we use TwilioRestClient to route this call to a Voicemail Twimlet(link takes you to an external page). Twimlets are tiny web applications for voice. This one will generate a TwiML response using Say verb and record a message using Record verb. The recorded message will then be transcribed and sent to the email address configured.

Note that we are also listening for task.canceled. This is triggered when the customer hangs up before being assigned to an agent, therefore canceling the task. Capturing this event allows us to collect the information from the customers that hang up before the Workflow times out.

task_router/views.py

1
import json
2
from urllib.parse import quote_plus
3
4
from django.conf import settings
5
from django.http import HttpResponse, JsonResponse
6
from django.shortcuts import render
7
from django.urls import reverse
8
from django.views.decorators.csrf import csrf_exempt
9
from twilio.rest import Client
10
from twilio.twiml.messaging_response import MessagingResponse
11
from twilio.twiml.voice_response import VoiceResponse
12
13
from . import sms_sender, workspace
14
from .models import MissedCall
15
16
if not getattr(settings, 'TESTING', False):
17
WORKSPACE_INFO = workspace.setup()
18
else:
19
WORKSPACE_INFO = None
20
21
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
22
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
23
TWILIO_NUMBER = settings.TWILIO_NUMBER
24
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS
25
26
27
def root(request):
28
""" Renders a missed calls list, with product and phone number """
29
missed_calls = MissedCall.objects.order_by('-created')
30
return render(request, 'index.html', {
31
'missed_calls': missed_calls
32
})
33
34
35
@csrf_exempt
36
def incoming_sms(request):
37
""" Changes worker activity and returns a confirmation """
38
client = Client(ACCOUNT_SID, AUTH_TOKEN)
39
activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
40
activity_sid = WORKSPACE_INFO.activities[activity].sid
41
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
42
workspace_sid = WORKSPACE_INFO.workspace_sid
43
44
client.workspaces(workspace_sid)\
45
.workers(worker_sid)\
46
.update(activity_sid=activity_sid)
47
48
resp = MessagingResponse()
49
message = 'Your status has changed to ' + activity
50
resp.message(message)
51
return HttpResponse(resp)
52
53
54
@csrf_exempt
55
def incoming_call(request):
56
""" Returns TwiML instructions to Twilio's POST requests """
57
resp = VoiceResponse()
58
gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")
59
gather.say("For Programmable SMS, press one. For Voice, press any other key.")
60
61
return HttpResponse(resp)
62
63
64
@csrf_exempt
65
def enqueue(request):
66
""" Parses a selected product, creating a Task on Task Router Workflow """
67
resp = VoiceResponse()
68
digits = request.POST['Digits']
69
selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
70
task = {'selected_product': selected_product}
71
72
enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)
73
enqueue.task(json.dumps(task))
74
75
return HttpResponse(resp)
76
77
78
@csrf_exempt
79
def assignment(request):
80
""" Task assignment """
81
response = {'instruction': 'dequeue',
82
'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}
83
return JsonResponse(response)
84
85
86
@csrf_exempt
87
def events(request):
88
""" Events callback for missed calls """
89
POST = request.POST
90
event_type = POST.get('EventType')
91
task_events = ['workflow.timeout', 'task.canceled']
92
worker_event = 'worker.activity.update'
93
94
if event_type in task_events:
95
task_attributes = json.loads(POST['TaskAttributes'])
96
_save_missed_call(task_attributes)
97
if event_type == 'workflow.timeout':
98
_voicemail(task_attributes['call_sid'])
99
elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
100
message = 'Your status has changed to Offline. Reply with '\
101
'"On" to get back Online'
102
worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
103
sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)
104
105
return HttpResponse('')
106
107
108
def _voicemail(call_sid):
109
msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
110
route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
111
route_call(call_sid, route_url)
112
113
114
def route_call(call_sid, route_url):
115
client = Client(ACCOUNT_SID, AUTH_TOKEN)
116
client.api.calls(call_sid).update(url=route_url)
117
118
119
def _save_missed_call(task_attributes):
120
MissedCall.objects.create(
121
phone_number=task_attributes['from'],
122
selected_product=task_attributes['selected_product'])
123
124
125
# Only used by the tests in order to patch requests before any call is made
126
def setup_workspace():
127
global WORKSPACE_INFO
128
WORKSPACE_INFO = workspace.setup()

Most of the features of our application are implemented. The last piece is allowing the Workers to change their availability status. Let's see how to do that next.


Change a Worker's Activity

change-a-workers-activity page anchor

We have created this endpoint, so a worker can send an SMS message to the support line with the command "On" or "Off" to change their availability status.

This is important as a worker's activity will change to Offline when they miss a call. When this happens, they receive an SMS letting them know that their activity has changed, and that they can reply with the On command to make themselves available for incoming calls again.

Changing a Worker's Activity

changing-a-workers-activity page anchor

task_router/views.py

1
import json
2
from urllib.parse import quote_plus
3
4
from django.conf import settings
5
from django.http import HttpResponse, JsonResponse
6
from django.shortcuts import render
7
from django.urls import reverse
8
from django.views.decorators.csrf import csrf_exempt
9
from twilio.rest import Client
10
from twilio.twiml.messaging_response import MessagingResponse
11
from twilio.twiml.voice_response import VoiceResponse
12
13
from . import sms_sender, workspace
14
from .models import MissedCall
15
16
if not getattr(settings, 'TESTING', False):
17
WORKSPACE_INFO = workspace.setup()
18
else:
19
WORKSPACE_INFO = None
20
21
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
22
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
23
TWILIO_NUMBER = settings.TWILIO_NUMBER
24
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS
25
26
27
def root(request):
28
""" Renders a missed calls list, with product and phone number """
29
missed_calls = MissedCall.objects.order_by('-created')
30
return render(request, 'index.html', {
31
'missed_calls': missed_calls
32
})
33
34
35
@csrf_exempt
36
def incoming_sms(request):
37
""" Changes worker activity and returns a confirmation """
38
client = Client(ACCOUNT_SID, AUTH_TOKEN)
39
activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
40
activity_sid = WORKSPACE_INFO.activities[activity].sid
41
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
42
workspace_sid = WORKSPACE_INFO.workspace_sid
43
44
client.workspaces(workspace_sid)\
45
.workers(worker_sid)\
46
.update(activity_sid=activity_sid)
47
48
resp = MessagingResponse()
49
message = 'Your status has changed to ' + activity
50
resp.message(message)
51
return HttpResponse(resp)
52
53
54
@csrf_exempt
55
def incoming_call(request):
56
""" Returns TwiML instructions to Twilio's POST requests """
57
resp = VoiceResponse()
58
gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")
59
gather.say("For Programmable SMS, press one. For Voice, press any other key.")
60
61
return HttpResponse(resp)
62
63
64
@csrf_exempt
65
def enqueue(request):
66
""" Parses a selected product, creating a Task on Task Router Workflow """
67
resp = VoiceResponse()
68
digits = request.POST['Digits']
69
selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
70
task = {'selected_product': selected_product}
71
72
enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)
73
enqueue.task(json.dumps(task))
74
75
return HttpResponse(resp)
76
77
78
@csrf_exempt
79
def assignment(request):
80
""" Task assignment """
81
response = {'instruction': 'dequeue',
82
'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}
83
return JsonResponse(response)
84
85
86
@csrf_exempt
87
def events(request):
88
""" Events callback for missed calls """
89
POST = request.POST
90
event_type = POST.get('EventType')
91
task_events = ['workflow.timeout', 'task.canceled']
92
worker_event = 'worker.activity.update'
93
94
if event_type in task_events:
95
task_attributes = json.loads(POST['TaskAttributes'])
96
_save_missed_call(task_attributes)
97
if event_type == 'workflow.timeout':
98
_voicemail(task_attributes['call_sid'])
99
elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
100
message = 'Your status has changed to Offline. Reply with '\
101
'"On" to get back Online'
102
worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
103
sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)
104
105
return HttpResponse('')
106
107
108
def _voicemail(call_sid):
109
msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
110
route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
111
route_call(call_sid, route_url)
112
113
114
def route_call(call_sid, route_url):
115
client = Client(ACCOUNT_SID, AUTH_TOKEN)
116
client.api.calls(call_sid).update(url=route_url)
117
118
119
def _save_missed_call(task_attributes):
120
MissedCall.objects.create(
121
phone_number=task_attributes['from'],
122
selected_product=task_attributes['selected_product'])
123
124
125
# Only used by the tests in order to patch requests before any call is made
126
def setup_workspace():
127
global WORKSPACE_INFO
128
WORKSPACE_INFO = workspace.setup()

Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.


If you're a Python developer working with Twilio, you might enjoy these other tutorials:

Appointment-Reminders

Automate the process of reaching out to your customers prior to an upcoming appointment.

Automated-Survey-Django(link takes you to an external page)

Instantly collect structured data from your users with a survey conducted over a call or SMS text messages.