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:

  • 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.

Configure the Workspace

In order to instruct TaskRouter to handle the Tasks, we need to configure a Workspace. We can do this in the TaskRouter Console 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.

Loading Code Samples...
Language
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
task_router/workspace.py
Create, Setup and Configure the Workspace

task_router/workspace.py

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

Create a Workspace

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.

Loading Code Samples...
Language
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
task_router/workspace.py
Create Workspace

task_router/workspace.py

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

Create the Workers

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.

Loading Code Samples...
Language
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
task_router/workspace.py
Create Workers

task_router/workspace.py

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

Create 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.
Loading Code Samples...
Language
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
task_router/workspace.py
Create Task Queues

task_router/workspace.py

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

Create a Workflow

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:
    1. "selected_product==\ "ProgrammableSMS\"" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.
    2. "selected_product==\ "ProgrammableVoice\"" expression for Voice Task Queue.
Loading Code Samples...
Language
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
task_router/workspace.py
Create a Workflow

task_router/workspace.py

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

Handle Twilio's Request

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.

Loading Code Samples...
Language
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
task_router/views.py
Handling Twilio's Requests

task_router/views.py

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

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 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.

Loading Code Samples...
Language
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
task_router/views.py
Create a Task

task_router/views.py

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

Assign a Worker

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, e-mail, 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.

Loading Code Samples...
Language
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
task_router/views.py
Assign a Worker

task_router/views.py

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

Collect Missed Calls

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. 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.

Loading Code Samples...
Language
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
task_router/views.py
Collect Missed Calls

task_router/views.py

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

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.

Loading Code Samples...
Language
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
task_router/views.py
Changing a Worker's Activity

task_router/views.py

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

Where to Next?

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.

Did this help?

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think!

Agustin Camino
Samuel Mendes
David Prothero

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
from twilio.rest import Client
from django.conf import settings
import json

HOST = settings.HOST
ALICE_NUMBER = settings.ALICE_NUMBER
BOB_NUMBER = settings.BOB_NUMBER
WORKSPACE_NAME = 'Twilio Workspace'


def first(items):
    return items[0] if items else None


def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)


CLIENT = build_client()
CACHE = {}


def activities_dict(workspace_sid):
    activities = build_client().taskrouter.workspaces(workspace_sid)\
                               .activities.list()

    return dict((activity.friendly_name, activity) for activity in activities)


class WorkspaceInfo:

    def __init__(self, workspace, workflow, activities, workers):
        self.workflow_sid = workflow.sid
        self.workspace_sid = workspace.sid
        self.activities = activities
        self.post_work_activity_sid = activities['Idle'].sid
        self.workers = workers


def setup():
    if 'WORKSPACE_INFO' not in CACHE:
        workspace = create_workspace()
        activities = activities_dict(workspace.sid)
        workers = create_workers(workspace, activities)
        queues = create_task_queues(workspace, activities)
        workflow = create_workflow(workspace, queues)
        CACHE['WORKSPACE_INFO'] = WorkspaceInfo(workspace, workflow, activities, workers)
    return CACHE['WORKSPACE_INFO']


def create_workspace():
    try:
        workspace = first(CLIENT.taskrouter.workspaces.list(friendly_name=WORKSPACE_NAME))
        CLIENT.taskrouter.workspaces(workspace.sid).delete()
    except:
        pass

    events_callback = HOST+'/events'

    return CLIENT.taskrouter.workspaces.create(
            friendly_name=WORKSPACE_NAME,
            event_callback_url=events_callback,
            template=None)


def create_workers(workspace, activities):
    alice_attributes = {
        "products": ["ProgrammableVoice"],
        "contact_uri": ALICE_NUMBER
    }

    alice = CLIENT.taskrouter.workspaces(workspace.sid)\
                  .workers.create(activity_sid=activities['Idle'].sid,
                                  friendly_name='Alice',
                                  attributes=json.dumps(alice_attributes))

    bob_attributes = {
        "products": ["ProgrammableSMS"],
        "contact_uri": BOB_NUMBER
    }

    bob = CLIENT.taskrouter.workspaces(workspace.sid)\
                .workers.create(activity_sid=activities['Idle'].sid,
                                friendly_name='Bob',
                                attributes=json.dumps(bob_attributes))

    return {BOB_NUMBER: bob.sid, ALICE_NUMBER: alice.sid}


def create_task_queues(workspace, activities):
    default_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                    .create(friendly_name='Default',
                            reservation_activity_sid=activities['Reserved'].sid,
                            assignment_activity_sid=activities['Busy'].sid,
                            target_workers='1==1')

    sms_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                      .create(friendly_name='SMS',
                              reservation_activity_sid=activities['Reserved'].sid,
                              assignment_activity_sid=activities['Busy'].sid,
                              target_workers='"ProgrammableSMS" in products')

    voice_queue = CLIENT.taskrouter.workspaces(workspace.sid).task_queues\
                        .create(friendly_name='Voice',
                                reservation_activity_sid=activities['Reserved'].sid,
                                assignment_activity_sid=activities['Busy'].sid,
                                target_workers='"ProgrammableVoice" in products')

    return {'sms': sms_queue, 'voice': voice_queue, 'default': default_queue}


