Want to learn how to use TaskRouter.js Worker to route tasks to a web-based application? Dive into the TaskRouter Quickstart.
TaskRouter's JavaScript SDK makes it easy to build web-based applications for the people that will process TaskRouter Tasks. The SDK allows developers to:
Register an endpoint as a TaskRouter Worker.
Manage the registered Worker's Activity state.
Receive assigned Task & Reservation details.
Accept & Reject Reservations.
Call a given Worker with a Dequeue or Call instruction
Complete Tasks
The TaskRouter JavaScript SDK makes a WebSocket connection to TaskRouter. TaskRouter events and commands, such as Task Assignment and Acceptance, or Activity changes, are communicated via this Websocket connection.
Include the TaskRouter JS SDK in your JavaScript application as follows:
<script src="https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>
TaskRouter uses Twilio capability tokens to delegate scoped access to TaskRouter resources to your JavaScript application. Twilio capability tokens conform to the JSON Web Token (commonly referred to as a JWT and pronounced "jot") standard, which allow for limited-time use of credentials by a third party. Your web server needs to generate a Twilio capability token and provide it to your JavaScript application in order to register a TaskRouter worker.
There are two capabilities you can enable today (and in most cases you'll want to use all of them in your application):
Capability | Authorization |
---|---|
ActivityUpdates | A worker can update its current Activity. |
ReservationUpdates | A worker can accept or reject a reservation as well as provide a dequeue or call instruction. |
You can generate a TaskRouter capability token using any of Twilio's Helper Libraries. You'll need to provide your Twilio AccountSid and AuthToken, along with the WorkspaceSid and WorkerSid for the Worker you would like to register. For example, using our PHP helper library you can create a token and add capabilities as follows:
1// Download the Node helper library from twilio.com/docs/node/install2// These consts are your accountSid and authToken from https://www.twilio.com/console3const taskrouter = require('twilio').jwt.taskrouter;4const util = taskrouter.util;56const TaskRouterCapability = taskrouter.TaskRouterCapability;7const Policy = TaskRouterCapability.Policy;89// To set up environmental variables, see http://twil.io/secure10const accountSid = process.env.TWILIO_ACCOUNT_SID;11const authToken = process.env.TWILIO_AUTH_TOKEN;12const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';13const workerSid = 'WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';1415const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';16const version = 'v1';1718const capability = new TaskRouterCapability({19accountSid: accountSid,20authToken: authToken,21workspaceSid: workspaceSid,22channelId: workerSid});2324// Helper function to create Policy25function buildWorkspacePolicy(options) {26options = options || {};27var resources = options.resources || [];28var urlComponents = [TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid]2930return new Policy({31url: urlComponents.concat(resources).join('/'),32method: options.method || 'GET',33allow: true34});35}3637// Event Bridge Policies38const eventBridgePolicies = util.defaultEventBridgePolicies(accountSid, workerSid);3940// Worker Policies41const workerPolicies = util.defaultWorkerPolicies(version, workspaceSid, workerSid);4243const workspacePolicies = [44// Workspace fetch Policy45buildWorkspacePolicy(),46// Workspace subresources fetch Policy47buildWorkspacePolicy({ resources: ['**'] }),48// Workspace Activities Update Policy49buildWorkspacePolicy({ resources: ['Activities'], method: 'POST' }),50// Workspace Activities Worker Reserations Policy51buildWorkspacePolicy({ resources: ['Workers', workerSid, 'Reservations', '**'], method: 'POST' }),52];5354eventBridgePolicies.concat(workerPolicies).concat(workspacePolicies).forEach(function (policy) {55capability.addPolicy(policy);56});5758const token = capability.toJwt();
Additionally, you can to define more granular access to particular resources beyond these capabilities. These can be viewed under Constructing JWTs.
Once you have generated a TaskRouter capability token, you can pass this to your front-end web application and initialize the JavaScript library as follows:
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
The library will raise a 'ready' event once it has connected to TaskRouter:
1worker.on("ready", function(worker) {2console.log(worker.sid) // 'WKxxx'3console.log(worker.friendlyName) // 'Worker 1'4console.log(worker.activityName) // 'Reserved'5console.log(worker.available) // false6});
See more about the methods and events exposed on this object below.
TaskRouter.js Worker exposes the following API:
Twilio.TaskRouter.Worker is the top-level class you'll use for managing a Worker's activity, and receiving notifications when a Worker is assigned a task or when a Worker's Activity is changed.
Register a new Twilio.TaskRouter.Worker with the capabilities provided in workerToken
.
Name | Type | Description |
---|---|---|
workerToken | String | A Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information. |
debug | Boolean | (optional) Whether or not the JS SDK will print event messages to the console. Defaults to true. |
connectActivitySid | String | (optional) ActivitySid to place the worker in upon the WebSocket Connecting |
disconnectActivitySid | String | (optional) ActivitySid to place the worker in upon the Websocket Disconnecting |
closeExistingSessions | Boolean | (optional) Whether or not to disconnect existing websockets for the same Worker upon Connecting. Defaults to false. |
region | String | (optional) A Twilio region for websocket connections (ex. ie1-ix ). |
maxRetries | Integer | (optional) The maximum of retries to attempt if a websocket request fails. Defaults to 0. |
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
Turning off debugging:
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN, false);
Adding Connecting and Disconnecting Activities, and closing Existing Sessions
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN, false, "WAxxx", "WAyyy", true);
Updates properties of a Worker. There are properties of a Worker, such as ActiveSid, FriendlyName, etc. These can be edited singly (see below) or in bulk. If you wish to change the Attributes property of a Worker, you must pass in the full JSON blob of its new Attributes.
To update the activity or reservation of a specific worker, please refer to the Worker Resource.
Note:
Updating the activity or reservation If updating the Worker's activity state, the activity.update
event will also fire.
If updating the Worker's attributes, the attributes.update
event will also fire.
Name | Type | Description |
---|---|---|
args... | String or JSON | A single API parameter and value or a JSON object containing multiple values |
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of the update. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Worker object. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.update("ActivitySid", "WAxxx", function(error, worker) {4if(error) {5console.log(error.code);6console.log(error.message);7} else {8console.log(worker.activityName); // "Offline"9}10});
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23const props = {"ActivitySid":"WAxxx", "FriendlyName":"UpdatedWorker"};45worker.update(props, function(error, worker) {6if(error) {7console.log(error.code);8console.log(error.message);9} else {10console.log(worker.activityName); // "Offline"11}12});
Updates the TaskRouter capability token for the Worker.
Name | Type | Description |
---|---|---|
workerToken | String | A valid TaskRouter capability token. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23const token = refreshJWT(); // your method to retrieve a new capability token4worker.updateToken(token);
Retrieves the list of Activities configured in your TaskRouter's Workspace.
Name | Type | Description |
---|---|---|
callback | Function | A function that will be called when the Activity list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Activities |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.activities.fetch(4function(error, activityList) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10const data = activityList.data;11for(i=0; i<data.length; i++) {12console.log(data[i].friendlyName);13}14}15);
Retrieves the list of Reservations assigned to your Worker
Name | Type | Description |
---|---|---|
callback | Function | A function that will be called when the Reservation list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Reservations |
params | Object | (optional) A JSON object of query parameters |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.fetchReservations(4function(error, reservations) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10const data = reservations.data;11for(i=0; i<data.length; i++) {12console.log(data[i].sid);13}14}15);
The following will fetch just pending reservations:
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23const queryParams = {"ReservationStatus":"pending"};45worker.fetchReservations(6function(error, reservations) {7if(error) {8console.log(error.code);9console.log(error.message);10return;11}12const data = reservations.data;13for(i=0; i<data.length; i++) {14console.log(data[i].sid);15}16},17queryParams18);
Retrieves the list of Channels assigned to your Worker
Note: To utilize this, when constructing your Worker JWT, allow your worker to fetch subresources of the given Worker.
Name | Type | Description |
---|---|---|
callback | Function | A function that will be called when the Worker Channel list is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain an Array of Channels |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.fetchChannels(4function(error, channels) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10const data = channels.data;11for(i=0; i<data.length; i++) {12console.log(data[i].taskChannelUniqueName + " with capacity: " + data[i].configuredCapacity);13}14}15);
Updates a given Task with the given parameters
Name | Type | Description |
---|---|---|
taskSid | String | The given TaskSid |
params | JSON | JSON object containing multiple values |
callback | Function | A function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23const params = {"Priority":"15"};4worker.updateTask(taskSid, params,5function(error, updatedTask) {6if(error) {7console.log(error.code);8console.log(error.message);9return;10}11console.log("Updated Task Priority: "+updatedTask.priority);12}13);
Completes a given Task with an optional reason
Name | Type | Description |
---|---|---|
taskSid | String | The given TaskSid |
callback | Function | A function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance. |
reason | String | (optional) The reason for completion |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.completeTask(taskSid,4function(error, completedTask) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10console.log("Completed Task: "+completedTask.assignmentStatus);11}12);
If you have the context of given Reservation, you can complete Task from the Task object itself:
Name | Type | Description |
---|---|---|
callback | Function | (optional) A function that will be called when the updated instance is returned. If an error occurs when updating the instance, the first parameter passed to this function will contain the Error object. If the update is successful, the first parameter will be null and the second parameter will contain the updated instance. |
reason | String | (optional) The reason for completion |
reservation.task.complete();
With the optional callback, this would look like the following:
1reservation.task.complete(2function(error, completedTask) {3if(error) {4console.log(error.code);5console.log(error.message);6return;7}8console.log("Completed Task: "+completedTask.assignmentStatus);9}10);
Attaches a listener to the specified event. See Events for the complete list of supported events.
Name | Type | Description |
---|---|---|
event | String | An event name. See Events for the complete list of supported events. |
callback | Function | A function that will be called when the specified Event is raised. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("activity.update", function(worker) {4console.log(worker.activityName) // 'Reserved'5console.log(worker.activitySid) // 'WAxxx'6console.log(worker.available) // false7});
TaskRouter's JS library currently raises the following events to the registered Worker object:
The Worker has established a connection to TaskRouter and has completed initialization.
Name | Type | Description |
---|---|---|
worker | Worker | The Worker object for the Worker you've created. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("ready", function(worker) {4console.log(worker.available) // true5});
The Worker's activity has changed. This event is fired any time the Worker's Activity changes, both when TaskRouter updates a Worker's Activity, and when you make a change to the Worker's Activity via Worker.js or the TaskRouter REST API.
Name | Type | Description |
---|---|---|
worker | Worker | The updated Worker object |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("activity.update", function(worker) {4console.log(worker.sid) // 'WKxxx'5console.log(worker.friendlyName) // 'Worker 1'6console.log(worker.activityName) // 'Reserved'7console.log(worker.available) // false8});
The Worker's attributes have been updated.
Name | Type | Description |
---|---|---|
worker | Worker | The updated Worker object |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("attributes.update", function(worker) {4console.log(worker.sid) // 'WKxxx'5console.log(worker.friendlyName) // 'Worker 1'6console.log(worker.activityName) // 'Reserved'7console.log(worker.available) // false8});
The Worker's Capacity have been updated.
Name | Type | Description |
---|---|---|
channel | WorkerChannel | The updated WorkerChannel object |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("capacity.update", function(channel) {4console.log(channel.sid) // 'WCxxx'5console.log(channel.taskChannelUniqueName) // 'ipm'6console.log(channel.available) // true7console.log(channel.configuredCapacity) // '3'8console.log(channel.availableCapacityPercentage) // 66.79console.log(channel.assignedTasks) // 210});
The Worker has been assigned a reservation.
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been assigned to the Worker. |
Access Task and their attributes details as you would with any other JavaScript object.
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.created", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when the Worker has accepted a Reservation.
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been accepted for this worker. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.accepted", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when the Worker has rejected a Reservation
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been rejected for this worker. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.rejected", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when a pending Reservation associated with this Worker times out.
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been timed-out for this worker. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.timeout", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when a pending Reservation associated with this Worker is canceled.
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been canceled for this worker. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.canceled", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when a pending Reservation associated with this Worker is rescinded in the case of multi-reservation.
Name | Type | Description |
---|---|---|
reservation | Reservation | The Reservation object that has been rescinded for this worker. |
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("reservation.rescinded", function(reservation) {4console.log(reservation.task.attributes) // {foo: 'bar', baz: 'bang' }5console.log(reservation.task.priority) // 16console.log(reservation.task.age) // 3007console.log(reservation.task.sid) // WTxxx8console.log(reservation.sid) // WRxxx9});
Raised when the TaskRouter capability token used to create this Worker expires.
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("token.expired", function() {4console.log("updating token");5const token = refreshJWT(); // your method to retrieve a new capability token6worker.updateToken(token);7});
Raised when the Websocket connects.
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("connected", function() {4console.log("Websocket has connected");5});
Raised when the Websocket disconnects.
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("disconnected", function() {4console.log("Websocket has disconnected");5});
Raised when the Websocket has an error.
1const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);23worker.on("error", function(error) {4console.log("Websocket had an error: "+ error.response + " with message: "+error.message);5});
When a Worker receives a reservation.created
event with a Reservation object, the reservation object contains several
actionable methods on the reservation.
This will accept the reservation for the worker.
Note: This will NOT perform any telephony. If the task was enqueued using the Enqueue TwiML verb, utilize reservation.dequeue(#reservation-dequeue) to perform telephony and dequeue the call.
Name | Type | Description |
---|---|---|
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of accepting the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object. |
1reservation.accept(2function(error, reservation) {3if(error) {4console.log(error.code);5console.log(error.message);6return;7}8console.log("reservation accepted");9for (const property in reservation) {10console.log(property+" : "+reservation[property]);11}12}13);
If you do not care about the callback, then simply the following will do:
reservation.accept();
This will reject the reservation for the worker.
Name | Type | Description |
---|---|---|
activitySid | String | (optional) The activitySid to update the worker to after rejecting the reservation |
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of rejecting the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object. |
1reservation.reject(2function(error, reservation) {3if(error) {4console.log(error.code);5console.log(error.message);6return;7}8console.log("reservation rejected");9for (const property in reservation) {10console.log(property+" : "+reservation[property]);11}12}13);
If you do not care about the callback, then simply the following will do:
reservation.reject();
If you do not care about the callback, but want to update the worker's ActivitySid then simply the following will do:
reservation.reject("WAxxx");
This will create a conference and puts worker and caller into conference.
Note: This will create a conference for a task that was enqueued using the Enqueue TwiML verb.
Name | Type | Description | |
---|---|---|---|
from | String | (optional) The caller id for the call to the worker. This needs to be a verified Twilio number. If you need this to be the original callee number, please contact Support. If the "from" is not provided and the Task was created using Enqueue verb, then we will use the "To" number dialed by the caller as the "from" number when executing "conference" instruction. | |
postWorkActivitySid | String | (optional) The activitySid to update the worker to after conference completes. | |
timeout | string | (optional) The integer number of seconds that Twilio should allow the phone associated with contact_uri to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail. | |
to | string | (optional) The contact URI of the Worker. A phone number or client ID. Required if the worker's attributes do not include a contact_uri property. | |
resultCallback | Function | (optional) A JavaScript Function that will be called upon the completion of the dial. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below. | |
options | object | (optional) If you have Agent Conference enabled, you can utilize similar parameters as specified by the Participants API for the Worker Conference Leg. See the documentation for the full list of parameters that can be used. You can enable Agent Conference via the Twilio Console | |
options.ConferenceStatusCallbackEvent | String[] | (optional) Ensure that, for the TaskRouter SDK, this parameter is a comma separated array. Refer to the documentation for the full list of values that can be included in the array. |
If you simply wish to conference the call, then simply do the following since all parameters are optional:
reservation.conference();
If you wish to hook into additional options, you can do so as follows:
1reservation.conference(2"18004746453",3"WAxxx",4"30",5"client:joey",6function(error, reservation) {7if(error) {8console.log(error.code);9console.log(error.message);10return;11}12console.log("conference initiated");13}14);
If you wish to hook into Agent Conference parameters for the Worker Conference Leg, you can do so as follows:
1const options = {2"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",3"ConferenceStatusCallbackEvent": "start,end",4"ConferenceRecord": "true",5"ConferenceRecordingStatusCallback": "https://requestb.in/wzfljiwz",6"EndConferenceOnExit": "true"7}89reservation.conference(null, null, null, null, null, options);
If you wish to NOT utilize Agent Conference or its parameters for the Worker Conference Leg, but control your conference settings via the options parameter, that is possible as well:
1const options = {2"From": "18004746453",3"PostWorkActivitySid": "WAxxx",4"Timeout": "30",5"To": "client:joey",6"Record":"true",7"ConferenceStatusCallback": "https://requestb.in/wzfljiwz",8"ConferenceStatusCallbackEvent": "start,end,join,leave"9}1011reservation.conference(null, null, null, null, null, options);
This will dequeue the reservation for the worker.
Note: This will perform telephony to dequeue a task that was enqueued using the Enqueue TwiML verb.
Note: A Worker's Attributes must contain a contact_uri
attribute for the call to go through since this will be considered the To
for the Calls API.
Name | Type | Description |
---|---|---|
dequeueFrom | String | (optional) The caller id for the call to the worker. This needs to be a verified Twilio number. If you need this to be the original callee number, please contact Support. If the "dequeueFrom" is not provided and the Task was created using Enqueue verb, then we will use the "To" number dialed by the caller as the "dequeueFrom" number when executing "dequeue" instruction. |
dequeuePostWorkActivitySid | String | (optional) The activitySid to update the worker to after dequeuing the reservation |
dequeueRecord | string | (optional) The 'record' attribute lets you record both legs of a call. Set to "record-from-answer" to record the call from answer. Default to "do-not-record" which will not record the call. The RecordingUrl will be sent with status_callback_url. |
dequeueTimeout | string | (optional) The integer number of seconds that Twilio should allow the phone associated with contact_uri to ring before assuming there is no answer. Default is 60 seconds, the maximum is 999 seconds. Note, you could set this to a low value, such as 15, to hangup before reaching an answering machine or voicemail. |
dequeueStatusCallbackUrl | string | (optional) A URL that Twilio will send asynchronous webhook requests to on completed call event. **Note: TaskRouter sends "taskCallSid" as parameter with sid of the call that created the Task. This is very useful in the event a call to worker fails, where you could remove the original call from queue and send to voice mail or enqueue again with new workflow to route to different group of workers. |
dequeueStatusCallbackEvents | string | (optional) Defines which Call Progress Events are sent to the above dequeueStatusCallbackUrl. By default, we will send only the call completed event. If you wish to listen to all, simply provide "initiated,ringing,answered,completed". Any permutation of the above as long as it is comma delimited is acceptable. |
dequeueTo | string | (optional) The contact URI of the Worker. A phone number or client ID. Required if the worker's attributes do not include a contact_uri property. |
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of dequeuing the reservation. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated Reservation object. |
If you simply wish to dequeue the call, then simply the following will do since all parameters are optional:
reservation.dequeue();
If you wish to hook into additional options, you can do so as follows:
1reservation.dequeue(2"18004746453",3"WAxxx",4"record-from-answer",5"30",6"http://requestb.in/13285vq1",7"client:joey",8function(error, reservation) {9if(error) {10console.log(error.code);11console.log(error.message);12return;13}14console.log("reservation dequeued");15}16);
This will call a worker using the Twilio Calls API. To give a sense of the matchup of parameters, an additional column is listed on the parameters to indicate which Calls API parameter each JS SDK parameter is mapping to.
Note: If CallTo is not provided, a Worker's Attributes must contain a contact_uri
attribute for the call to go through since this will be considered the To
for the Calls API.
Name | Type | Description | Calls API Parameter |
---|---|---|---|
callFrom | String | The caller id for the call to the worker | From |
callUrl | String | A valid TwiML URI that is executed on the answering Worker's leg. | Url |
callStatusCallbackUrl | String | (optional) A valid status callback URL. | StatusCallback |
callAccept | String | (optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true | |
callRecord | String | (optional) record-from-answer or false. Record the call. Defaults to false. | Record |
callTo | String | (optional) Whom to call. If not provided, will utilize worker contact_uri attribute | To |
resultCallback | Function | (optional) A JavaScript Function that will be called upon the completion of the dial. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below. |
1reservation.call(2"18004746453",3"http://twimlbin.com/451369ae",4"http://requestb.in/13285vq1",5"true",6"record-from-answer",7"client:joey"8function(error, reservation) {9if(error) {10console.log(error.code);11console.log(error.message);12return;13}14console.log("reservation called the worker");15}16);
If you do not care about the callback, then simply the following will do:
1reservation.call(2"18004746453",3"http://twimlbin.com/451369ae",4"http://requestb.in/13285vq1",5"false");
If you do not care about the status callback, and want to accept the reservation AFTER the call is bridged, you can do the following:
1reservation.call(2"18004746453",3"http://twimlbin.com/451369ae",4null,5null,6null,7null,8function(error, reservation) {9if(error) {10console.log(error.code);11console.log(error.message);12return;13}14reservation.accept();15}16);
If you do not care about the callback, or the status callback, and want to accept the reservation BEFORE the call is bridged, you can do the following:
1reservation.call(2"18004746453",3"http://twimlbin.com/451369ae",4null,5"true");
This will redirect the active call tied to a reservation using the Twilio Calls API. To give a sense of the matchup of parameters, an additional column is listed on the parameters to indicate which Calls API parameter each JS SDK parameter is mapping to.
Name | Type | Description | Calls API Parameter |
---|---|---|---|
redirectCallSid | String | The Call to Redirect | From |
redirectUrl | String | A valid TwiML URI that is executed on the Caller's leg upon redirecting. | Url |
redirectAccept | String | (optional) "true" or "false", accept the task before initiating call. Defaults to "false". Needs to be a string. Eg: "true", not true | |
resultCallback | Function | (optional) A JavaScript Function that will be called upon the completion of the redirect. If an error occurs, the first argument passed to this function will be an Error. If the call is successful, the first argument will be null and the second argument will contain the non-updated Reservation object. However, you can still utilize actions on it. See below. |
1reservation.redirect(2"CAxxxx", //redirectCallSid3"https://handler.twilio.com/twiml/EH621f0e21da7ce5441f6ec6aacce64069", //redirectUrl4"true", //redirectAccept5function(error, reservation) { //resultCallback6if(error) {7console.log(error.code);8console.log(error.message);9return;10}11console.log("reservation call was redirected");12}13);
Note: The URL used in the example above is created using TwiML Bins which returns the following TwiML that plays "Hello from TwiML".
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Say>Hello from Twilio!</Say>4</Response>