Dynamic call center with Python and Django
This tutorial explains how to automate call routing from customers to your support agents. In this example, customers select a product and are then connected to a specialist for that product. If no one is available, the customer's number is saved so that an agent can call them back.
When complete, your application does the following:
- Configures a Workspace using the Twilio TaskRouter REST API.
- Listens for incoming calls and lets the user select a product with the dial pad.
- Creates a Task with the selected product and lets TaskRouter handle it.
- Stores missed calls so agents can return the call to customers.
- Redirects users to a voice mail when no one answers the call.
- Allows agents to change their status (Available/Offline) via SMS.
For TaskRouter to handle the Tasks, you need to configure a Workspace. You can do this in the TaskRouter Console or programmatically using the TaskRouter REST API.
Your Django application will do this setup when the app starts.
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. For example, idle, offline, or busy
In order to build a client for this API, you need a TWILIO_ACCOUNT_SID
and TWILIO_AUTH_TOKEN
which you can find in Twilio Console. The function build_client
configures and returns a TwilioTaskRouterClient, which is provided by the Twilio Python library.
task_router/workspace.py
1import json23from django.conf import settings4from twilio.rest import Client56HOST = settings.HOST7ALICE_NUMBER = settings.ALICE_NUMBER8BOB_NUMBER = settings.BOB_NUMBER9WORKSPACE_NAME = 'Twilio Workspace'101112def first(items):13return items[0] if items else None141516def build_client():17account_sid = settings.TWILIO_ACCOUNT_SID18auth_token = settings.TWILIO_AUTH_TOKEN19return Client(account_sid, auth_token)202122CACHE = {}232425def activities_dict(client, workspace_sid):26activities = client.taskrouter.workspaces(workspace_sid)\27.activities.list()2829return {activity.friendly_name: activity for activity in activities}303132class WorkspaceInfo:3334def __init__(self, workspace, workflow, activities, workers):35self.workflow_sid = workflow.sid36self.workspace_sid = workspace.sid37self.activities = activities38self.post_work_activity_sid = activities['Available'].sid39self.workers = workers404142def setup():43client = build_client()44if 'WORKSPACE_INFO' not in CACHE:45workspace = create_workspace(client)46activities = activities_dict(client, workspace.sid)47workers = create_workers(client, workspace, activities)48queues = create_task_queues(client, workspace, activities)49workflow = create_workflow(client, workspace, queues)50CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)51return CACHE['WORKSPACE_INFO']525354def create_workspace(client):55try:56workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))57client.taskrouter.workspaces(workspace.sid).delete()58except Exception:59pass6061events_callback = HOST + '/events/'6263return client.taskrouter.workspaces.create(64friendly_name=WORKSPACE_NAME,65event_callback_url=events_callback,66template=None)676869def create_workers(client, workspace, activities):70alice_attributes = {71"products": ["ProgrammableVoice"],72"contact_uri": ALICE_NUMBER73}7475alice = client.taskrouter.workspaces(workspace.sid)\76.workers.create(friendly_name='Alice',77attributes=json.dumps(alice_attributes))7879bob_attributes = {80"products": ["ProgrammableSMS"],81"contact_uri": BOB_NUMBER82}8384bob = client.taskrouter.workspaces(workspace.sid)\85.workers.create(friendly_name='Bob',86attributes=json.dumps(bob_attributes))8788return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}899091def create_task_queues(client, workspace, activities):92default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\93.create(friendly_name='Default',94assignment_activity_sid=activities['Unavailable'].sid,95target_workers='1==1')9697sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\98.create(friendly_name='SMS',99assignment_activity_sid=activities['Unavailable'].sid,100target_workers='"ProgrammableSMS" in products')101102voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\103.create(friendly_name='Voice',104assignment_activity_sid=activities['Unavailable'].sid,105target_workers='"ProgrammableVoice" in products')106107return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}108109110def create_workflow(client, workspace, queues):111defaultTarget = {112'queue': queues['sms'].sid,113'priority': 5,114'timeout': 30115}116117smsTarget = {118'queue': queues['sms'].sid,119'priority': 5,120'timeout': 30121}122123voiceTarget = {124'queue': queues['voice'].sid,125'priority': 5,126'timeout': 30127}128129default_filter = {130'filter_friendly_name': 'Default Filter',131'queue': queues['default'].sid,132'Expression': '1==1',133'priority': 1,134'timeout': 30135}136137voiceFilter = {138'filter_friendly_name': 'Voice Filter',139'expression': 'selected_product=="ProgrammableVoice"',140'targets': [voiceTarget, defaultTarget]141}142143smsFilter = {144'filter_friendly_name': 'SMS Filter',145'expression': 'selected_product=="ProgrammableSMS"',146'targets': [smsTarget, defaultTarget]147}148149config = {150'task_routing': {151'filters': [voiceFilter, smsFilter],152'default_filter': default_filter153}154}155156callback_url = HOST + '/assignment/'157158return client.taskrouter.workspaces(workspace.sid)\159.workflows.create(friendly_name='Sales',160assignment_callback_url=callback_url,161fallback_assignment_callback_url=callback_url,162task_reservation_timeout=15,163configuration=json.dumps(config))
Before creating a workspace, you need to delete any others with the same friendly_name
as the one you're trying to create. To create a workspace, you need to provide a friendly_name
and a event_callback_url
where a requests will be made every time an event is triggered in your workspace.
task_router/workspace.py
1import json23from django.conf import settings4from twilio.rest import Client56HOST = settings.HOST7ALICE_NUMBER = settings.ALICE_NUMBER8BOB_NUMBER = settings.BOB_NUMBER9WORKSPACE_NAME = 'Twilio Workspace'101112def first(items):13return items[0] if items else None141516def build_client():17account_sid = settings.TWILIO_ACCOUNT_SID18auth_token = settings.TWILIO_AUTH_TOKEN19return Client(account_sid, auth_token)202122CACHE = {}232425def activities_dict(client, workspace_sid):26activities = client.taskrouter.workspaces(workspace_sid)\27.activities.list()2829return {activity.friendly_name: activity for activity in activities}303132class WorkspaceInfo:3334def __init__(self, workspace, workflow, activities, workers):35self.workflow_sid = workflow.sid36self.workspace_sid = workspace.sid37self.activities = activities38self.post_work_activity_sid = activities['Available'].sid39self.workers = workers404142def setup():43client = build_client()44if 'WORKSPACE_INFO' not in CACHE:45workspace = create_workspace(client)46activities = activities_dict(client, workspace.sid)47workers = create_workers(client, workspace, activities)48queues = create_task_queues(client, workspace, activities)49workflow = create_workflow(client, workspace, queues)50CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)51return CACHE['WORKSPACE_INFO']525354def create_workspace(client):55try:56workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))57client.taskrouter.workspaces(workspace.sid).delete()58except Exception:59pass6061events_callback = HOST + '/events/'6263return client.taskrouter.workspaces.create(64friendly_name=WORKSPACE_NAME,65event_callback_url=events_callback,66template=None)676869def create_workers(client, workspace, activities):70alice_attributes = {71"products": ["ProgrammableVoice"],72"contact_uri": ALICE_NUMBER73}7475alice = client.taskrouter.workspaces(workspace.sid)\76.workers.create(friendly_name='Alice',77attributes=json.dumps(alice_attributes))7879bob_attributes = {80"products": ["ProgrammableSMS"],81"contact_uri": BOB_NUMBER82}8384bob = client.taskrouter.workspaces(workspace.sid)\85.workers.create(friendly_name='Bob',86attributes=json.dumps(bob_attributes))8788return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}899091def create_task_queues(client, workspace, activities):92default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\93.create(friendly_name='Default',94assignment_activity_sid=activities['Unavailable'].sid,95target_workers='1==1')9697sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\98.create(friendly_name='SMS',99assignment_activity_sid=activities['Unavailable'].sid,100target_workers='"ProgrammableSMS" in products')101102voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\103.create(friendly_name='Voice',104assignment_activity_sid=activities['Unavailable'].sid,105target_workers='"ProgrammableVoice" in products')106107return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}108109110def create_workflow(client, workspace, queues):111defaultTarget = {112'queue': queues['sms'].sid,113'priority': 5,114'timeout': 30115}116117smsTarget = {118'queue': queues['sms'].sid,119'priority': 5,120'timeout': 30121}122123voiceTarget = {124'queue': queues['voice'].sid,125'priority': 5,126'timeout': 30127}128129default_filter = {130'filter_friendly_name': 'Default Filter',131'queue': queues['default'].sid,132'Expression': '1==1',133'priority': 1,134'timeout': 30135}136137voiceFilter = {138'filter_friendly_name': 'Voice Filter',139'expression': 'selected_product=="ProgrammableVoice"',140'targets': [voiceTarget, defaultTarget]141}142143smsFilter = {144'filter_friendly_name': 'SMS Filter',145'expression': 'selected_product=="ProgrammableSMS"',146'targets': [smsTarget, defaultTarget]147}148149config = {150'task_routing': {151'filters': [voiceFilter, smsFilter],152'default_filter': default_filter153}154}155156callback_url = HOST + '/assignment/'157158return client.taskrouter.workspaces(workspace.sid)\159.workflows.create(friendly_name='Sales',160assignment_callback_url=callback_url,161fallback_assignment_callback_url=callback_url,162task_reservation_timeout=15,163configuration=json.dumps(config))
In the next step, you'll create workers for your new Workspace.
You'll create two workers: Bob and Alice. They each have two attributes: contact_uri
, which is a phone number, and products
, a list of products each worker specializes in. You also need to specify an activity_sid
and a name for each worker. The selected activity defines the status of the worker.
A set of default activities is created with your workspace. Use the Idle
activity to make a worker available for incoming calls.
task_router/workspace.py
1import json23from django.conf import settings4from twilio.rest import Client56HOST = settings.HOST7ALICE_NUMBER = settings.ALICE_NUMBER8BOB_NUMBER = settings.BOB_NUMBER9WORKSPACE_NAME = 'Twilio Workspace'101112def first(items):13return items[0] if items else None141516def build_client():17account_sid = settings.TWILIO_ACCOUNT_SID18auth_token = settings.TWILIO_AUTH_TOKEN19return Client(account_sid, auth_token)202122CACHE = {}232425def activities_dict(client, workspace_sid):26activities = client.taskrouter.workspaces(workspace_sid)\27.activities.list()2829return {activity.friendly_name: activity for activity in activities}303132class WorkspaceInfo:3334def __init__(self, workspace, workflow, activities, workers):35self.workflow_sid = workflow.sid36self.workspace_sid = workspace.sid37self.activities = activities38self.post_work_activity_sid = activities['Available'].sid39self.workers = workers404142def setup():43client = build_client()44if 'WORKSPACE_INFO' not in CACHE:45workspace = create_workspace(client)46activities = activities_dict(client, workspace.sid)47workers = create_workers(client, workspace, activities)48queues = create_task_queues(client, workspace, activities)49workflow = create_workflow(client, workspace, queues)50CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)51return CACHE['WORKSPACE_INFO']525354def create_workspace(client):55try:56workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))57client.taskrouter.workspaces(workspace.sid).delete()58except Exception:59pass6061events_callback = HOST + '/events/'6263return client.taskrouter.workspaces.create(64friendly_name=WORKSPACE_NAME,65event_callback_url=events_callback,66template=None)676869def create_workers(client, workspace, activities):70alice_attributes = {71"products": ["ProgrammableVoice"],72"contact_uri": ALICE_NUMBER73}7475alice = client.taskrouter.workspaces(workspace.sid)\76.workers.create(friendly_name='Alice',77attributes=json.dumps(alice_attributes))7879bob_attributes = {80"products": ["ProgrammableSMS"],81"contact_uri": BOB_NUMBER82}8384bob = client.taskrouter.workspaces(workspace.sid)\85.workers.create(friendly_name='Bob',86attributes=json.dumps(bob_attributes))8788return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}899091def create_task_queues(client, workspace, activities):92default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\93.create(friendly_name='Default',94assignment_activity_sid=activities['Unavailable'].sid,95target_workers='1==1')9697sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\98.create(friendly_name='SMS',99assignment_activity_sid=activities['Unavailable'].sid,100target_workers='"ProgrammableSMS" in products')101102voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\103.create(friendly_name='Voice',104assignment_activity_sid=activities['Unavailable'].sid,105target_workers='"ProgrammableVoice" in products')106107return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}108109110def create_workflow(client, workspace, queues):111defaultTarget = {112'queue': queues['sms'].sid,113'priority': 5,114'timeout': 30115}116117smsTarget = {118'queue': queues['sms'].sid,119'priority': 5,120'timeout': 30121}122123voiceTarget = {124'queue': queues['voice'].sid,125'priority': 5,126'timeout': 30127}128129default_filter = {130'filter_friendly_name': 'Default Filter',131'queue': queues['default'].sid,132'Expression': '1==1',133'priority': 1,134'timeout': 30135}136137voiceFilter = {138'filter_friendly_name': 'Voice Filter',139'expression': 'selected_product=="ProgrammableVoice"',140'targets': [voiceTarget, defaultTarget]141}142143smsFilter = {144'filter_friendly_name': 'SMS Filter',145'expression': 'selected_product=="ProgrammableSMS"',146'targets': [smsTarget, defaultTarget]147}148149config = {150'task_routing': {151'filters': [voiceFilter, smsFilter],152'default_filter': default_filter153}154}155156callback_url = HOST + '/assignment/'157158return client.taskrouter.workspaces(workspace.sid)\159.workflows.create(friendly_name='Sales',160assignment_callback_url=callback_url,161fallback_assignment_callback_url=callback_url,162task_reservation_timeout=15,163configuration=json.dumps(config))
After creating your workers, set up the Task Queues.
Each Task Queue needs a friendly_name
and a targetWorkers
, which is an expression to match Workers. Use these Task Queues:
SMS
: Targets Workers specialized in Programmable SMS, like Bob, using the expression'"ProgrammableSMS" in products'
.Voice
: Targets Workers specialized in Programmable Voice, like Alice, using the expression'"ProgrammableVoice" in products'
.Default
: Targets all users and can be used when there's no specialist for the chosen product. You can use the"1==1"
expression here.
task_router/workspace.py
1import json23from django.conf import settings4from twilio.rest import Client56HOST = settings.HOST7ALICE_NUMBER = settings.ALICE_NUMBER8BOB_NUMBER = settings.BOB_NUMBER9WORKSPACE_NAME = 'Twilio Workspace'101112def first(items):13return items[0] if items else None141516def build_client():17account_sid = settings.TWILIO_ACCOUNT_SID18auth_token = settings.TWILIO_AUTH_TOKEN19return Client(account_sid, auth_token)202122CACHE = {}232425def activities_dict(client, workspace_sid):26activities = client.taskrouter.workspaces(workspace_sid)\27.activities.list()2829return {activity.friendly_name: activity for activity in activities}303132class WorkspaceInfo:3334def __init__(self, workspace, workflow, activities, workers):35self.workflow_sid = workflow.sid36self.workspace_sid = workspace.sid37self.activities = activities38self.post_work_activity_sid = activities['Available'].sid39self.workers = workers404142def setup():43client = build_client()44if 'WORKSPACE_INFO' not in CACHE:45workspace = create_workspace(client)46activities = activities_dict(client, workspace.sid)47workers = create_workers(client, workspace, activities)48queues = create_task_queues(client, workspace, activities)49workflow = create_workflow(client, workspace, queues)50CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)51return CACHE['WORKSPACE_INFO']525354def create_workspace(client):55try:56workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))57client.taskrouter.workspaces(workspace.sid).delete()58except Exception:59pass6061events_callback = HOST + '/events/'6263return client.taskrouter.workspaces.create(64friendly_name=WORKSPACE_NAME,65event_callback_url=events_callback,66template=None)676869def create_workers(client, workspace, activities):70alice_attributes = {71"products": ["ProgrammableVoice"],72"contact_uri": ALICE_NUMBER73}7475alice = client.taskrouter.workspaces(workspace.sid)\76.workers.create(friendly_name='Alice',77attributes=json.dumps(alice_attributes))7879bob_attributes = {80"products": ["ProgrammableSMS"],81"contact_uri": BOB_NUMBER82}8384bob = client.taskrouter.workspaces(workspace.sid)\85.workers.create(friendly_name='Bob',86attributes=json.dumps(bob_attributes))8788return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}899091def create_task_queues(client, workspace, activities):92default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\93.create(friendly_name='Default',94assignment_activity_sid=activities['Unavailable'].sid,95target_workers='1==1')9697sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\98.create(friendly_name='SMS',99assignment_activity_sid=activities['Unavailable'].sid,100target_workers='"ProgrammableSMS" in products')101102voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\103.create(friendly_name='Voice',104assignment_activity_sid=activities['Unavailable'].sid,105target_workers='"ProgrammableVoice" in products')106107return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}108109110def create_workflow(client, workspace, queues):111defaultTarget = {112'queue': queues['sms'].sid,113'priority': 5,114'timeout': 30115}116117smsTarget = {118'queue': queues['sms'].sid,119'priority': 5,120'timeout': 30121}122123voiceTarget = {124'queue': queues['voice'].sid,125'priority': 5,126'timeout': 30127}128129default_filter = {130'filter_friendly_name': 'Default Filter',131'queue': queues['default'].sid,132'Expression': '1==1',133'priority': 1,134'timeout': 30135}136137voiceFilter = {138'filter_friendly_name': 'Voice Filter',139'expression': 'selected_product=="ProgrammableVoice"',140'targets': [voiceTarget, defaultTarget]141}142143smsFilter = {144'filter_friendly_name': 'SMS Filter',145'expression': 'selected_product=="ProgrammableSMS"',146'targets': [smsTarget, defaultTarget]147}148149config = {150'task_routing': {151'filters': [voiceFilter, smsFilter],152'default_filter': default_filter153}154}155156callback_url = HOST + '/assignment/'157158return client.taskrouter.workspaces(workspace.sid)\159.workflows.create(friendly_name='Sales',160assignment_callback_url=callback_url,161fallback_assignment_callback_url=callback_url,162task_reservation_timeout=15,163configuration=json.dumps(config))
The last remaining step is to create a Workflow.
Use the following parameters:
friendly_name
: The name of a Workflow.assignment_callback_url
andfallback_assignment_callback_url
: The public URL where a request is made when this Workflow assigns a Task to a Worker. You'll learn how to implement this URL in the next steps.task_reservation_timeout
: The maximum time you want to wait until a Worker is available for handling a Task.configuration
: A set of rules for placing Tasks into Task Queues. The routing configuration takes a Task attribute and matches it with Task Queues. This application's Workflow rules are defined as:"selected_product==\ "ProgrammableSMS\""
expression forSMS
Task Queue. This expression matches any Task withProgrammableSMS
as theselected_product
attribute."selected_product==\ "ProgrammableVoice\""
expression forVoice
Task Queue.
task_router/workspace.py
1import json23from django.conf import settings4from twilio.rest import Client56HOST = settings.HOST7ALICE_NUMBER = settings.ALICE_NUMBER8BOB_NUMBER = settings.BOB_NUMBER9WORKSPACE_NAME = 'Twilio Workspace'101112def first(items):13return items[0] if items else None141516def build_client():17account_sid = settings.TWILIO_ACCOUNT_SID18auth_token = settings.TWILIO_AUTH_TOKEN19return Client(account_sid, auth_token)202122CACHE = {}232425def activities_dict(client, workspace_sid):26activities = client.taskrouter.workspaces(workspace_sid)\27.activities.list()2829return {activity.friendly_name: activity for activity in activities}303132class WorkspaceInfo:3334def __init__(self, workspace, workflow, activities, workers):35self.workflow_sid = workflow.sid36self.workspace_sid = workspace.sid37self.activities = activities38self.post_work_activity_sid = activities['Available'].sid39self.workers = workers404142def setup():43client = build_client()44if 'WORKSPACE_INFO' not in CACHE:45workspace = create_workspace(client)46activities = activities_dict(client, workspace.sid)47workers = create_workers(client, workspace, activities)48queues = create_task_queues(client, workspace, activities)49workflow = create_workflow(client, workspace, queues)50CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)51return CACHE['WORKSPACE_INFO']525354def create_workspace(client):55try:56workspace = first(client.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))57client.taskrouter.workspaces(workspace.sid).delete()58except Exception:59pass6061events_callback = HOST + '/events/'6263return client.taskrouter.workspaces.create(64friendly_name=WORKSPACE_NAME,65event_callback_url=events_callback,66template=None)676869def create_workers(client, workspace, activities):70alice_attributes = {71"products": ["ProgrammableVoice"],72"contact_uri": ALICE_NUMBER73}7475alice = client.taskrouter.workspaces(workspace.sid)\76.workers.create(friendly_name='Alice',77attributes=json.dumps(alice_attributes))7879bob_attributes = {80"products": ["ProgrammableSMS"],81"contact_uri": BOB_NUMBER82}8384bob = client.taskrouter.workspaces(workspace.sid)\85.workers.create(friendly_name='Bob',86attributes=json.dumps(bob_attributes))8788return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}899091def create_task_queues(client, workspace, activities):92default_queue = client.taskrouter.workspaces(workspace.sid).task_queues\93.create(friendly_name='Default',94assignment_activity_sid=activities['Unavailable'].sid,95target_workers='1==1')9697sms_queue = client.taskrouter.workspaces(workspace.sid).task_queues\98.create(friendly_name='SMS',99assignment_activity_sid=activities['Unavailable'].sid,100target_workers='"ProgrammableSMS" in products')101102voice_queue = client.taskrouter.workspaces(workspace.sid).task_queues\103.create(friendly_name='Voice',104assignment_activity_sid=activities['Unavailable'].sid,105target_workers='"ProgrammableVoice" in products')106107return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}108109110def create_workflow(client, workspace, queues):111defaultTarget = {112'queue': queues['sms'].sid,113'priority': 5,114'timeout': 30115}116117smsTarget = {118'queue': queues['sms'].sid,119'priority': 5,120'timeout': 30121}122123voiceTarget = {124'queue': queues['voice'].sid,125'priority': 5,126'timeout': 30127}128129default_filter = {130'filter_friendly_name': 'Default Filter',131'queue': queues['default'].sid,132'Expression': '1==1',133'priority': 1,134'timeout': 30135}136137voiceFilter = {138'filter_friendly_name': 'Voice Filter',139'expression': 'selected_product=="ProgrammableVoice"',140'targets': [voiceTarget, defaultTarget]141}142143smsFilter = {144'filter_friendly_name': 'SMS Filter',145'expression': 'selected_product=="ProgrammableSMS"',146'targets': [smsTarget, defaultTarget]147}148149config = {150'task_routing': {151'filters': [voiceFilter, smsFilter],152'default_filter': default_filter153}154}155156callback_url = HOST + '/assignment/'157158return client.taskrouter.workspaces(workspace.sid)\159.workflows.create(friendly_name='Sales',160assignment_callback_url=callback_url,161fallback_assignment_callback_url=callback_url,162task_reservation_timeout=15,163configuration=json.dumps(config))
Now that your workspace is completely set up, learn how you can use it to route calls.
Right after receiving a call, Twilio sends a request to the URL specified on the number's configuration.
The endpoint then processes the request and generates a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press to select one. The Gather verb allows you to capture the user's key press.
task_router/views.py
1import json2from urllib.parse import quote_plus34from django.conf import settings5from django.http import HttpResponse, JsonResponse6from django.shortcuts import render7from django.urls import reverse8from django.views.decorators.csrf import csrf_exempt9from twilio.rest import Client10from twilio.twiml.messaging_response import MessagingResponse11from twilio.twiml.voice_response import VoiceResponse1213from . import sms_sender, workspace14from .models import MissedCall1516if not getattr(settings, 'TESTING', False):17WORKSPACE_INFO = workspace.setup()18else:19WORKSPACE_INFO = None2021ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID22AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN23TWILIO_NUMBER = settings.TWILIO_NUMBER24EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS252627def root(request):28""" Renders a missed calls list, with product and phone number """29missed_calls = MissedCall.objects.order_by('-created')30return render(request, 'index.html', {31'missed_calls': missed_calls32})333435@csrf_exempt36def incoming_sms(request):37""" Changes worker activity and returns a confirmation """38client = Client(ACCOUNT_SID, AUTH_TOKEN)39activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'40activity_sid = WORKSPACE_INFO.activities[activity].sid41worker_sid = WORKSPACE_INFO.workers[request.POST['From']]42workspace_sid = WORKSPACE_INFO.workspace_sid4344client.workspaces(workspace_sid)\45.workers(worker_sid)\46.update(activity_sid=activity_sid)4748resp = MessagingResponse()49message = 'Your status has changed to ' + activity50resp.message(message)51return HttpResponse(resp)525354@csrf_exempt55def incoming_call(request):56""" Returns TwiML instructions to Twilio's POST requests """57resp = VoiceResponse()58gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")59gather.say("For Programmable SMS, press one. For Voice, press any other key.")6061return HttpResponse(resp)626364@csrf_exempt65def enqueue(request):66""" Parses a selected product, creating a Task on Task Router Workflow """67resp = VoiceResponse()68digits = request.POST['Digits']69selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'70task = {'selected_product': selected_product}7172enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)73enqueue.task(json.dumps(task))7475return HttpResponse(resp)767778@csrf_exempt79def assignment(request):80""" Task assignment """81response = {'instruction': 'dequeue',82'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}83return JsonResponse(response)848586@csrf_exempt87def events(request):88""" Events callback for missed calls """89POST = request.POST90event_type = POST.get('EventType')91task_events = ['workflow.timeout', 'task.canceled']92worker_event = 'worker.activity.update'9394if event_type in task_events:95task_attributes = json.loads(POST['TaskAttributes'])96_save_missed_call(task_attributes)97if event_type == 'workflow.timeout':98_voicemail(task_attributes['call_sid'])99elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':100message = 'Your status has changed to Offline. Reply with '\101'"On" to get back Online'102worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']103sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)104105return HttpResponse('')106107108def _voicemail(call_sid):109msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'110route_url = 'https://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)111route_call(call_sid, route_url)112113114def route_call(call_sid, route_url):115client = Client(ACCOUNT_SID, AUTH_TOKEN)116client.api.calls(call_sid).update(url=route_url)117118119def _save_missed_call(task_attributes):120MissedCall.objects.create(121phone_number=task_attributes['from'],122selected_product=task_attributes['selected_product'])123124125# Only used by the tests in order to patch requests before any call is made126def setup_workspace():127global WORKSPACE_INFO128WORKSPACE_INFO = workspace.setup()
You just asked the caller to choose a product, next you'll use their choice to create the appropriate Task.
TwiML™ Voice: <Enqueue>Create a 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
is created based on the pressed digit with the selected_product
as an attribute. The Workflow takes this Task's attributes and matches 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.
Use the Enqueue
verb with a WorkflowSid
attribute to integrate with TaskRouter. Then the voice call is put on hold while TaskRouter tries to find an available Worker to handle this Task.
task_router/views.py
1import json2from urllib.parse import quote_plus34from django.conf import settings5from django.http import HttpResponse, JsonResponse6from django.shortcuts import render7from django.urls import reverse8from django.views.decorators.csrf import csrf_exempt9from twilio.rest import Client10from twilio.twiml.messaging_response import MessagingResponse11from twilio.twiml.voice_response import VoiceResponse1213from . import sms_sender, workspace14from .models import MissedCall1516if not getattr(settings, 'TESTING', False):17WORKSPACE_INFO = workspace.setup()18else:19WORKSPACE_INFO = None2021ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID22AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN23TWILIO_NUMBER = settings.TWILIO_NUMBER24EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS252627def root(request):28""" Renders a missed calls list, with product and phone number """29missed_calls = MissedCall.objects.order_by('-created')30return render(request, 'index.html', {31'missed_calls': missed_calls32})333435@csrf_exempt36def incoming_sms(request):37""" Changes worker activity and returns a confirmation """38client = Client(ACCOUNT_SID, AUTH_TOKEN)39activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'40activity_sid = WORKSPACE_INFO.activities[activity].sid41worker_sid = WORKSPACE_INFO.workers[request.POST['From']]42workspace_sid = WORKSPACE_INFO.workspace_sid4344client.workspaces(workspace_sid)\45.workers(worker_sid)\46.update(activity_sid=activity_sid)4748resp = MessagingResponse()49message = 'Your status has changed to ' + activity50resp.message(message)51return HttpResponse(resp)525354@csrf_exempt55def incoming_call(request):56""" Returns TwiML instructions to Twilio's POST requests """57resp = VoiceResponse()58gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")59gather.say("For Programmable SMS, press one. For Voice, press any other key.")6061return HttpResponse(resp)626364@csrf_exempt65def enqueue(request):66""" Parses a selected product, creating a Task on Task Router Workflow """67resp = VoiceResponse()68digits = request.POST['Digits']69selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'70task = {'selected_product': selected_product}7172enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)73enqueue.task(json.dumps(task))7475return HttpResponse(resp)767778@csrf_exempt79def assignment(request):80""" Task assignment """81response = {'instruction': 'dequeue',82'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}83return JsonResponse(response)848586@csrf_exempt87def events(request):88""" Events callback for missed calls """89POST = request.POST90event_type = POST.get('EventType')91task_events = ['workflow.timeout', 'task.canceled']92worker_event = 'worker.activity.update'9394if event_type in task_events:95task_attributes = json.loads(POST['TaskAttributes'])96_save_missed_call(task_attributes)97if event_type == 'workflow.timeout':98_voicemail(task_attributes['call_sid'])99elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':100message = 'Your status has changed to Offline. Reply with '\101'"On" to get back Online'102worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']103sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)104105return HttpResponse('')106107108def _voicemail(call_sid):109msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'110route_url = 'https://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)111route_call(call_sid, route_url)112113114def route_call(call_sid, route_url):115client = Client(ACCOUNT_SID, AUTH_TOKEN)116client.api.calls(call_sid).update(url=route_url)117118119def _save_missed_call(task_attributes):120MissedCall.objects.create(121phone_number=task_attributes['from'],122selected_product=task_attributes['selected_product'])123124125# Only used by the tests in order to patch requests before any call is made126def setup_workspace():127global WORKSPACE_INFO128WORKSPACE_INFO = workspace.setup()
After sending a Task to Twilio, you can tell TaskRouter which Worker to use to execute that task.
When TaskRouter selects a Worker, it does the following:
- Sets the Task's Assignment Status to 'reserved'.
- Generates a Reservation instance that links the Task to the selected Worker.
- At the same time it creates a Reservation, it makes a
POST
request to the Workflow's AssignmentCallbackURL, which you 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 because you can configure how the Worker handles a Task. You could send a text, email, push notification, or make a call.
Since you created this Task during a voice call with an Enqueue
verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If you don't specify a to
parameter with a phone number, TaskRouter picks the Worker's contact_uri
attribute.
You can also send a post_work_activity_sid
, which tells TaskRouter which Activity to assign this worker after the call ends.
task_router/views.py
1import json2from urllib.parse import quote_plus34from django.conf import settings5from django.http import HttpResponse, JsonResponse6from django.shortcuts import render7from django.urls import reverse8from django.views.decorators.csrf import csrf_exempt9from twilio.rest import Client10from twilio.twiml.messaging_response import MessagingResponse11from twilio.twiml.voice_response import VoiceResponse1213from . import sms_sender, workspace14from .models import MissedCall1516if not getattr(settings, 'TESTING', False):17WORKSPACE_INFO = workspace.setup()18else:19WORKSPACE_INFO = None2021ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID22AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN23TWILIO_NUMBER = settings.TWILIO_NUMBER24EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS252627def root(request):28""" Renders a missed calls list, with product and phone number """29missed_calls = MissedCall.objects.order_by('-created')30return render(request, 'index.html', {31'missed_calls': missed_calls32})333435@csrf_exempt36def incoming_sms(request):37""" Changes worker activity and returns a confirmation """38client = Client(ACCOUNT_SID, AUTH_TOKEN)39activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'40activity_sid = WORKSPACE_INFO.activities[activity].sid41worker_sid = WORKSPACE_INFO.workers[request.POST['From']]42workspace_sid = WORKSPACE_INFO.workspace_sid4344client.workspaces(workspace_sid)\45.workers(worker_sid)\46.update(activity_sid=activity_sid)4748resp = MessagingResponse()49message = 'Your status has changed to ' + activity50resp.message(message)51return HttpResponse(resp)525354@csrf_exempt55def incoming_call(request):56""" Returns TwiML instructions to Twilio's POST requests """57resp = VoiceResponse()58gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")59gather.say("For Programmable SMS, press one. For Voice, press any other key.")6061return HttpResponse(resp)626364@csrf_exempt65def enqueue(request):66""" Parses a selected product, creating a Task on Task Router Workflow """67resp = VoiceResponse()68digits = request.POST['Digits']69selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'70task = {'selected_product': selected_product}7172enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)73enqueue.task(json.dumps(task))7475return HttpResponse(resp)767778@csrf_exempt79def assignment(request):80""" Task assignment """81response = {'instruction': 'dequeue',82'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}83return JsonResponse(response)848586@csrf_exempt87def events(request):88""" Events callback for missed calls """89POST = request.POST90event_type = POST.get('EventType')91task_events = ['workflow.timeout', 'task.canceled']92worker_event = 'worker.activity.update'9394if event_type in task_events:95task_attributes = json.loads(POST['TaskAttributes'])96_save_missed_call(task_attributes)97if event_type == 'workflow.timeout':98_voicemail(task_attributes['call_sid'])99elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':100message = 'Your status has changed to Offline. Reply with '\101'"On" to get back Online'102worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']103sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)104105return HttpResponse('')106107108def _voicemail(call_sid):109msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'110route_url = 'https://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)111route_call(call_sid, route_url)112113114def route_call(call_sid, route_url):115client = Client(ACCOUNT_SID, AUTH_TOKEN)116client.api.calls(call_sid).update(url=route_url)117118119def _save_missed_call(task_attributes):120MissedCall.objects.create(121phone_number=task_attributes['from'],122selected_product=task_attributes['selected_product'])123124125# Only used by the tests in order to patch requests before any call is made126def setup_workspace():127global WORKSPACE_INFO128WORKSPACE_INFO = workspace.setup()
Now that TaskRouter can route your Tasks properly, set up a process for handling missed calls.
This endpoint is called after each TaskRouter Event is triggered. In your application, you're trying to collect missed calls, so you want 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 you'll use TwilioRestClient to route this call to a Voicemail Twimlet. Twimlets are tiny web applications for voice. This one generates a TwiML
response using Say
verb and record a message using Record
verb. The recorded message is then be transcribed and sent to the email address configured.
Note that the following code also listens 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 you to collect information from customers who hang up before the Workflow times out.
task_router/views.py
1import json2from urllib.parse import quote_plus34from django.conf import settings5from django.http import HttpResponse, JsonResponse6from django.shortcuts import render7from django.urls import reverse8from django.views.decorators.csrf import csrf_exempt9from twilio.rest import Client10from twilio.twiml.messaging_response import MessagingResponse11from twilio.twiml.voice_response import VoiceResponse1213from . import sms_sender, workspace14from .models import MissedCall1516if not getattr(settings, 'TESTING', False):17WORKSPACE_INFO = workspace.setup()18else:19WORKSPACE_INFO = None2021ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID22AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN23TWILIO_NUMBER = settings.TWILIO_NUMBER24EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS252627def root(request):28""" Renders a missed calls list, with product and phone number """29missed_calls = MissedCall.objects.order_by('-created')30return render(request, 'index.html', {31'missed_calls': missed_calls32})333435@csrf_exempt36def incoming_sms(request):37""" Changes worker activity and returns a confirmation """38client = Client(ACCOUNT_SID, AUTH_TOKEN)39activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'40activity_sid = WORKSPACE_INFO.activities[activity].sid41worker_sid = WORKSPACE_INFO.workers[request.POST['From']]42workspace_sid = WORKSPACE_INFO.workspace_sid4344client.workspaces(workspace_sid)\45.workers(worker_sid)\46.update(activity_sid=activity_sid)4748resp = MessagingResponse()49message = 'Your status has changed to ' + activity50resp.message(message)51return HttpResponse(resp)525354@csrf_exempt55def incoming_call(request):56""" Returns TwiML instructions to Twilio's POST requests """57resp = VoiceResponse()58gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")59gather.say("For Programmable SMS, press one. For Voice, press any other key.")6061return HttpResponse(resp)626364@csrf_exempt65def enqueue(request):66""" Parses a selected product, creating a Task on Task Router Workflow """67resp = VoiceResponse()68digits = request.POST['Digits']69selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'70task = {'selected_product': selected_product}7172enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)73enqueue.task(json.dumps(task))7475return HttpResponse(resp)767778@csrf_exempt79def assignment(request):80""" Task assignment """81response = {'instruction': 'dequeue',82'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}83return JsonResponse(response)848586@csrf_exempt87def events(request):88""" Events callback for missed calls """89POST = request.POST90event_type = POST.get('EventType')91task_events = ['workflow.timeout', 'task.canceled']92worker_event = 'worker.activity.update'9394if event_type in task_events:95task_attributes = json.loads(POST['TaskAttributes'])96_save_missed_call(task_attributes)97if event_type == 'workflow.timeout':98_voicemail(task_attributes['call_sid'])99elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':100message = 'Your status has changed to Offline. Reply with '\101'"On" to get back Online'102worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']103sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)104105return HttpResponse('')106107108def _voicemail(call_sid):109msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'110route_url = 'https://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)111route_call(call_sid, route_url)112113114def route_call(call_sid, route_url):115client = Client(ACCOUNT_SID, AUTH_TOKEN)116client.api.calls(call_sid).update(url=route_url)117118119def _save_missed_call(task_attributes):120MissedCall.objects.create(121phone_number=task_attributes['from'],122selected_product=task_attributes['selected_product'])123124125# Only used by the tests in order to patch requests before any call is made126def setup_workspace():127global WORKSPACE_INFO128WORKSPACE_INFO = workspace.setup()
You've now implemented most of the necessary features of your application. The last piece is to allow Workers to change their availability status.
You've 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 because a worker's activity changes 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.
task_router/views.py
1import json2from urllib.parse import quote_plus34from django.conf import settings5from django.http import HttpResponse, JsonResponse6from django.shortcuts import render7from django.urls import reverse8from django.views.decorators.csrf import csrf_exempt9from twilio.rest import Client10from twilio.twiml.messaging_response import MessagingResponse11from twilio.twiml.voice_response import VoiceResponse1213from . import sms_sender, workspace14from .models import MissedCall1516if not getattr(settings, 'TESTING', False):17WORKSPACE_INFO = workspace.setup()18else:19WORKSPACE_INFO = None2021ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID22AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN23TWILIO_NUMBER = settings.TWILIO_NUMBER24EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS252627def root(request):28""" Renders a missed calls list, with product and phone number """29missed_calls = MissedCall.objects.order_by('-created')30return render(request, 'index.html', {31'missed_calls': missed_calls32})333435@csrf_exempt36def incoming_sms(request):37""" Changes worker activity and returns a confirmation """38client = Client(ACCOUNT_SID, AUTH_TOKEN)39activity = 'Available' if request.POST['Body'].lower().strip() == 'on' else 'Offline'40activity_sid = WORKSPACE_INFO.activities[activity].sid41worker_sid = WORKSPACE_INFO.workers[request.POST['From']]42workspace_sid = WORKSPACE_INFO.workspace_sid4344client.workspaces(workspace_sid)\45.workers(worker_sid)\46.update(activity_sid=activity_sid)4748resp = MessagingResponse()49message = 'Your status has changed to ' + activity50resp.message(message)51return HttpResponse(resp)525354@csrf_exempt55def incoming_call(request):56""" Returns TwiML instructions to Twilio's POST requests """57resp = VoiceResponse()58gather = resp.gather(numDigits=1, action=reverse('enqueue'), method="POST")59gather.say("For Programmable SMS, press one. For Voice, press any other key.")6061return HttpResponse(resp)626364@csrf_exempt65def enqueue(request):66""" Parses a selected product, creating a Task on Task Router Workflow """67resp = VoiceResponse()68digits = request.POST['Digits']69selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'70task = {'selected_product': selected_product}7172enqueue = resp.enqueue(None, workflowSid=WORKSPACE_INFO.workflow_sid)73enqueue.task(json.dumps(task))7475return HttpResponse(resp)767778@csrf_exempt79def assignment(request):80""" Task assignment """81response = {'instruction': 'dequeue',82'post_work_activity_sid': WORKSPACE_INFO.post_work_activity_sid}83return JsonResponse(response)848586@csrf_exempt87def events(request):88""" Events callback for missed calls """89POST = request.POST90event_type = POST.get('EventType')91task_events = ['workflow.timeout', 'task.canceled']92worker_event = 'worker.activity.update'9394if event_type in task_events:95task_attributes = json.loads(POST['TaskAttributes'])96_save_missed_call(task_attributes)97if event_type == 'workflow.timeout':98_voicemail(task_attributes['call_sid'])99elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':100message = 'Your status has changed to Offline. Reply with '\101'"On" to get back Online'102worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']103sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)104105return HttpResponse('')106107108def _voicemail(call_sid):109msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'110route_url = 'https://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)111route_call(call_sid, route_url)112113114def route_call(call_sid, route_url):115client = Client(ACCOUNT_SID, AUTH_TOKEN)116client.api.calls(call_sid).update(url=route_url)117118119def _save_missed_call(task_attributes):120MissedCall.objects.create(121phone_number=task_attributes['from'],122selected_product=task_attributes['selected_product'])123124125# Only used by the tests in order to patch requests before any call is made126def setup_workspace():127global WORKSPACE_INFO128WORKSPACE_INFO = workspace.setup()
Congratulations! You finished this tutorial. 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: Instantly collect structured data from your users with a survey conducted over a call or SMS text messages.