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.
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 Node.js 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:
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 initClient
configures and returns a TaskRouterClient, which is provided by the Twilio Node.js library.
lib/workspace.js
1'use strict';23var twilio = require('twilio');4var find = require('lodash/find');5var map = require('lodash/map');6var difference = require('lodash/difference');7var WORKSPACE_NAME = 'TaskRouter Node Workspace';8var HOST = process.env.HOST;9var EVENT_CALLBACK = `${HOST}/events`;10var ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;11var AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;1213module.exports = function() {14function initClient(existingWorkspaceSid) {15if (!existingWorkspaceSid) {16this.client = twilio(ACCOUNT_SID, AUTH_TOKEN).taskrouter.v1.workspaces;17} else {18this.client = twilio(ACCOUNT_SID, AUTH_TOKEN)19.taskrouter.v1.workspaces(existingWorkspaceSid);20}21}2223function createWorker(opts) {24var ctx = this;2526return this.client.activities.list({friendlyName: 'Idle'})27.then(function(idleActivity) {28return ctx.client.workers.create({29friendlyName: opts.name,30attributes: JSON.stringify({31'products': opts.products,32'contact_uri': opts.phoneNumber,33}),34activitySid: idleActivity.sid,35});36});37}3839function createWorkflow() {40var ctx = this;41var config = this.createWorkflowConfig();4243return ctx.client.workflows44.create({45friendlyName: 'Sales',46assignmentCallbackUrl: HOST + '/call/assignment',47fallbackAssignmentCallbackUrl: HOST + '/call/assignment',48taskReservationTimeout: 15,49configuration: config,50})51.then(function(workflow) {52return ctx.client.activities.list()53.then(function(activities) {54var idleActivity = find(activities, {friendlyName: 'Idle'});55var offlineActivity = find(activities, {friendlyName: 'Offline'});5657return {58workflowSid: workflow.sid,59activities: {60idle: idleActivity.sid,61offline: offlineActivity.sid,62},63workspaceSid: ctx.client._solution.sid,64};65});66});67}6869function createTaskQueues() {70var ctx = this;71return this.client.activities.list()72.then(function(activities) {73var busyActivity = find(activities, {friendlyName: 'Busy'});74var reservedActivity = find(activities, {friendlyName: 'Reserved'});7576return Promise.all([77ctx.client.taskQueues.create({78friendlyName: 'SMS',79targetWorkers: 'products HAS "ProgrammableSMS"',80assignmentActivitySid: busyActivity.sid,81reservationActivitySid: reservedActivity.sid,82}),83ctx.client.taskQueues.create({84friendlyName: 'Voice',85targetWorkers: 'products HAS "ProgrammableVoice"',86assignmentActivitySid: busyActivity.sid,87reservationActivitySid: reservedActivity.sid,88}),89ctx.client.taskQueues.create({90friendlyName: 'Default',91targetWorkers: '1==1',92assignmentActivitySid: busyActivity.sid,93reservationActivitySid: reservedActivity.sid,94}),95])96.then(function(queues) {97ctx.queues = queues;98});99});100}101102function createWorkers() {103var ctx = this;104105return Promise.all([106ctx.createWorker({107name: 'Bob',108phoneNumber: process.env.BOB_NUMBER,109products: ['ProgrammableSMS'],110}),111ctx.createWorker({112name: 'Alice',113phoneNumber: process.env.ALICE_NUMBER,114products: ['ProgrammableVoice'],115})116])117.then(function(workers) {118var bobWorker = workers[0];119var aliceWorker = workers[1];120var workerInfo = {};121122workerInfo[process.env.ALICE_NUMBER] = aliceWorker.sid;123workerInfo[process.env.BOB_NUMBER] = bobWorker.sid;124125return workerInfo;126});127}128129function createWorkflowActivities() {130var ctx = this;131var activityNames = ['Idle', 'Busy', 'Offline', 'Reserved'];132133return ctx.client.activities.list()134.then(function(activities) {135var existingActivities = map(activities, 'friendlyName');136137var missingActivities = difference(activityNames, existingActivities);138139var newActivities = map(missingActivities, function(friendlyName) {140return ctx.client.activities141.create({142friendlyName: friendlyName,143available: 'true'144});145});146147return Promise.all(newActivities);148})149.then(function() {150return ctx.client.activities.list();151});152}153154function createWorkflowConfig() {155var queues = this.queues;156157if (!queues) {158throw new Error('Queues must be initialized.');159}160161var defaultTarget = {162queue: find(queues, {friendlyName: 'Default'}).sid,163timeout: 30,164priority: 1,165};166167var smsTarget = {168queue: find(queues, {friendlyName: 'SMS'}).sid,169timeout: 30,170priority: 5,171};172173var voiceTarget = {174queue: find(queues, {friendlyName: 'Voice'}).sid,175timeout: 30,176priority: 5,177};178179var rules = [180{181expression: 'selected_product=="ProgrammableSMS"',182targets: [smsTarget, defaultTarget],183timeout: 30,184},185{186expression: 'selected_product=="ProgrammableVoice"',187targets: [voiceTarget, defaultTarget],188timeout: 30,189},190];191192var config = {193task_routing: {194filters: rules,195default_filter: defaultTarget,196},197};198199return JSON.stringify(config);200}201202function setup() {203var ctx = this;204205ctx.initClient();206207return this.initWorkspace()208.then(createWorkflowActivities.bind(ctx))209.then(createTaskQueues.bind(ctx))210.then(createWorkflow.bind(ctx))211.then(function(workspaceInfo) {212return ctx.createWorkers()213.then(function(workerInfo) {214return [workerInfo, workspaceInfo];215});216});217}218219function findByFriendlyName(friendlyName) {220var client = this.client;221222return client.list()223.then(function (data) {224return find(data, {friendlyName: friendlyName});225});226}227228function deleteByFriendlyName(friendlyName) {229var ctx = this;230231return this.findByFriendlyName(friendlyName)232.then(function(workspace) {233if (workspace.remove) {234return workspace.remove();235}236});237}238239function createWorkspace() {240return this.client.create({241friendlyName: WORKSPACE_NAME,242EVENT_CALLBACKUrl: EVENT_CALLBACK,243});244}245246function initWorkspace() {247var ctx = this;248var client = this.client;249250return ctx.findByFriendlyName(WORKSPACE_NAME)251.then(function(workspace) {252var newWorkspace;253254if (workspace) {255newWorkspace = ctx.deleteByFriendlyName(WORKSPACE_NAME)256.then(createWorkspace.bind(ctx));257} else {258newWorkspace = ctx.createWorkspace();259}260261return newWorkspace;262})263.then(function(workspace) {264ctx.initClient(workspace.sid);265266return workspace;267});268}269270return {271createTaskQueues: createTaskQueues,272createWorker: createWorker,273createWorkers: createWorkers,274createWorkflow: createWorkflow,275createWorkflowActivities: createWorkflowActivities,276createWorkflowConfig: createWorkflowConfig,277createWorkspace: createWorkspace,278deleteByFriendlyName: deleteByFriendlyName,279findByFriendlyName: findByFriendlyName,280initClient: initClient,281initWorkspace: initWorkspace,282setup: setup,283};284};
Now let's look in more detail at all the steps, starting with the creation of the workspace itself.
Before creating a workspace, we need to delete any others with the same friendlyName
as the one we are trying to create. In order to create a workspace we need to provide a friendlyName
and a eventCallbackUrl
where a request will be made every time an event is triggered in our workspace.
lib/workspace.js
1'use strict';23var twilio = require('twilio');4var find = require('lodash/find');5var map = require('lodash/map');6var difference = require('lodash/difference');7var WORKSPACE_NAME = 'TaskRouter Node Workspace';8var HOST = process.env.HOST;9var EVENT_CALLBACK = `${HOST}/events`;10var ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;11var AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;1213module.exports = function() {14function initClient(existingWorkspaceSid) {15if (!existingWorkspaceSid) {16this.client = twilio(ACCOUNT_SID, AUTH_TOKEN).taskrouter.v1.workspaces;17} else {18this.client = twilio(ACCOUNT_SID, AUTH_TOKEN)19.taskrouter.v1.workspaces(existingWorkspaceSid);20}21}2223function createWorker(opts) {24var ctx = this;2526return this.client.activities.list({friendlyName: 'Idle'})27.then(function(idleActivity) {28return ctx.client.workers.create({29friendlyName: opts.name,30attributes: JSON.stringify({31'products': opts.products,32'contact_uri': opts.phoneNumber,33}),34activitySid: idleActivity.sid,35});36});37}3839function createWorkflow() {40var ctx = this;41var config = this.createWorkflowConfig();4243return ctx.client.workflows44.create({45friendlyName: 'Sales',46assignmentCallbackUrl: HOST + '/call/assignment',47fallbackAssignmentCallbackUrl: HOST + '/call/assignment',48taskReservationTimeout: 15,49configuration: config,50})51.then(function(workflow) {52return ctx.client.activities.list()53.then(function(activities) {54var idleActivity = find(activities, {friendlyName: 'Idle'});55var offlineActivity = find(activities, {friendlyName: 'Offline'});5657return {58workflowSid: workflow.sid,59activities: {60idle: idleActivity.sid,61offline: offlineActivity.sid,62},63workspaceSid: ctx.client._solution.sid,64};65});66});67}6869function createTaskQueues() {70var ctx = this;71return this.client.activities.list()72.then(function(activities) {73var busyActivity = find(activities, {friendlyName: 'Busy'});74var reservedActivity = find(activities, {friendlyName: 'Reserved'});7576return Promise.all([77ctx.client.taskQueues.create({78friendlyName: 'SMS',79targetWorkers: 'products HAS "ProgrammableSMS"',80assignmentActivitySid: busyActivity.sid,81reservationActivitySid: reservedActivity.sid,82}),83ctx.client.taskQueues.create({84friendlyName: 'Voice',85targetWorkers: 'products HAS "ProgrammableVoice"',86assignmentActivitySid: busyActivity.sid,87reservationActivitySid: reservedActivity.sid,88}),89ctx.client.taskQueues.create({90friendlyName: 'Default',91targetWorkers: '1==1',92assignmentActivitySid: busyActivity.sid,93reservationActivitySid: reservedActivity.sid,94}),95])96.then(function(queues) {97ctx.queues = queues;98});99});100}101102function createWorkers() {103var ctx = this;104105return Promise.all([106ctx.createWorker({107name: 'Bob',108phoneNumber: process.env.BOB_NUMBER,109products: ['ProgrammableSMS'],110}),111ctx.createWorker({112name: 'Alice',113phoneNumber: process.env.ALICE_NUMBER,114products: ['ProgrammableVoice'],115})116])117.then(function(workers) {118var bobWorker = workers[0];119var aliceWorker = workers[1];120var workerInfo = {};121122workerInfo[process.env.ALICE_NUMBER] = aliceWorker.sid;123workerInfo[process.env.BOB_NUMBER] = bobWorker.sid;124125return workerInfo;126});127}128129function createWorkflowActivities() {130var ctx = this;131var activityNames = ['Idle', 'Busy', 'Offline', 'Reserved'];132133return ctx.client.activities.list()134.then(function(activities) {135var existingActivities = map(activities, 'friendlyName');136137var missingActivities = difference(activityNames, existingActivities);138139var newActivities = map(missingActivities, function(friendlyName) {140return ctx.client.activities141.create({142friendlyName: friendlyName,143available: 'true'144});145});146147return Promise.all(newActivities);148})149.then(function() {150return ctx.client.activities.list();151});152}153154function createWorkflowConfig() {155var queues = this.queues;156157if (!queues) {158throw new Error('Queues must be initialized.');159}160161var defaultTarget = {162queue: find(queues, {friendlyName: 'Default'}).sid,163timeout: 30,164priority: 1,165};166167var smsTarget = {168queue: find(queues, {friendlyName: 'SMS'}).sid,169timeout: 30,170priority: 5,171};172173var voiceTarget = {174queue: find(queues, {friendlyName: 'Voice'}).sid,175timeout: 30,176priority: 5,177};178179var rules = [180{181expression: 'selected_product=="ProgrammableSMS"',182targets: [smsTarget, defaultTarget],183timeout: 30,184},185{186expression: 'selected_product=="ProgrammableVoice"',187targets: [voiceTarget, defaultTarget],188timeout: 30,189},190];191192var config = {193task_routing: {194filters: rules,195default_filter: defaultTarget,196},197};198199return JSON.stringify(config);200}201202function setup() {203var ctx = this;204205ctx.initClient();206207return this.initWorkspace()208.then(createWorkflowActivities.bind(ctx))209.then(createTaskQueues.bind(ctx))210.then(createWorkflow.bind(ctx))211.then(function(workspaceInfo) {212return ctx.createWorkers()213.then(function(workerInfo) {214return [workerInfo, workspaceInfo];215});216});217}218219function findByFriendlyName(friendlyName) {220var client = this.client;221222return client.list()223.then(function (data) {224return find(data, {friendlyName: friendlyName});225});226}227228function deleteByFriendlyName(friendlyName) {229var ctx = this;230231return this.findByFriendlyName(friendlyName)232.then(function(workspace) {233if (workspace.remove) {234return workspace.remove();235}236});237}238239function createWorkspace() {240return this.client.create({241friendlyName: WORKSPACE_NAME,242EVENT_CALLBACKUrl: EVENT_CALLBACK,243});244}245246function initWorkspace() {247var ctx = this;248var client = this.client;249250return ctx.findByFriendlyName(WORKSPACE_NAME)251.then(function(workspace) {252var newWorkspace;253254if (workspace) {255newWorkspace = ctx.deleteByFriendlyName(WORKSPACE_NAME)256.then(createWorkspace.bind(ctx));257} else {258newWorkspace = ctx.createWorkspace();259}260261return newWorkspace;262})263.then(function(workspace) {264ctx.initClient(workspace.sid);265266return workspace;267});268}269270return {271createTaskQueues: createTaskQueues,272createWorker: createWorker,273createWorkers: createWorkers,274createWorkflow: createWorkflow,275createWorkflowActivities: createWorkflowActivities,276createWorkflowConfig: createWorkflowConfig,277createWorkspace: createWorkspace,278deleteByFriendlyName: deleteByFriendlyName,279findByFriendlyName: findByFriendlyName,280initClient: initClient,281initWorkspace: initWorkspace,282setup: setup,283};284};
We have a brand new workspace, now we need workers. Let's create them on the next step.
We'll create two workers: Bob and Alice. They each have two attributes: contact_uri
a phone number and products
, a list of products each worker is specialized in. We also need to specify an activitySid
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.
lib/workspace.js
1'use strict';23var twilio = require('twilio');4var find = require('lodash/find');5var map = require('lodash/map');6var difference = require('lodash/difference');7var WORKSPACE_NAME = 'TaskRouter Node Workspace';8var HOST = process.env.HOST;9var EVENT_CALLBACK = `${HOST}/events`;10var ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;11var AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;1213module.exports = function() {14function initClient(existingWorkspaceSid) {15if (!existingWorkspaceSid) {16this.client = twilio(ACCOUNT_SID, AUTH_TOKEN).taskrouter.v1.workspaces;17} else {18this.client = twilio(ACCOUNT_SID, AUTH_TOKEN)19.taskrouter.v1.workspaces(existingWorkspaceSid);20}21}2223function createWorker(opts) {24var ctx = this;2526return this.client.activities.list({friendlyName: 'Idle'})27.then(function(idleActivity) {28return ctx.client.workers.create({29friendlyName: opts.name,30attributes: JSON.stringify({31'products': opts.products,32'contact_uri': opts.phoneNumber,33}),34activitySid: idleActivity.sid,35});36});37}3839function createWorkflow() {40var ctx = this;41var config = this.createWorkflowConfig();4243return ctx.client.workflows44.create({45friendlyName: 'Sales',46assignmentCallbackUrl: HOST + '/call/assignment',47fallbackAssignmentCallbackUrl: HOST + '/call/assignment',48taskReservationTimeout: 15,49configuration: config,50})51.then(function(workflow) {52return ctx.client.activities.list()53.then(function(activities) {54var idleActivity = find(activities, {friendlyName: 'Idle'});55var offlineActivity = find(activities, {friendlyName: 'Offline'});5657return {58workflowSid: workflow.sid,59activities: {60idle: idleActivity.sid,61offline: offlineActivity.sid,62},63workspaceSid: ctx.client._solution.sid,64};65});66});67}6869function createTaskQueues() {70var ctx = this;71return this.client.activities.list()72.then(function(activities) {73var busyActivity = find(activities, {friendlyName: 'Busy'});74var reservedActivity = find(activities, {friendlyName: 'Reserved'});7576return Promise.all([77ctx.client.taskQueues.create({78friendlyName: 'SMS',79targetWorkers: 'products HAS "ProgrammableSMS"',80assignmentActivitySid: busyActivity.sid,81reservationActivitySid: reservedActivity.sid,82}),83ctx.client.taskQueues.create({84friendlyName: 'Voice',85targetWorkers: 'products HAS "ProgrammableVoice"',86assignmentActivitySid: busyActivity.sid,87reservationActivitySid: reservedActivity.sid,88}),89ctx.client.taskQueues.create({90friendlyName: 'Default',91targetWorkers: '1==1',92assignmentActivitySid: busyActivity.sid,93reservationActivitySid: reservedActivity.sid,94}),95])96.then(function(queues) {97ctx.queues = queues;98});99});100}101102function createWorkers() {103var ctx = this;104105return Promise.all([106ctx.createWorker({107name: 'Bob',108phoneNumber: process.env.BOB_NUMBER,109products: ['ProgrammableSMS'],110}),111ctx.createWorker({112name: 'Alice',113phoneNumber: process.env.ALICE_NUMBER,114products: ['ProgrammableVoice'],115})116])117.then(function(workers) {118var bobWorker = workers[0];119var aliceWorker = workers[1];120var workerInfo = {};121122workerInfo[process.env.ALICE_NUMBER] = aliceWorker.sid;123workerInfo[process.env.BOB_NUMBER] = bobWorker.sid;124125return workerInfo;126});127}128129function createWorkflowActivities() {130var ctx = this;131var activityNames = ['Idle', 'Busy', 'Offline', 'Reserved'];132133return ctx.client.activities.list()134.then(function(activities) {135var existingActivities = map(activities, 'friendlyName');136137var missingActivities = difference(activityNames, existingActivities);138139var newActivities = map(missingActivities, function(friendlyName) {140return ctx.client.activities141.create({142friendlyName: friendlyName,143available: 'true'144});145});146147return Promise.all(newActivities);148})149.then(function() {150return ctx.client.activities.list();151});152}153154function createWorkflowConfig() {155var queues = this.queues;156157if (!queues) {158throw new Error('Queues must be initialized.');159}160161var defaultTarget = {162queue: find(queues, {friendlyName: 'Default'}).sid,163timeout: 30,164priority: 1,165};166167var smsTarget = {168queue: find(queues, {friendlyName: 'SMS'}).sid,169timeout: 30,170priority: 5,171};172173var voiceTarget = {174queue: find(queues, {friendlyName: 'Voice'}).sid,175timeout: 30,176priority: 5,177};178179var rules = [180{181expression: 'selected_product=="ProgrammableSMS"',182targets: [smsTarget, defaultTarget],183timeout: 30,184},185{186expression: 'selected_product=="ProgrammableVoice"',187targets: [voiceTarget, defaultTarget],188timeout: 30,189},190];191192var config = {193task_routing: {194filters: rules,195default_filter: defaultTarget,196},197};198199return JSON.stringify(config);200}201202function setup() {203var ctx = this;204205ctx.initClient();206207return this.initWorkspace()208.then(createWorkflowActivities.bind(ctx))209.then(createTaskQueues.bind(ctx))210.then(createWorkflow.bind(ctx))211.then(function(workspaceInfo) {212return ctx.createWorkers()213.then(function(workerInfo) {214return [workerInfo, workspaceInfo];215});216});217}218219function findByFriendlyName(friendlyName) {220var client = this.client;221222return client.list()223.then(function (data) {224return find(data, {friendlyName: friendlyName});225});226}227228function deleteByFriendlyName(friendlyName) {229var ctx = this;230231return this.findByFriendlyName(friendlyName)232.then(function(workspace) {233if (workspace.remove) {234return workspace.remove();235}236});237}238239function createWorkspace() {240return this.client.create({241friendlyName: WORKSPACE_NAME,242EVENT_CALLBACKUrl: EVENT_CALLBACK,243});244}245246function initWorkspace() {247var ctx = this;248var client = this.client;249250return ctx.findByFriendlyName(WORKSPACE_NAME)251.then(function(workspace) {252var newWorkspace;253254if (workspace) {255newWorkspace = ctx.deleteByFriendlyName(WORKSPACE_NAME)256.then(createWorkspace.bind(ctx));257} else {258newWorkspace = ctx.createWorkspace();259}260261return newWorkspace;262})263.then(function(workspace) {264ctx.initClient(workspace.sid);265266return workspace;267});268}269270return {271createTaskQueues: createTaskQueues,272createWorker: createWorker,273createWorkers: createWorkers,274createWorkflow: createWorkflow,275createWorkflowActivities: createWorkflowActivities,276createWorkflowConfig: createWorkflowConfig,277createWorkspace: createWorkspace,278deleteByFriendlyName: deleteByFriendlyName,279findByFriendlyName: findByFriendlyName,280initClient: initClient,281initWorkspace: initWorkspace,282setup: setup,283};284};
After creating our workers, let's set up the Task Queues.
Next, we set up the Task Queues. Each with a friendlyName
and a targetWorkers
, which is an expression to match Workers. Our Task Queues are:
SMS
- Will target Workers specialized in Programmable SMS, such as Bob, using the expression
'"ProgrammableSMS" in products'
.
Voice
- Will do the same for Programmable Voice Workers, such as Alice, using the expression
'"ProgrammableVoice" in products'
.
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.
lib/workspace.js
1'use strict';23var twilio = require('twilio');4var find = require('lodash/find');5var map = require('lodash/map');6var difference = require('lodash/difference');7var WORKSPACE_NAME = 'TaskRouter Node Workspace';8var HOST = process.env.HOST;9var EVENT_CALLBACK = `${HOST}/events`;10var ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;11var AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;1213module.exports = function() {14function initClient(existingWorkspaceSid) {15if (!existingWorkspaceSid) {16this.client = twilio(ACCOUNT_SID, AUTH_TOKEN).taskrouter.v1.workspaces;17} else {18this.client = twilio(ACCOUNT_SID, AUTH_TOKEN)19.taskrouter.v1.workspaces(existingWorkspaceSid);20}21}2223function createWorker(opts) {24var ctx = this;2526return this.client.activities.list({friendlyName: 'Idle'})27.then(function(idleActivity) {28return ctx.client.workers.create({29friendlyName: opts.name,30attributes: JSON.stringify({31'products': opts.products,32'contact_uri': opts.phoneNumber,33}),34activitySid: idleActivity.sid,35});36});37}3839function createWorkflow() {40var ctx = this;41var config = this.createWorkflowConfig();4243return ctx.client.workflows44.create({45friendlyName: 'Sales',46assignmentCallbackUrl: HOST + '/call/assignment',47fallbackAssignmentCallbackUrl: HOST + '/call/assignment',48taskReservationTimeout: 15,49configuration: config,50})51.then(function(workflow) {52return ctx.client.activities.list()53.then(function(activities) {54var idleActivity = find(activities, {friendlyName: 'Idle'});55var offlineActivity = find(activities, {friendlyName: 'Offline'});5657return {58workflowSid: workflow.sid,59activities: {60idle: idleActivity.sid,61offline: offlineActivity.sid,62},63workspaceSid: ctx.client._solution.sid,64};65});66});67}6869function createTaskQueues() {70var ctx = this;71return this.client.activities.list()72.then(function(activities) {73var busyActivity = find(activities, {friendlyName: 'Busy'});74var reservedActivity = find(activities, {friendlyName: 'Reserved'});7576return Promise.all([77ctx.client.taskQueues.create({78friendlyName: 'SMS',79targetWorkers: 'products HAS "ProgrammableSMS"',80assignmentActivitySid: busyActivity.sid,81reservationActivitySid: reservedActivity.sid,82}),83ctx.client.taskQueues.create({84friendlyName: 'Voice',85targetWorkers: 'products HAS "ProgrammableVoice"',86assignmentActivitySid: busyActivity.sid,87reservationActivitySid: reservedActivity.sid,88}),89ctx.client.taskQueues.create({90friendlyName: 'Default',91targetWorkers: '1==1',92assignmentActivitySid: busyActivity.sid,93reservationActivitySid: reservedActivity.sid,94}),95])96.then(function(queues) {97ctx.queues = queues;98});99});100}101102function createWorkers() {103var ctx = this;104105return Promise.all([106ctx.createWorker({107name: 'Bob',108phoneNumber: process.env.BOB_NUMBER,109products: ['ProgrammableSMS'],110}),111ctx.createWorker({112name: 'Alice',113phoneNumber: process.env.ALICE_NUMBER,114products: ['ProgrammableVoice'],115})116])117.then(function(workers) {118var bobWorker = workers[0];119var aliceWorker = workers[1];120var workerInfo = {};121122workerInfo[process.env.ALICE_NUMBER] = aliceWorker.sid;123workerInfo[process.env.BOB_NUMBER] = bobWorker.sid;124125return workerInfo;126});127}128129function createWorkflowActivities() {130var ctx = this;131var activityNames = ['Idle', 'Busy', 'Offline', 'Reserved'];132133return ctx.client.activities.list()134.then(function(activities) {135var existingActivities = map(activities, 'friendlyName');136137var missingActivities = difference(activityNames, existingActivities);138139var newActivities = map(missingActivities, function(friendlyName) {140return ctx.client.activities141.create({142friendlyName: friendlyName,143available: 'true'144});145});146147return Promise.all(newActivities);148})149.then(function() {150return ctx.client.activities.list();151});152}153154function createWorkflowConfig() {155var queues = this.queues;156157if (!queues) {158throw new Error('Queues must be initialized.');159}160161var defaultTarget = {162queue: find(queues, {friendlyName: 'Default'}).sid,163timeout: 30,164priority: 1,165};166167var smsTarget = {168queue: find(queues, {friendlyName: 'SMS'}).sid,169timeout: 30,170priority: 5,171};172173var voiceTarget = {174queue: find(queues, {friendlyName: 'Voice'}).sid,175timeout: 30,176priority: 5,177};178179var rules = [180{181expression: 'selected_product=="ProgrammableSMS"',182targets: [smsTarget, defaultTarget],183timeout: 30,184},185{186expression: 'selected_product=="ProgrammableVoice"',187targets: [voiceTarget, defaultTarget],188timeout: 30,189},190];191192var config = {193task_routing: {194filters: rules,195default_filter: defaultTarget,196},197};198199return JSON.stringify(config);200}201202function setup() {203var ctx = this;204205ctx.initClient();206207return this.initWorkspace()208.then(createWorkflowActivities.bind(ctx))209.then(createTaskQueues.bind(ctx))210.then(createWorkflow.bind(ctx))211.then(function(workspaceInfo) {212return ctx.createWorkers()213.then(function(workerInfo) {214return [workerInfo, workspaceInfo];215});216});217}218219function findByFriendlyName(friendlyName) {220var client = this.client;221222return client.list()223.then(function (data) {224return find(data, {friendlyName: friendlyName});225});226}227228function deleteByFriendlyName(friendlyName) {229var ctx = this;230231return this.findByFriendlyName(friendlyName)232.then(function(workspace) {233if (workspace.remove) {234return workspace.remove();235}236});237}238239function createWorkspace() {240return this.client.create({241friendlyName: WORKSPACE_NAME,242EVENT_CALLBACKUrl: EVENT_CALLBACK,243});244}245246function initWorkspace() {247var ctx = this;248var client = this.client;249250return ctx.findByFriendlyName(WORKSPACE_NAME)251.then(function(workspace) {252var newWorkspace;253254if (workspace) {255newWorkspace = ctx.deleteByFriendlyName(WORKSPACE_NAME)256.then(createWorkspace.bind(ctx));257} else {258newWorkspace = ctx.createWorkspace();259}260261return newWorkspace;262})263.then(function(workspace) {264ctx.initClient(workspace.sid);265266return workspace;267});268}269270return {271createTaskQueues: createTaskQueues,272createWorker: createWorker,273createWorkers: createWorkers,274createWorkflow: createWorkflow,275createWorkflowActivities: createWorkflowActivities,276createWorkflowConfig: createWorkflowConfig,277createWorkspace: createWorkspace,278deleteByFriendlyName: deleteByFriendlyName,279findByFriendlyName: findByFriendlyName,280initClient: initClient,281initWorkspace: initWorkspace,282setup: setup,283};284};
We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!
Finally, we create the Workflow using the following parameters:
friendlyName
as the name of a Workflow.
assignmentCallbackUrl
and
fallbackAssignmentCallbackUrl
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.
taskReservationTimeout
as the maximum time we want to wait until a Worker is available for handling a Task.
configuration
which is a set of rules for placing Tasks into Task Queues. The routing configuration will take a Task's attribute and match this with Task Queues. This application's Workflow rules are defined as:
"selected_product==\ "ProgrammableSMS\""
expression for
SMS
Task Queue. This expression will match any Task with
ProgrammableSMS
as the
selected_product
attribute.
"selected_product==\ "ProgrammableVoice\""
expression for
Voice
Task Queue.
lib/workspace.js
1'use strict';23var twilio = require('twilio');4var find = require('lodash/find');5var map = require('lodash/map');6var difference = require('lodash/difference');7var WORKSPACE_NAME = 'TaskRouter Node Workspace';8var HOST = process.env.HOST;9var EVENT_CALLBACK = `${HOST}/events`;10var ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;11var AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;1213module.exports = function() {14function initClient(existingWorkspaceSid) {15if (!existingWorkspaceSid) {16this.client = twilio(ACCOUNT_SID, AUTH_TOKEN).taskrouter.v1.workspaces;17} else {18this.client = twilio(ACCOUNT_SID, AUTH_TOKEN)19.taskrouter.v1.workspaces(existingWorkspaceSid);20}21}2223function createWorker(opts) {24var ctx = this;2526return this.client.activities.list({friendlyName: 'Idle'})27.then(function(idleActivity) {28return ctx.client.workers.create({29friendlyName: opts.name,30attributes: JSON.stringify({31'products': opts.products,32'contact_uri': opts.phoneNumber,33}),34activitySid: idleActivity.sid,35});36});37}3839function createWorkflow() {40var ctx = this;41var config = this.createWorkflowConfig();4243return ctx.client.workflows44.create({45friendlyName: 'Sales',46assignmentCallbackUrl: HOST + '/call/assignment',47fallbackAssignmentCallbackUrl: HOST + '/call/assignment',48taskReservationTimeout: 15,49configuration: config,50})51.then(function(workflow) {52return ctx.client.activities.list()53.then(function(activities) {54var idleActivity = find(activities, {friendlyName: 'Idle'});55var offlineActivity = find(activities, {friendlyName: 'Offline'});5657return {58workflowSid: workflow.sid,59activities: {60idle: idleActivity.sid,61offline: offlineActivity.sid,62},63workspaceSid: ctx.client._solution.sid,64};65});66});67}6869function createTaskQueues() {70var ctx = this;71return this.client.activities.list()72.then(function(activities) {73var busyActivity = find(activities, {friendlyName: 'Busy'});74var reservedActivity = find(activities, {friendlyName: 'Reserved'});7576return Promise.all([77ctx.client.taskQueues.create({78friendlyName: 'SMS',79targetWorkers: 'products HAS "ProgrammableSMS"',80assignmentActivitySid: busyActivity.sid,81reservationActivitySid: reservedActivity.sid,82}),83ctx.client.taskQueues.create({84friendlyName: 'Voice',85targetWorkers: 'products HAS "ProgrammableVoice"',86assignmentActivitySid: busyActivity.sid,87reservationActivitySid: reservedActivity.sid,88}),89ctx.client.taskQueues.create({90friendlyName: 'Default',91targetWorkers: '1==1',92assignmentActivitySid: busyActivity.sid,93reservationActivitySid: reservedActivity.sid,94}),95])96.then(function(queues) {97ctx.queues = queues;98});99});100}101102function createWorkers() {103var ctx = this;104105return Promise.all([106ctx.createWorker({107name: 'Bob',108phoneNumber: process.env.BOB_NUMBER,109products: ['ProgrammableSMS'],110}),111ctx.createWorker({112name: 'Alice',113phoneNumber: process.env.ALICE_NUMBER,114products: ['ProgrammableVoice'],115})116])117.then(function(workers) {118var bobWorker = workers[0];119var aliceWorker = workers[1];120var workerInfo = {};121122workerInfo[process.env.ALICE_NUMBER] = aliceWorker.sid;123workerInfo[process.env.BOB_NUMBER] = bobWorker.sid;124125return workerInfo;126});127}128129function createWorkflowActivities() {130var ctx = this;131var activityNames = ['Idle', 'Busy', 'Offline', 'Reserved'];132133return ctx.client.activities.list()134.then(function(activities) {135var existingActivities = map(activities, 'friendlyName');136137var missingActivities = difference(activityNames, existingActivities);138139var newActivities = map(missingActivities, function(friendlyName) {140return ctx.client.activities141.create({142friendlyName: friendlyName,143available: 'true'144});145});146147return Promise.all(newActivities);148})149.then(function() {150return ctx.client.activities.list();151});152}153154function createWorkflowConfig() {155var queues = this.queues;156157if (!queues) {158throw new Error('Queues must be initialized.');159}160161var defaultTarget = {162queue: find(queues, {friendlyName: 'Default'}).sid,163timeout: 30,164priority: 1,165};166167var smsTarget = {168queue: find(queues, {friendlyName: 'SMS'}).sid,169timeout: 30,170priority: 5,171};172173var voiceTarget = {174queue: find(queues, {friendlyName: 'Voice'}).sid,175timeout: 30,176priority: 5,177};178179var rules = [180{181expression: 'selected_product=="ProgrammableSMS"',182targets: [smsTarget, defaultTarget],183timeout: 30,184},185{186expression: 'selected_product=="ProgrammableVoice"',187targets: [voiceTarget, defaultTarget],188timeout: 30,189},190];191192var config = {193task_routing: {194filters: rules,195default_filter: defaultTarget,196},197};198199return JSON.stringify(config);200}201202function setup() {203var ctx = this;204205ctx.initClient();206207return this.initWorkspace()208.then(createWorkflowActivities.bind(ctx))209.then(createTaskQueues.bind(ctx))210.then(createWorkflow.bind(ctx))211.then(function(workspaceInfo) {212return ctx.createWorkers()213.then(function(workerInfo) {214return [workerInfo, workspaceInfo];215});216});217}218219function findByFriendlyName(friendlyName) {220var client = this.client;221222return client.list()223.then(function (data) {224return find(data, {friendlyName: friendlyName});225});226}227228function deleteByFriendlyName(friendlyName) {229var ctx = this;230231return this.findByFriendlyName(friendlyName)232.then(function(workspace) {233if (workspace.remove) {234return workspace.remove();235}236});237}238239function createWorkspace() {240return this.client.create({241friendlyName: WORKSPACE_NAME,242EVENT_CALLBACKUrl: EVENT_CALLBACK,243});244}245246function initWorkspace() {247var ctx = this;248var client = this.client;249250return ctx.findByFriendlyName(WORKSPACE_NAME)251.then(function(workspace) {252var newWorkspace;253254if (workspace) {255newWorkspace = ctx.deleteByFriendlyName(WORKSPACE_NAME)256.then(createWorkspace.bind(ctx));257} else {258newWorkspace = ctx.createWorkspace();259}260261return newWorkspace;262})263.then(function(workspace) {264ctx.initClient(workspace.sid);265266return workspace;267});268}269270return {271createTaskQueues: createTaskQueues,272createWorker: createWorker,273createWorkers: createWorkers,274createWorkflow: createWorkflow,275createWorkflowActivities: createWorkflowActivities,276createWorkflowConfig: createWorkflowConfig,277createWorkspace: createWorkspace,278deleteByFriendlyName: deleteByFriendlyName,279findByFriendlyName: findByFriendlyName,280initClient: initClient,281initWorkspace: initWorkspace,282setup: setup,283};284};
Our workspace is completely setup. Now it's time to see how we use it to route calls.
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 they can select by pressing a key. The Gather verb allows us to capture the user's key press.
routes/call.js
1'use strict';23var express = require('express'),4router = express.Router(),5VoiceResponse = require('twilio/lib/twiml/VoiceResponse');67module.exports = function (app) {8// POST /call/incoming9router.post('/incoming/', function (req, res) {10var twimlResponse = new VoiceResponse();11var gather = twimlResponse.gather({12numDigits: 1,13action: '/call/enqueue',14method: 'POST'15});16gather.say('For Programmable SMS, press one. For Voice, press any other key.');17res.type('text/xml');18res.send(twimlResponse.toString());19});2021// POST /call/enqueue22router.post('/enqueue/', function (req, res) {23var pressedKey = req.body.Digits;24var twimlResponse = new VoiceResponse();25var selectedProduct = (pressedKey === '1') ? 'ProgrammableSMS' : 'ProgrammableVoice';26var enqueue = twimlResponse.enqueueTask(27{workflowSid: app.get('workspaceInfo').workflowSid}28);29enqueue.task({}, JSON.stringify({selected_product: selectedProduct}));3031res.type('text/xml');32res.send(twimlResponse.toString());33});3435// POST /call/assignment36router.post('/assignment/', function (req, res) {37res.type('application/json');38res.send({39instruction: "dequeue",40post_work_activity_sid: app.get('workspaceInfo').activities.idle41});42});4344return router;45};
We just asked the caller to choose a product, next we will use their choice to create the appropriate Task.
This is the endpoint set as the action
URL on the Gather
verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits
parameter that holds the pressed keys. A Task
will be created based on the pressed digit with the selected_product
as an attribute. The Workflow will take this Task's attributes and match with the configured expressions in order to find a Task Queue for this Task, so an appropriate available Worker can be assigned to handle it.
We use the Enqueue
verb with a WorkflowSid
attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.
routes/call.js
1'use strict';23var express = require('express'),4router = express.Router(),5VoiceResponse = require('twilio/lib/twiml/VoiceResponse');67module.exports = function (app) {8// POST /call/incoming9router.post('/incoming/', function (req, res) {10var twimlResponse = new VoiceResponse();11var gather = twimlResponse.gather({12numDigits: 1,13action: '/call/enqueue',14method: 'POST'15});16gather.say('For Programmable SMS, press one. For Voice, press any other key.');17res.type('text/xml');18res.send(twimlResponse.toString());19});2021// POST /call/enqueue22router.post('/enqueue/', function (req, res) {23var pressedKey = req.body.Digits;24var twimlResponse = new VoiceResponse();25var selectedProduct = (pressedKey === '1') ? 'ProgrammableSMS' : 'ProgrammableVoice';26var enqueue = twimlResponse.enqueueTask(27{workflowSid: app.get('workspaceInfo').workflowSid}28);29enqueue.task({}, JSON.stringify({selected_product: selectedProduct}));3031res.type('text/xml');32res.send(twimlResponse.toString());33});3435// POST /call/assignment36router.post('/assignment/', function (req, res) {37res.type('application/json');38res.send({39instruction: "dequeue",40post_work_activity_sid: app.get('workspaceInfo').activities.idle41});42});4344return router;45};
After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.
When TaskRouter selects a Worker, it does the following:
POST
request is made to the Workflow's AssignmentCallbackURL, which was configured while creating the Workflow. This request includes the full details of the Task, the selected Worker, and the Reservation.
Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, email, push notifications or make a call.
Since we created this Task during a voice call with an Enqueue
verb, lets 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.
routes/call.js
1'use strict';23var express = require('express'),4router = express.Router(),5VoiceResponse = require('twilio/lib/twiml/VoiceResponse');67module.exports = function (app) {8// POST /call/incoming9router.post('/incoming/', function (req, res) {10var twimlResponse = new VoiceResponse();11var gather = twimlResponse.gather({12numDigits: 1,13action: '/call/enqueue',14method: 'POST'15});16gather.say('For Programmable SMS, press one. For Voice, press any other key.');17res.type('text/xml');18res.send(twimlResponse.toString());19});2021// POST /call/enqueue22router.post('/enqueue/', function (req, res) {23var pressedKey = req.body.Digits;24var twimlResponse = new VoiceResponse();25var selectedProduct = (pressedKey === '1') ? 'ProgrammableSMS' : 'ProgrammableVoice';26var enqueue = twimlResponse.enqueueTask(27{workflowSid: app.get('workspaceInfo').workflowSid}28);29enqueue.task({}, JSON.stringify({selected_product: selectedProduct}));3031res.type('text/xml');32res.send(twimlResponse.toString());33});3435// POST /call/assignment36router.post('/assignment/', function (req, res) {37res.type('application/json');38res.send({39instruction: "dequeue",40post_work_activity_sid: app.get('workspaceInfo').activities.idle41});42});4344return router;45};
Now that our Tasks are routed properly, let's deal with missed calls in the next step.
This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout
event. This event is triggered when the Task waits more than the limit set on the 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.
routes/events.js
1'use strict';23var express = require('express'),4MissedCall = require('../models/missed-call'),5util = require('util'),6querystring = require('querystring'),7router = express.Router(),8Q = require('q');910// POST /events11router.post('/', function (req, res) {12var eventType = req.body.EventType;13var taskAttributes = (req.body.TaskAttributes)? JSON.parse(req.body.TaskAttributes) : {};1415function saveMissedCall(){16return MissedCall.create({17selectedProduct: taskAttributes.selected_product,18phoneNumber: taskAttributes.from19});20}2122var eventHandler = {23'task.canceled': saveMissedCall,24'workflow.timeout': function() {25return saveMissedCall().then(voicemail(taskAttributes.call_sid));26},27'worker.activity.update': function(){28var workerAttributes = JSON.parse(req.body.WorkerAttributes);29if (req.body.WorkerActivityName === 'Offline') {30notifyOfflineStatus(workerAttributes.contact_uri);31}32return Q.resolve({});33},34'default': function() { return Q.resolve({}); }35};3637(eventHandler[eventType] || eventHandler['default'])().then(function () {38res.json({});39});40});4142function voicemail (callSid){43var client = buildClient(),44query = querystring.stringify({45Message: 'Sorry, All agents are busy. Please leave a message. We\'ll call you as soon as possible',46Email: process.env.MISSED_CALLS_EMAIL_ADDRESS}),47voicemailUrl = util.format("http://twimlets.com/voicemail?%s", query);4849client.calls(callSid).update({50method: 'POST',51url: voicemailUrl52});53}5455function notifyOfflineStatus(phone_number) {56var client = buildClient(),57message = 'Your status has changed to Offline. Reply with "On" to get back Online';58client.sendMessage({59to: phone_number,60from: process.env.TWILIO_NUMBER,61body: message62});63}6465function buildClient() {66var accountSid = process.env.TWILIO_ACCOUNT_SID,67authToken = process.env.TWILIO_AUTH_TOKEN;68return require('twilio')(accountSid, authToken);69}7071module.exports = router;
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.
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.
routes/sms.js
1'use strict';23var express = require('express'),4router = express.Router(),5twimlGenerator = require('../lib/twiml-generator');67module.exports = function (app) {8// POST /sms/incoming9router.post('/incoming/', function (req, res) {10var targetActivity = (req.body.Body.toLowerCase() === "on")? "idle":"offline";11var activitySid = app.get('workspaceInfo').activities[targetActivity];12changeWorkerActivitySid(req.body.From, activitySid);13res.type('text/xml');14res.send(twimlGenerator.generateConfirmMessage(targetActivity));15});1617function changeWorkerActivitySid(workerNumber, activitySid){18var accountSid = process.env.TWILIO_ACCOUNT_SID,19authToken = process.env.TWILIO_AUTH_TOKEN,20workspaceSid = app.get('workspaceInfo').workspaceSid,21workerSid = app.get('workerInfo')[workerNumber],22twilio = require('twilio'),23client = new twilio.TaskRouterClient(accountSid, authToken, workspaceSid);24client.workspace.workers(workerSid).update({activitySid: activitySid});25}26return router;27};
Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.
If you're a Node.js/Express developer working with Twilio, you might enjoy these other tutorials:
Have you ever been disconnected from a support call while being transferred to another support agent? Warm transfer eliminates this problem. Using Twilio powered warm transfers your agents will have the ability to conference in another agent in realtime.
Instantly collect structured data from your users with a survey conducted over a call or SMS text messages.