def create_workflow(workspace, queues):
    defaultTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    smsTarget = {
        'queue': queues['sms'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    voiceTarget = {
        'queue': queues['voice'].sid,
        'Priority': 5,
        'Timeout': 30
    }

    default_filter = {
        'queue': queues['default'].sid,
        'Expression': '1==1',
        'Priority': 1,
        'Timeout': 30
    }

    voiceFilter = {
        'expression': 'selected_product=="ProgrammableVoice"',
        'targets': [voiceTarget, defaultTarget]
    }

    smsFilter = {
        'expression': 'selected_product=="ProgrammableSMS"',
        'targets': [smsTarget, defaultTarget]
    }

    config = {
        'task_routing': {
            'filters': [voiceFilter, smsFilter],
            'default_filter': default_filter
        }
    }

    callback_url = HOST + '/assignment'

    return CLIENT.taskrouter.workspaces(workspace.sid)\
                 .workflows.create(friendly_name='Sales',
                                   assignment_callback_url=callback_url,
                                   fallback_assignment_callback_url=callback_url,
                                   task_reservation_timeout=15,
                                   configuration=json.dumps(config))
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from twilio.twiml.voice_response import VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from .models import MissedCall
from . import workspace
from twilio.rest import Client
import json
from . import sms_sender
try:
    from urllib import quote_plus
except:
    # PY3
    from urllib.parse import quote_plus

WORKSPACE_INFO = workspace.setup()
ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID
AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN
TWILIO_NUMBER = settings.TWILIO_NUMBER
EMAIL = settings.MISSED_CALLS_EMAIL_ADDRESS


def root(request):
    """ Renders a missed calls list, with product and phone number """
    missed_calls = MissedCall.objects.order_by('-created')
    return render(request, 'index.html', {
        'missed_calls': missed_calls
    })


@csrf_exempt
def incoming_sms(request):
    """ Changes worker activity and returns a confirmation """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
    activity_sid = WORKSPACE_INFO.activities[activity].sid
    worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
    workspace_sid = WORKSPACE_INFO.workspace_sid

    client.workspaces(workspace_sid)\
          .workers(worker_sid)\
          .update(activity_sid=activity_sid)

    resp = MessagingResponse()
    message = 'Your status has changed to ' + activity
    resp.message(message)
    return HttpResponse(resp)


@csrf_exempt
def incoming_call(request):
    """ Returns TwiML instructions to Twilio's POST requests """
    resp = VoiceResponse()
    resp.say("For Programmable SMS, press one. For Voice, press any other key.")
    resp.gather(numDigits=1, action="/call/enqueue", method="POST")

    return HttpResponse(resp)


@csrf_exempt
def enqueue(request):
    """ Parses a selected product, creating a Task on Task Router Workflow """
    resp = VoiceResponse()
    digits = request.POST['Digits']
    selected_product = 'ProgrammableSMS' if digits == '1' else 'ProgrammableVoice'
    task = '{"selected_product": "%s"}' % selected_product

    resp.enqueue(None,
                 workflowSid=WORKSPACE_INFO.workflow_sid,
                 task=task)

    return HttpResponse(resp)


@csrf_exempt
def assignment(request):
    """ Task assignment """
    response = {"instruction": "dequeue",
                "post_work_activity_sid": WORKSPACE_INFO.post_work_activity_sid}
    return JsonResponse(response)


@csrf_exempt
def events(request):
    """ Events callback for missed calls """
    POST = request.POST
    event_type = POST.get('EventType')
    task_events = ['workflow.timeout', 'task.canceled']
    worker_event = 'worker.activity.update'

    if event_type in task_events:
        task_attributes = json.loads(POST['TaskAttributes'])
        _save_missed_call(task_attributes)
        _voicemail(task_attributes['call_sid'])
    elif event_type == worker_event and POST['WorkerActivityName'] == 'Offline':
        message = 'Your status has changed to Offline. Reply with '\
            '"On" to get back Online'
        worker_number = json.loads(POST['WorkerAttributes'])['contact_uri']
        sms_sender.send(to=worker_number, from_=TWILIO_NUMBER, body=message)

    return HttpResponse('')


def _voicemail(call_sid):
    msg = 'Sorry, All agents are busy. Please leave a message. We will call you as soon as possible'
    route_url = 'http://twimlets.com/voicemail?Email=' + EMAIL + '&Message=' + quote_plus(msg)
    route_call(call_sid, route_url)


def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)


def _save_missed_call(task_attributes):
    MissedCall.objects.create(
            phone_number=task_attributes['from'],
            selected_product=task_attributes['selected_product'])