In this tutorial we will show how to automate the routing of calls from customers to your support agents. Customers will be able to select a product and wait while TaskRouter tries to contact a product specialist for the best support experience. If no one is available, our application will save the customer's number and selected product so an agent can call them back later on.
This is what the application does at a high level:
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.
A Workspace is the container element for any TaskRouter application. The elements are:
resources/workspace.json
1{2"name": "Twilio Workspace",3"event_callback": "%(host)s/events",4"workers": [5{6"name": "Bob",7"attributes": {8"products": [9"ProgrammableSMS"10],11"contact_uri": "%(bob_phone)s"12}13},14{15"name": "Alice",16"attributes": {17"products": [18"ProgrammableVoice"19],20"contact_uri": "%(alice_phone)s"21}22}23],24"activities": [25{26"name": "Offline",27"availability": "false"28},29{30"name": "Idle",31"availability": "true"32},33{34"name": "Busy",35"availability": "false"36},37{38"name": "Reserved",39"availability": "false"40}41],42"task_queues": [43{44"name": "Default",45"targetWorkers": "1==1"46},47{48"name": "SMS",49"targetWorkers": "products HAS \"ProgrammableSMS\""50},51{52"name": "Voice",53"targetWorkers": "products HAS \"ProgrammableVoice\""54}55],56"workflow": {57"name": "Sales",58"callback": "%(host)s/assignment",59"timeout": "15"60}61}
In order to build a client for this API, we need as system variables a TWILIO_ACCOUNT_SID
and TWILIO_AUTH_TOKEN
which you can find on Twilio Console. The artisan command workspace:create
creates a Twilio\Rest\Client
, which is provided by the Twilio PHP library. This client is used by WorkspaceFacade which encapsulates all logic related to the creation of a Task Router workflow.
Let's take a look at that command next.
In this application the Artisan command workspace:create
is used to orchestrate calls to our WorkspaceFacade
class in order to build a Workspace from scratch. CreateWorkspace
is the PHP class behind the Artisan command. It uses data provided by workspace.json
and expects 3 arguments:
host
- A public URL to which Twilio can send requests. This can be either a cloud service or
ngrok
, which can expose a local application to the internet.
bob_phone
- The telephone number of Bob, the Programmable SMS specialist.
alice_phone
- Same for Alice, the Programmable Voice specialist.
The function createWorkspaceConfig
is used to load the configuration of the workspace from workspace.json
.
app/Console/Commands/CreateWorkspace.php
1<?php23namespace App\Console\Commands;45use App\TaskRouter\WorkspaceFacade;6use Illuminate\Console\Command;7use Illuminate\Support\Facades\File;8use TaskRouter_Services_Twilio;9use Twilio\Rest\Client;10use Twilio\Rest\Taskrouter;11use WorkflowRuleTarget;1213class CreateWorkspace extends Command14{15/**16* The name and signature of the console command.17*18* @var string19*/20protected $signature = 'workspace:create21{host : Server hostname in Internet}22{bob_phone : Phone of the first agent (Bob)}23{alice_phone : Phone of the secondary agent (Alice)}';2425/**26* The console command description.27*28* @var string29*/30protected $description = 'Creates a Twilio workspace for 2 call agents';3132private $_twilioClient;3334/**35* Create a new command instance.36*/37public function __construct(Client $twilioClient)38{39parent::__construct();40$this->_twilioClient = $twilioClient;41}4243/**44* Execute the console command.45*46* @return mixed47*/48public function handle()49{50$this->info("Create workspace.");51$this->line("- Server: \t{$this->argument('host')}");52$this->line("- Bob phone: \t{$this->argument('bob_phone')}");53$this->line("- Alice phone: \t{$this->argument('alice_phone')}");5455//Get the configuration56$workspaceConfig = $this->createWorkspaceConfig();5758//Create the workspace59$params = array();60$params['friendlyName'] = $workspaceConfig->name;61$params['eventCallbackUrl'] = $workspaceConfig->event_callback;62$workspace = WorkspaceFacade::createNewWorkspace(63$this->_twilioClient->taskrouter,64$params65);66$this->addWorkersToWorkspace($workspace, $workspaceConfig);67$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);68$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);6970$this->printSuccessAndInstructions($workspace, $workflow);71}7273/**74* Get the json configuration of the Workspace75*76* @return mixed77*/78function createWorkspaceConfig()79{80$fileContent = File::get("resources/workspace.json");81$interpolatedContent = sprintfn($fileContent, $this->argument());82return json_decode($interpolatedContent);83}8485/**86* Add workers to workspace87*88* @param $workspace WorkspaceFacade89* @param $workspaceConfig string with Json90*/91function addWorkersToWorkspace($workspace, $workspaceConfig)92{93$this->line("Add Workers.");94$idleActivity = $workspace->findActivityByName("Idle")95or die("The activity 'Idle' was not found. Workers cannot be added.");96foreach ($workspaceConfig->workers as $workerJson) {97$params = array();98$params['friendlyName'] = $workerJson->name;99$params['activitySid'] = $idleActivity->sid;100$params['attributes'] = json_encode($workerJson->attributes);101$workspace->addWorker($params);102}103}104105/**106* Add the Task Queues to the workspace107*108* @param $workspace WorkspaceFacade109* @param $workspaceConfig string with Json110*/111function addTaskQueuesToWorkspace($workspace, $workspaceConfig)112{113$this->line("Add Task Queues.");114$reservedActivity = $workspace->findActivityByName("Reserved");115$assignmentActivity = $workspace->findActivityByName("Busy");116foreach ($workspaceConfig->task_queues as $taskQueueJson) {117$params = array();118$params['friendlyName'] = $taskQueueJson->name;119$params['targetWorkers'] = $taskQueueJson->targetWorkers;120$params['reservationActivitySid'] = $reservedActivity->sid;121$params['assignmentActivitySid'] = $assignmentActivity->sid;122$workspace->addTaskQueue($params);123}124}125126/**127* Create and configure the workflow to use in the workspace128*129* @param $workspace WorkspaceFacade130* @param $workspaceConfig string with Json131*132* @return object with added workflow133*/134function addWorkflowToWorkspace($workspace, $workspaceConfig)135{136$this->line("Add Worflow.");137$workflowJson = $workspaceConfig->workflow;138$params = array();139$params['friendlyName'] = $workflowJson->name;140$params['assignmentCallbackUrl'] = $workflowJson->callback;141$params['taskReservationTimeout'] = $workflowJson->timeout;142$params['configuration'] = $this->createWorkFlowJsonConfig(143$workspace,144$workflowJson145);146return $workspace->addWorkflow($params);147}148149/**150* Create the workflow configuration in json format151*152* @param $workspace153* @param $workspaceConfig154*155* @return string configuration of workflow in json format156*/157function createWorkFlowJsonConfig($workspace, $workspaceConfig)158{159$params = array();160$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(161"The 'Default' task queue was not found. The Workflow cannot be created."162);163$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(164"The 'SMS' task queue was not found. The Workflow cannot be created."165);166$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(167"The 'Voice' task queue was not found. The Workflow cannot be created."168);169170$params["default_task_queue_sid"] = $defaultTaskQueue->sid;171$params["sms_task_queue_sid"] = $smsTaskQueue->sid;172$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;173174$fileContent = File::get("resources/workflow.json");175$interpolatedContent = sprintfn($fileContent, $params);176return $interpolatedContent;177}178179/**180* Prints the message indicating the workspace was successfully created and181* shows the commands to export the workspace variables into the environment.182*183* @param $workspace184* @param $workflow185*/186function printSuccessAndInstructions($workspace, $workflow)187{188$idleActivity = $workspace->findActivityByName("Idle")189or die("Somehow the activity 'Idle' was not found.");190$successMsg = "Workspace \"{$workspace->friendlyName}\"" .191" was created successfully.";192$this->printTitle($successMsg);193$this->line(194"The following variables will be set automatically."195);196$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());197$envVars = [198"WORKFLOW_SID" => $workflow->sid,199"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,200"WORKSPACE_SID" => $workspace->sid,201"PHONE_TO_WORKER" => $encondedWorkersPhone202];203updateEnv($envVars);204foreach ($envVars as $key => $value) {205$this->warn("export $key=$value");206}207}208209/**210* Prints a text separated up and doNwn by a token based line, usually "*"211*/212function printTitle($text)213{214$lineLength = strlen($text) + 2;215$this->line(str_repeat("*", $lineLength));216$this->line(" $text ");217$this->line(str_repeat("*", $lineLength));218}219}
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 identifier. In order to create a workspace we need to provide a friendlyName
, and a eventCallbackUrl
which contains a URL to be called every time an event is triggered in the workspace.
app/TaskRouter/WorkspaceFacade.php
1<?php23namespace App\TaskRouter;45use Twilio\Rest\Taskrouter\V1\Workspace;678class WorkspaceFacade9{10private $_taskRouterClient;1112private $_workspace;1314private $_activities;1516public function __construct($taskRouterClient, $workspace)17{18$this->_taskRouterClient = $taskRouterClient;19$this->_workspace = $workspace;20}2122public static function createNewWorkspace($taskRouterClient, $params)23{24$workspaceName = $params["friendlyName"];25$existingWorkspace = $taskRouterClient->workspaces->read(26array(27"friendlyName" => $workspaceName28)29);30if ($existingWorkspace) {31$existingWorkspace[0]->delete();32}3334$workspace = $taskRouterClient->workspaces35->create($workspaceName, $params);36return new WorkspaceFacade($taskRouterClient, $workspace);37}3839public static function createBySid($taskRouterClient, $workspaceSid)40{41$workspace = $taskRouterClient->workspaces($workspaceSid);42return new WorkspaceFacade($taskRouterClient, $workspace);43}4445/**46* Magic getter to lazy load subresources47*48* @param string $property Subresource to return49*50* @return \Twilio\ListResource The requested subresource51*52* @throws \Twilio\Exceptions\TwilioException For unknown subresources53*/54public function __get($property)55{56return $this->_workspace->$property;57}5859/**60* Gets an activity instance by its friendly name61*62* @param $activityName Friendly name of the activity to search for63*64* @return ActivityInstance of the activity found or null65*/66function findActivityByName($activityName)67{68$this->cacheActivitiesByName();69return $this->_activities[$activityName];70}7172/**73* Caches the activities in an associative array which links friendlyName with74* its ActivityInstance75*/76protected function cacheActivitiesByName()77{78if (!$this->_activities) {79$this->_activities = array();80foreach ($this->_workspace->activities->read() as $activity) {81$this->_activities[$activity->friendlyName] = $activity;82}83}84}8586/**87* Looks for a worker by its SID88*89* @param $sid string with the Worker SID90*91* @return mixed worker found or null92*/93function findWorkerBySid($sid)94{95return $this->_workspace->workers($sid);96}9798/**99* Returns an associative array with100*101* @return mixed array with the relation phone -> workerSid102*/103function getWorkerPhones()104{105$worker_phones = array();106foreach ($this->_workspace->workers->read() as $worker) {107$workerAttribs = json_decode($worker->attributes);108$worker_phones[$workerAttribs->contact_uri] = $worker->sid;109}110return $worker_phones;111}112113/**114* Looks for a Task Queue by its friendly name115*116* @param $taskQueueName string with the friendly name of the task queue to117* search for118*119* @return the activity found or null120*/121function findTaskQueueByName($taskQueueName)122{123$result = $this->_workspace->taskQueues->read(124array(125"friendlyName" => $taskQueueName126)127);128if ($result) {129return $result[0];130}131}132133function updateWorkerActivity($worker, $activitySid)134{135$worker->update(['activitySid' => $activitySid]);136}137138/**139* Adds workers to the workspace140*141* @param $params mixed with the attributes to define the new Worker in the142* workspace143*144* @return Workspace\WorkerInstance|Null145*/146function addWorker($params)147{148return $this->_workspace->workers->create($params['friendlyName'], $params);149}150151/**152* Adds a Task Queue to the workspace153*154* @param $params mixed with attributes to define the new Task Queue in the155* workspace156*157* @return Workspace\TaskQueueInstance|Null158*/159function addTaskQueue($params)160{161return $this->_workspace->taskQueues->create(162$params['friendlyName'],163$params['reservationActivitySid'],164$params['assignmentActivitySid'],165$params166);167}168169170/**171* Adds a workflow to the workspace172*173* @param $params mixed with attributes to define the new Workflow in the174* workspace175*176* @return Workspace\WorkflowInstance|Null177*/178function addWorkFlow($params)179{180return $this->_workspace->workflows->create(181$params["friendlyName"],182$params["configuration"],183$params184);185}186187}
We have a brand new workspace, now we need workers. Let's create them on the next step.
We'll create two workers: Bob and Alice. They each have two attributes: contact_uri
, a phone number, and products
, a list of products each worker is specialized in. We also need to specify an activity_sid
and a name for each worker. The selected activity will define the status of the worker.
app/Console/Commands/CreateWorkspace.php
1<?php23namespace App\Console\Commands;45use App\TaskRouter\WorkspaceFacade;6use Illuminate\Console\Command;7use Illuminate\Support\Facades\File;8use TaskRouter_Services_Twilio;9use Twilio\Rest\Client;10use Twilio\Rest\Taskrouter;11use WorkflowRuleTarget;1213class CreateWorkspace extends Command14{15/**16* The name and signature of the console command.17*18* @var string19*/20protected $signature = 'workspace:create21{host : Server hostname in Internet}22{bob_phone : Phone of the first agent (Bob)}23{alice_phone : Phone of the secondary agent (Alice)}';2425/**26* The console command description.27*28* @var string29*/30protected $description = 'Creates a Twilio workspace for 2 call agents';3132private $_twilioClient;3334/**35* Create a new command instance.36*/37public function __construct(Client $twilioClient)38{39parent::__construct();40$this->_twilioClient = $twilioClient;41}4243/**44* Execute the console command.45*46* @return mixed47*/48public function handle()49{50$this->info("Create workspace.");51$this->line("- Server: \t{$this->argument('host')}");52$this->line("- Bob phone: \t{$this->argument('bob_phone')}");53$this->line("- Alice phone: \t{$this->argument('alice_phone')}");5455//Get the configuration56$workspaceConfig = $this->createWorkspaceConfig();5758//Create the workspace59$params = array();60$params['friendlyName'] = $workspaceConfig->name;61$params['eventCallbackUrl'] = $workspaceConfig->event_callback;62$workspace = WorkspaceFacade::createNewWorkspace(63$this->_twilioClient->taskrouter,64$params65);66$this->addWorkersToWorkspace($workspace, $workspaceConfig);67$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);68$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);6970$this->printSuccessAndInstructions($workspace, $workflow);71}7273/**74* Get the json configuration of the Workspace75*76* @return mixed77*/78function createWorkspaceConfig()79{80$fileContent = File::get("resources/workspace.json");81$interpolatedContent = sprintfn($fileContent, $this->argument());82return json_decode($interpolatedContent);83}8485/**86* Add workers to workspace87*88* @param $workspace WorkspaceFacade89* @param $workspaceConfig string with Json90*/91function addWorkersToWorkspace($workspace, $workspaceConfig)92{93$this->line("Add Workers.");94$idleActivity = $workspace->findActivityByName("Idle")95or die("The activity 'Idle' was not found. Workers cannot be added.");96foreach ($workspaceConfig->workers as $workerJson) {97$params = array();98$params['friendlyName'] = $workerJson->name;99$params['activitySid'] = $idleActivity->sid;100$params['attributes'] = json_encode($workerJson->attributes);101$workspace->addWorker($params);102}103}104105/**106* Add the Task Queues to the workspace107*108* @param $workspace WorkspaceFacade109* @param $workspaceConfig string with Json110*/111function addTaskQueuesToWorkspace($workspace, $workspaceConfig)112{113$this->line("Add Task Queues.");114$reservedActivity = $workspace->findActivityByName("Reserved");115$assignmentActivity = $workspace->findActivityByName("Busy");116foreach ($workspaceConfig->task_queues as $taskQueueJson) {117$params = array();118$params['friendlyName'] = $taskQueueJson->name;119$params['targetWorkers'] = $taskQueueJson->targetWorkers;120$params['reservationActivitySid'] = $reservedActivity->sid;121$params['assignmentActivitySid'] = $assignmentActivity->sid;122$workspace->addTaskQueue($params);123}124}125126/**127* Create and configure the workflow to use in the workspace128*129* @param $workspace WorkspaceFacade130* @param $workspaceConfig string with Json131*132* @return object with added workflow133*/134function addWorkflowToWorkspace($workspace, $workspaceConfig)135{136$this->line("Add Worflow.");137$workflowJson = $workspaceConfig->workflow;138$params = array();139$params['friendlyName'] = $workflowJson->name;140$params['assignmentCallbackUrl'] = $workflowJson->callback;141$params['taskReservationTimeout'] = $workflowJson->timeout;142$params['configuration'] = $this->createWorkFlowJsonConfig(143$workspace,144$workflowJson145);146return $workspace->addWorkflow($params);147}148149/**150* Create the workflow configuration in json format151*152* @param $workspace153* @param $workspaceConfig154*155* @return string configuration of workflow in json format156*/157function createWorkFlowJsonConfig($workspace, $workspaceConfig)158{159$params = array();160$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(161"The 'Default' task queue was not found. The Workflow cannot be created."162);163$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(164"The 'SMS' task queue was not found. The Workflow cannot be created."165);166$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(167"The 'Voice' task queue was not found. The Workflow cannot be created."168);169170$params["default_task_queue_sid"] = $defaultTaskQueue->sid;171$params["sms_task_queue_sid"] = $smsTaskQueue->sid;172$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;173174$fileContent = File::get("resources/workflow.json");175$interpolatedContent = sprintfn($fileContent, $params);176return $interpolatedContent;177}178179/**180* Prints the message indicating the workspace was successfully created and181* shows the commands to export the workspace variables into the environment.182*183* @param $workspace184* @param $workflow185*/186function printSuccessAndInstructions($workspace, $workflow)187{188$idleActivity = $workspace->findActivityByName("Idle")189or die("Somehow the activity 'Idle' was not found.");190$successMsg = "Workspace \"{$workspace->friendlyName}\"" .191" was created successfully.";192$this->printTitle($successMsg);193$this->line(194"The following variables will be set automatically."195);196$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());197$envVars = [198"WORKFLOW_SID" => $workflow->sid,199"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,200"WORKSPACE_SID" => $workspace->sid,201"PHONE_TO_WORKER" => $encondedWorkersPhone202];203updateEnv($envVars);204foreach ($envVars as $key => $value) {205$this->warn("export $key=$value");206}207}208209/**210* Prints a text separated up and doNwn by a token based line, usually "*"211*/212function printTitle($text)213{214$lineLength = strlen($text) + 2;215$this->line(str_repeat("*", $lineLength));216$this->line(" $text ");217$this->line(str_repeat("*", $lineLength));218}219}
After creating our workers, let's set up the Task Queues.
Next, we set up the Task Queues. Each with a name and a targetWorkers
property, 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
"products HAS \"ProgrammableSMS\""
.
Voice
- Will do the same for Programmable Voice Workers, such as Alice, using the expression
"products HAS \"ProgrammableVoice\""
.
All
- 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.
app/Console/Commands/CreateWorkspace.php
1<?php23namespace App\Console\Commands;45use App\TaskRouter\WorkspaceFacade;6use Illuminate\Console\Command;7use Illuminate\Support\Facades\File;8use TaskRouter_Services_Twilio;9use Twilio\Rest\Client;10use Twilio\Rest\Taskrouter;11use WorkflowRuleTarget;1213class CreateWorkspace extends Command14{15/**16* The name and signature of the console command.17*18* @var string19*/20protected $signature = 'workspace:create21{host : Server hostname in Internet}22{bob_phone : Phone of the first agent (Bob)}23{alice_phone : Phone of the secondary agent (Alice)}';2425/**26* The console command description.27*28* @var string29*/30protected $description = 'Creates a Twilio workspace for 2 call agents';3132private $_twilioClient;3334/**35* Create a new command instance.36*/37public function __construct(Client $twilioClient)38{39parent::__construct();40$this->_twilioClient = $twilioClient;41}4243/**44* Execute the console command.45*46* @return mixed47*/48public function handle()49{50$this->info("Create workspace.");51$this->line("- Server: \t{$this->argument('host')}");52$this->line("- Bob phone: \t{$this->argument('bob_phone')}");53$this->line("- Alice phone: \t{$this->argument('alice_phone')}");5455//Get the configuration56$workspaceConfig = $this->createWorkspaceConfig();5758//Create the workspace59$params = array();60$params['friendlyName'] = $workspaceConfig->name;61$params['eventCallbackUrl'] = $workspaceConfig->event_callback;62$workspace = WorkspaceFacade::createNewWorkspace(63$this->_twilioClient->taskrouter,64$params65);66$this->addWorkersToWorkspace($workspace, $workspaceConfig);67$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);68$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);6970$this->printSuccessAndInstructions($workspace, $workflow);71}7273/**74* Get the json configuration of the Workspace75*76* @return mixed77*/78function createWorkspaceConfig()79{80$fileContent = File::get("resources/workspace.json");81$interpolatedContent = sprintfn($fileContent, $this->argument());82return json_decode($interpolatedContent);83}8485/**86* Add workers to workspace87*88* @param $workspace WorkspaceFacade89* @param $workspaceConfig string with Json90*/91function addWorkersToWorkspace($workspace, $workspaceConfig)92{93$this->line("Add Workers.");94$idleActivity = $workspace->findActivityByName("Idle")95or die("The activity 'Idle' was not found. Workers cannot be added.");96foreach ($workspaceConfig->workers as $workerJson) {97$params = array();98$params['friendlyName'] = $workerJson->name;99$params['activitySid'] = $idleActivity->sid;100$params['attributes'] = json_encode($workerJson->attributes);101$workspace->addWorker($params);102}103}104105/**106* Add the Task Queues to the workspace107*108* @param $workspace WorkspaceFacade109* @param $workspaceConfig string with Json110*/111function addTaskQueuesToWorkspace($workspace, $workspaceConfig)112{113$this->line("Add Task Queues.");114$reservedActivity = $workspace->findActivityByName("Reserved");115$assignmentActivity = $workspace->findActivityByName("Busy");116foreach ($workspaceConfig->task_queues as $taskQueueJson) {117$params = array();118$params['friendlyName'] = $taskQueueJson->name;119$params['targetWorkers'] = $taskQueueJson->targetWorkers;120$params['reservationActivitySid'] = $reservedActivity->sid;121$params['assignmentActivitySid'] = $assignmentActivity->sid;122$workspace->addTaskQueue($params);123}124}125126/**127* Create and configure the workflow to use in the workspace128*129* @param $workspace WorkspaceFacade130* @param $workspaceConfig string with Json131*132* @return object with added workflow133*/134function addWorkflowToWorkspace($workspace, $workspaceConfig)135{136$this->line("Add Worflow.");137$workflowJson = $workspaceConfig->workflow;138$params = array();139$params['friendlyName'] = $workflowJson->name;140$params['assignmentCallbackUrl'] = $workflowJson->callback;141$params['taskReservationTimeout'] = $workflowJson->timeout;142$params['configuration'] = $this->createWorkFlowJsonConfig(143$workspace,144$workflowJson145);146return $workspace->addWorkflow($params);147}148149/**150* Create the workflow configuration in json format151*152* @param $workspace153* @param $workspaceConfig154*155* @return string configuration of workflow in json format156*/157function createWorkFlowJsonConfig($workspace, $workspaceConfig)158{159$params = array();160$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(161"The 'Default' task queue was not found. The Workflow cannot be created."162);163$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(164"The 'SMS' task queue was not found. The Workflow cannot be created."165);166$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(167"The 'Voice' task queue was not found. The Workflow cannot be created."168);169170$params["default_task_queue_sid"] = $defaultTaskQueue->sid;171$params["sms_task_queue_sid"] = $smsTaskQueue->sid;172$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;173174$fileContent = File::get("resources/workflow.json");175$interpolatedContent = sprintfn($fileContent, $params);176return $interpolatedContent;177}178179/**180* Prints the message indicating the workspace was successfully created and181* shows the commands to export the workspace variables into the environment.182*183* @param $workspace184* @param $workflow185*/186function printSuccessAndInstructions($workspace, $workflow)187{188$idleActivity = $workspace->findActivityByName("Idle")189or die("Somehow the activity 'Idle' was not found.");190$successMsg = "Workspace \"{$workspace->friendlyName}\"" .191" was created successfully.";192$this->printTitle($successMsg);193$this->line(194"The following variables will be set automatically."195);196$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());197$envVars = [198"WORKFLOW_SID" => $workflow->sid,199"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,200"WORKSPACE_SID" => $workspace->sid,201"PHONE_TO_WORKER" => $encondedWorkersPhone202];203updateEnv($envVars);204foreach ($envVars as $key => $value) {205$this->warn("export $key=$value");206}207}208209/**210* Prints a text separated up and doNwn by a token based line, usually "*"211*/212function printTitle($text)213{214$lineLength = strlen($text) + 2;215$this->line(str_repeat("*", $lineLength));216$this->line(" $text ");217$this->line(str_repeat("*", $lineLength));218}219}
We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!
Finally, we set up the Workflow using the following parameters:
friendlyName
as the name of a Workflow.
assignmentCallbackUrl
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 handles a Task.
configuration
which is a set of rules for placing Task 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.
app/Console/Commands/CreateWorkspace.php
1<?php23namespace App\Console\Commands;45use App\TaskRouter\WorkspaceFacade;6use Illuminate\Console\Command;7use Illuminate\Support\Facades\File;8use TaskRouter_Services_Twilio;9use Twilio\Rest\Client;10use Twilio\Rest\Taskrouter;11use WorkflowRuleTarget;1213class CreateWorkspace extends Command14{15/**16* The name and signature of the console command.17*18* @var string19*/20protected $signature = 'workspace:create21{host : Server hostname in Internet}22{bob_phone : Phone of the first agent (Bob)}23{alice_phone : Phone of the secondary agent (Alice)}';2425/**26* The console command description.27*28* @var string29*/30protected $description = 'Creates a Twilio workspace for 2 call agents';3132private $_twilioClient;3334/**35* Create a new command instance.36*/37public function __construct(Client $twilioClient)38{39parent::__construct();40$this->_twilioClient = $twilioClient;41}4243/**44* Execute the console command.45*46* @return mixed47*/48public function handle()49{50$this->info("Create workspace.");51$this->line("- Server: \t{$this->argument('host')}");52$this->line("- Bob phone: \t{$this->argument('bob_phone')}");53$this->line("- Alice phone: \t{$this->argument('alice_phone')}");5455//Get the configuration56$workspaceConfig = $this->createWorkspaceConfig();5758//Create the workspace59$params = array();60$params['friendlyName'] = $workspaceConfig->name;61$params['eventCallbackUrl'] = $workspaceConfig->event_callback;62$workspace = WorkspaceFacade::createNewWorkspace(63$this->_twilioClient->taskrouter,64$params65);66$this->addWorkersToWorkspace($workspace, $workspaceConfig);67$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);68$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);6970$this->printSuccessAndInstructions($workspace, $workflow);71}7273/**74* Get the json configuration of the Workspace75*76* @return mixed77*/78function createWorkspaceConfig()79{80$fileContent = File::get("resources/workspace.json");81$interpolatedContent = sprintfn($fileContent, $this->argument());82return json_decode($interpolatedContent);83}8485/**86* Add workers to workspace87*88* @param $workspace WorkspaceFacade89* @param $workspaceConfig string with Json90*/91function addWorkersToWorkspace($workspace, $workspaceConfig)92{93$this->line("Add Workers.");94$idleActivity = $workspace->findActivityByName("Idle")95or die("The activity 'Idle' was not found. Workers cannot be added.");96foreach ($workspaceConfig->workers as $workerJson) {97$params = array();98$params['friendlyName'] = $workerJson->name;99$params['activitySid'] = $idleActivity->sid;100$params['attributes'] = json_encode($workerJson->attributes);101$workspace->addWorker($params);102}103}104105/**106* Add the Task Queues to the workspace107*108* @param $workspace WorkspaceFacade109* @param $workspaceConfig string with Json110*/111function addTaskQueuesToWorkspace($workspace, $workspaceConfig)112{113$this->line("Add Task Queues.");114$reservedActivity = $workspace->findActivityByName("Reserved");115$assignmentActivity = $workspace->findActivityByName("Busy");116foreach ($workspaceConfig->task_queues as $taskQueueJson) {117$params = array();118$params['friendlyName'] = $taskQueueJson->name;119$params['targetWorkers'] = $taskQueueJson->targetWorkers;120$params['reservationActivitySid'] = $reservedActivity->sid;121$params['assignmentActivitySid'] = $assignmentActivity->sid;122$workspace->addTaskQueue($params);123}124}125126/**127* Create and configure the workflow to use in the workspace128*129* @param $workspace WorkspaceFacade130* @param $workspaceConfig string with Json131*132* @return object with added workflow133*/134function addWorkflowToWorkspace($workspace, $workspaceConfig)135{136$this->line("Add Worflow.");137$workflowJson = $workspaceConfig->workflow;138$params = array();139$params['friendlyName'] = $workflowJson->name;140$params['assignmentCallbackUrl'] = $workflowJson->callback;141$params['taskReservationTimeout'] = $workflowJson->timeout;142$params['configuration'] = $this->createWorkFlowJsonConfig(143$workspace,144$workflowJson145);146return $workspace->addWorkflow($params);147}148149/**150* Create the workflow configuration in json format151*152* @param $workspace153* @param $workspaceConfig154*155* @return string configuration of workflow in json format156*/157function createWorkFlowJsonConfig($workspace, $workspaceConfig)158{159$params = array();160$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(161"The 'Default' task queue was not found. The Workflow cannot be created."162);163$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(164"The 'SMS' task queue was not found. The Workflow cannot be created."165);166$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(167"The 'Voice' task queue was not found. The Workflow cannot be created."168);169170$params["default_task_queue_sid"] = $defaultTaskQueue->sid;171$params["sms_task_queue_sid"] = $smsTaskQueue->sid;172$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;173174$fileContent = File::get("resources/workflow.json");175$interpolatedContent = sprintfn($fileContent, $params);176return $interpolatedContent;177}178179/**180* Prints the message indicating the workspace was successfully created and181* shows the commands to export the workspace variables into the environment.182*183* @param $workspace184* @param $workflow185*/186function printSuccessAndInstructions($workspace, $workflow)187{188$idleActivity = $workspace->findActivityByName("Idle")189or die("Somehow the activity 'Idle' was not found.");190$successMsg = "Workspace \"{$workspace->friendlyName}\"" .191" was created successfully.";192$this->printTitle($successMsg);193$this->line(194"The following variables will be set automatically."195);196$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());197$envVars = [198"WORKFLOW_SID" => $workflow->sid,199"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,200"WORKSPACE_SID" => $workspace->sid,201"PHONE_TO_WORKER" => $encondedWorkersPhone202];203updateEnv($envVars);204foreach ($envVars as $key => $value) {205$this->warn("export $key=$value");206}207}208209/**210* Prints a text separated up and doNwn by a token based line, usually "*"211*/212function printTitle($text)213{214$lineLength = strlen($text) + 2;215$this->line(str_repeat("*", $lineLength));216$this->line(" $text ");217$this->line(str_repeat("*", $lineLength));218}219}
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, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.
app/Http/Controllers/IncomingCallController.php
1<?php23namespace App\Http\Controllers;45use App\Http\Requests;6use Twilio\Twiml;78/**9* Class IncomingCallController10*11* @package App\Http\Controllers12*/13class IncomingCallController extends Controller14{1516public function respondToUser()17{18$response = new Twiml();1920$params = array();21$params['action'] = '/call/enqueue';22$params['numDigits'] = 1;23$params['timeout'] = 10;24$params['method'] = "POST";2526$params = $response->gather($params);27$params->say(28'For Programmable SMS, press one. For Voice, press any other key.'29);3031return response($response)->header('Content-Type', 'text/xml');32}33}
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 them with the configured expressions in order to find a corresponding Task Queue, 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.
app/Http/Controllers/EnqueueCallController.php
1<?php23namespace App\Http\Controllers;45use Illuminate\Http\Request;6use Twilio\Twiml;789/**10* Class EnqueueCallController11*12* @package App\Http\Controllers13*/14class EnqueueCallController extends Controller15{1617public function enqueueCall(Request $request)18{19$workflowSid = config('services.twilio')['workflowSid']20or die("WORKFLOW_SID is not set in the system environment");2122$selectProductInstruction = new \StdClass();23$selectProductInstruction->selected_product24= $this->_getSelectedProduct($request);2526$response = new Twiml();27$enqueue = $response->enqueue(['workflowSid' => $workflowSid]);28$enqueue->task(json_encode($selectProductInstruction));2930return response($response)->header('Content-Type', 'text/xml');31}3233/**34* Gets the wanted product upon the user's input35*36* @param $request Request of the user37*38* @return string selected product: "ProgrammableSMS" or "ProgrammableVoice"39*/40private function _getSelectedProduct($request)41{42return $request->input("Digits") == 143? "ProgrammableSMS"44: "ProgrammableVoice";45}46}
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:
reserved
.
POST
request is made to the Workflow's AssignmentCallbackURL, which was configured using the Artisan command
workspace:create
. This request includes the full details of the Task, the selected Worker, and the Reservation.
Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, email, push notifications or make a call.
Since we created this Task during a voice call with an Enqueue
verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to
parameter with a phone number, TaskRouter will pick the Worker's contact_uri
attribute.
We also send a post_work_activity_sid
which will tell TaskRouter which Activity to assign this worker after the call ends.
app/Http/Controllers/CallbackController.php
1<?php23namespace App\Http\Controllers;45use App\Exceptions\TaskRouterException;6use App\MissedCall;7use Illuminate\Http\Request;8use Illuminate\Support\Facades\Log;9use Twilio\Rest\Client;1011/**12* Class CallbackController Handles callbacks13*14* @package App\Http\Controllers15*/16class CallbackController extends Controller17{18/**19* Callback endpoint for Task assignments20*/21public function assignTask()22{23$dequeueInstructionModel = new \stdClass;24$dequeueInstructionModel->instruction = "dequeue";25$dequeueInstructionModel->post_work_activity_sid26= config('services.twilio')['postWorkActivitySid'];2728$dequeueInstructionJson = json_encode($dequeueInstructionModel);2930return response($dequeueInstructionJson)31->header('Content-Type', 'application/json');32}3334/**35* Events callback for missed calls36*37* @param $request Request with the input data38* @param $twilioClient Client of the Twilio Rest Api39*/40public function handleEvent(Request $request, Client $twilioClient)41{42$missedCallEvents = config('services.twilio')['missedCallEvents'];4344$eventTypeName = $request->input("EventType");4546if (in_array($eventTypeName, $missedCallEvents)) {47$taskAttr = $this->parseAttributes("TaskAttributes", $request);48if (!empty($taskAttr)) {49$this->addMissingCall($taskAttr);5051$message = config('services.twilio')["leaveMessage"];52return $this->redirectToVoiceMail(53$twilioClient, $taskAttr->call_sid, $message54);55}56} else if ('worker.activity.update' === $eventTypeName) {57$workerActivityName = $request->input("WorkerActivityName");58if ($workerActivityName === "Offline") {59$workerAttr = $this->parseAttributes("WorkerAttributes", $request);60$this->notifyOfflineStatusToWorker(61$workerAttr->contact_uri, $twilioClient62);63}64}65}6667protected function parseAttributes($name, $request)68{69$attrJson = $request->input($name);70return json_decode($attrJson);71}7273protected function addMissingCall($task)74{75$missedCall = new MissedCall(76[77"selected_product" => $task->selected_product,78"phone_number" => $task->from79]80);81$missedCall->save();82Log::info("New missed call added: $missedCall");83}8485protected function redirectToVoiceMail($twilioClient, $callSid, $message)86{87$missedCallsEmail = config('services.twilio')['missedCallsEmail']88or die("MISSED_CALLS_EMAIL_ADDRESS is not set in the environment");8990$call = $twilioClient->calls->getContext($callSid);91if (!$call) {92throw new TaskRouterException("The specified call does not exist");93}9495$encodedMsg = urlencode($message);96$twimletUrl = "http://twimlets.com/voicemail?Email=$missedCallsEmail" .97"&Message=$encodedMsg";98$call->update(["url" => $twimletUrl, "method" => "POST"]);99}100101protected function notifyOfflineStatusToWorker($workerPhone, $twilioClient)102{103$twilioNumber = config('services.twilio')['number']104or die("TWILIO_NUMBER is not set in the system environment");105106$params = [107"from" => $twilioNumber,108"body" => config('services.twilio')["offlineMessage"]109];110111$twilioClient->account->messages->create(112$workerPhone,113$params114);115}116117}
Now that our Tasks are routed properly, let's deal with missed calls in the next step.
This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout
event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.
Here we use TwilioRestClient to route this call to a Voicemail Twimlet. 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.
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.
app/Http/Controllers/CallbackController.php
1<?php23namespace App\Http\Controllers;45use App\Exceptions\TaskRouterException;6use App\MissedCall;7use Illuminate\Http\Request;8use Illuminate\Support\Facades\Log;9use Twilio\Rest\Client;1011/**12* Class CallbackController Handles callbacks13*14* @package App\Http\Controllers15*/16class CallbackController extends Controller17{18/**19* Callback endpoint for Task assignments20*/21public function assignTask()22{23$dequeueInstructionModel = new \stdClass;24$dequeueInstructionModel->instruction = "dequeue";25$dequeueInstructionModel->post_work_activity_sid26= config('services.twilio')['postWorkActivitySid'];2728$dequeueInstructionJson = json_encode($dequeueInstructionModel);2930return response($dequeueInstructionJson)31->header('Content-Type', 'application/json');32}3334/**35* Events callback for missed calls36*37* @param $request Request with the input data38* @param $twilioClient Client of the Twilio Rest Api39*/40public function handleEvent(Request $request, Client $twilioClient)41{42$missedCallEvents = config('services.twilio')['missedCallEvents'];4344$eventTypeName = $request->input("EventType");4546if (in_array($eventTypeName, $missedCallEvents)) {47$taskAttr = $this->parseAttributes("TaskAttributes", $request);48if (!empty($taskAttr)) {49$this->addMissingCall($taskAttr);5051$message = config('services.twilio')["leaveMessage"];52return $this->redirectToVoiceMail(53$twilioClient, $taskAttr->call_sid, $message54);55}56} else if ('worker.activity.update' === $eventTypeName) {57$workerActivityName = $request->input("WorkerActivityName");58if ($workerActivityName === "Offline") {59$workerAttr = $this->parseAttributes("WorkerAttributes", $request);60$this->notifyOfflineStatusToWorker(61$workerAttr->contact_uri, $twilioClient62);63}64}65}6667protected function parseAttributes($name, $request)68{69$attrJson = $request->input($name);70return json_decode($attrJson);71}7273protected function addMissingCall($task)74{75$missedCall = new MissedCall(76[77"selected_product" => $task->selected_product,78"phone_number" => $task->from79]80);81$missedCall->save();82Log::info("New missed call added: $missedCall");83}8485protected function redirectToVoiceMail($twilioClient, $callSid, $message)86{87$missedCallsEmail = config('services.twilio')['missedCallsEmail']88or die("MISSED_CALLS_EMAIL_ADDRESS is not set in the environment");8990$call = $twilioClient->calls->getContext($callSid);91if (!$call) {92throw new TaskRouterException("The specified call does not exist");93}9495$encodedMsg = urlencode($message);96$twimletUrl = "http://twimlets.com/voicemail?Email=$missedCallsEmail" .97"&Message=$encodedMsg";98$call->update(["url" => $twimletUrl, "method" => "POST"]);99}100101protected function notifyOfflineStatusToWorker($workerPhone, $twilioClient)102{103$twilioNumber = config('services.twilio')['number']104or die("TWILIO_NUMBER is not set in the system environment");105106$params = [107"from" => $twilioNumber,108"body" => config('services.twilio')["offlineMessage"]109];110111$twilioClient->account->messages->create(112$workerPhone,113$params114);115}116117}
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.
app/Http/Controllers/MessageController.php
1<?php23namespace App\Http\Controllers;45use App\Exceptions\TaskRouterException;6use Illuminate\Http\Request;7use App\TaskRouter\WorkspaceFacade;8use Twilio\Twiml;910class MessageController extends Controller11{1213public function handleIncomingMessage(14Request $request, WorkspaceFacade $workspace15) {16$cmd = strtolower($request->input("Body"));17$fromNumber = $request->input("From");18$newWorkerStatus = ($cmd === "off") ? "Offline" : "Idle";1920$response = new Twiml();2122try {23$worker = $this->getWorkerByPhone($fromNumber, $workspace);24$this->updateWorkerStatus($worker, $newWorkerStatus, $workspace);2526$response->sms("Your status has changed to {$newWorkerStatus}");2728} catch (TaskRouterException $e) {29$response->sms($e->getMessage());30}3132return response($response)->header('Content-Type', 'text/xml');33}3435function updateWorkerStatus($worker, $status, $workspace)36{37$wantedActivity = $workspace->findActivityByName($status);38$workspace->updateWorkerActivity($worker, $wantedActivity->sid);39}4041protected function getWorkerByPhone($phone, $workspace)42{43$phoneToWorkerStr = config('services.twilio')['phoneToWorker'];44parse_str($phoneToWorkerStr, $phoneToWorkerArray);45if (empty($phoneToWorkerArray[$phone])) {46throw new TaskRouterException("You are not a valid worker");47}48return $workspace->findWorkerBySid($phoneToWorkerArray[$phone]);49}50}
Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.
If you're a PHP developer working with Twilio, you might also enjoy these tutorials:
Instantly collect structured data from your users with a survey conducted over a call or SMS text messages. Let's get started!
Learn how to implement ETA Notifications using Laravel and Twilio.