Twilio Data Connector

The Twilio Data Connector allows you to send messages using the Twilio API. It also provides core functionality for interacting with Twilio that is built upon by other Data Connectors.

Constructor

Twilio(sid, authToken) → {object}

We recommend that you create a Data Connector Configuration called "Twilio" via the Verj.io Runtime Environment's Administration Application.

The Data Connector Configuration should include the following properties:

  • sid, your Twilio Account SID.
  • authToken, the Auth Token for your Twilio Account.

A Twilio Data Connector is then available at connectors.verjio.twilio using that configuration.

If you are unable to do that, you may use this constructor to create a new Twilio Data Connector.

This method accepts an Account SID and an Auth Token.

Parameters:
Name Type Description
sid string

Twilio Account SID.

authToken string

Auth Token used to authenticate API requests.

Returns:
object

The Twilio Data Connector.

Members

content.createCallToActionTemplate

Creates a new call to action content template.

Call to action templates include one or more buttons for the user to interact with. Each button triggers an action and is defined in the actions array.

See:
Example:
const actions = [
  {
    type: connectors.verjio.twilio.content.actionType.URL,
    title: 'Order details',
    url: 'https://lunar.example.com/order.eb?id={{1}}',
  },
  {
    type: connectors.verjio.twilio.content.actionType.URL,
    title: 'Store locations',
    url: 'https://lunar.example.com/branches.eb?postcode={{2}}',
  },
  {
    type: connectors.verjio.twilio.content.actionType.PHONE_NUMBER,
    title: 'Discuss your order',
    phone: '+441234567890'
  }
];

const variables = {
  1: 'order_number',
  2: 'post_code'
};

connectors.verjio.twilio.content.createCallToActionTemplate(
  'cta_order_complete',
  'Your Lunar Emporium order (#{{1}}) is now ready for collection.',
  actions,
  variables
);

content.createCardTemplate

Creates a new card content template.

Card templates are made up of a title. Optionally, a subtitle and media can be specified. Cards also include one or more action buttons as defined in the actions array.

See:
Example:
const actions = [
  {
    type: connectors.verjio.twilio.content.actionType.PHONE_NUMBER,
    title: 'Call us to book',
    phone: '+441234567890'
  }
];

connectors.verjio.twilio.content.createCardTemplate(
  'happybirthdayoffer',
  'Happy birthday from Sandy\'s!',
  'Why not celebrate with some free ice cream?',
  actions,
  'https://sandy.verj.cloud/images/birthday-cake.png'
);

content.createCarouselTemplate

Creates a new carousel content template.

Carousel templates display a horizontal, scrolling list of cards. Each card contains text, one or two action buttons and either an image or video. The cards are defined in the cards array.

See:
Example:
const actions = [
  {
    type: connectors.verjio.twilio.content.actionType.URL,
    title: 'Order now',
    url: 'https://sandy.verj.cloud/shop.eb'
  }
];

const cards = [
  {
    title: 'Pumpkin pie',
    body: 'Cinnamon spiced pumpkin goodness.',
    media: 'https://sandy.verj.cloud/images/pumpkin-pie.jpg',
    actions: actions
  },
  {
    title: 'Toffee apple',
    body: 'Sweet, rich toffee with candied apple pieces.',
    media: 'https://sandy.verj.cloud/images/toffee-apple.jpg',
    actions: actions
  }
];

const sid = connectors.verjio.twilio.content.createCarouselTemplate(
  'autumn_flavours',
  'Check our our new ice cream flavours for autumn!',
  cards
);

content.createListPickerTemplate

Creates a new list picker content template.

List picker templates contain a menu of up to 10 list items that a user can select from to trigger an action.

See:
Examples:
// Populate list from a Table
const services = [];

const rows = tables.services.fetchTable();
while (rows.next()) {
  services.push({
    id: `service-${tables.services.service_id.value.toLowerCase()}`,
    item: tables.services.name.value,
    description: tables.services.description.value
  });
}

connectors.verjio.twilio.content.createListPickerTemplate(
  'service_picker',
  'Thank you for contacting the Lunar Emporium. How can we help?',
  'Select a service',
  services,
);
// Populate list from an array of values
const items = ['Cod', 'Haddock', 'Pollock', 'Plaice'].map(fish => ({
  id: `product-${fish.toLowerCase()}`,
  item: fish,
}));

connectors.verjio.twilio.content.createListPickerTemplate(
  'fish_picker',
  'Thank you for ordering fish and chips with Salty\'s. What fish would you like to eat?',
  'Pick your fish',
  items,
);

content.createLocationTemplate

Creates a new location content template.

Location templates contain a location pin and an optional label.

See:
Example:
connectors.verjio.twilio.content.createLocationTemplate(
  'big_ben_location',
  51.510357,
  -0.116773,
  'Big Ben'
);

content.createMediaTemplate

Creates a new media content template.

Media templates are made up of a textual message and a media file, defined as a URL.

The media URL can make use of variables but only after the domain, e.g. https://example.com/img/{{1}}.

See:
Example:
connectors.verjio.twilio.content.createMediaTemplate(
  'testimonial_with_logo', 
  'Hi {{1}}, as requested, here are some testimonials about our business: {{2}}', 
  'https://sandy.verj.cloud/clients/{{3}}',
  {
    1: 'first_name',
    2: 'testimonial'
    3: 'client_logo'
  }
);

content.createQuickReplyTemplate

Creates a new quick reply content template.

Quick reply templates let the user tap an action button, rather than type, to respond to a message.

See:
Example:
const actions = [
  {
    type: connectors.verjio.twilio.content.actionType.QUICK_REPLY,
    title: 'Book a table',
    id: 'book_table',
  },
  {
    type: connectors.verjio.twilio.content.actionType.QUICK_REPLY,
    title: 'Change reservation',
    id: 'change_reservation',
  }
];

connectors.verjio.twilio.content.createQuickReplyTemplate(
  'table_booking_quick_reply',
  'Hi, {{1}}. Thank you for contacting us. How can we help?',
  actions,
  { 1: 'first_name' }
);

content.createTemplate

Create a new content template. The template, including its type(s), is defined using the params object.

This method is used internally by the createXTemplate methods, for example content.createMediaTemplate.

content.createTextTemplate

Creates a new text content template.

Text templates are the simplest templates and contain only a textual message.

See:
Examples:
const sid = connectors.verjio.twilio.content.createTextTemplate(
  'simpleorderconfirmation',
  'Your order {{1}} has been received.',
  { 1: 'order_number' }
);
fields.content_sid.value = sid;
// Specify a template in another language
connectors.verjio.twilio.content.createTextTemplate(
  'germanorderconfirmation',
  'Ihre Bestellung {{1}} ist eingegangen.',
  { 1: 'order_number' },
  'de'
);

content.deleteTemplate

Delete a specified content template.

Example:
if (connectors.verjio.twilio.content.deleteTemplate(fields.content_sid.value)) {
  event.owner.addInfoMessage('Template deleted successfully.');
}

content.getAllTemplates

Retrieve all existing content templates.

Example:
try {
  const templates = connectors.verjio.twilio.content.getAllTemplates();
  if (templates) {
    event.owner.addInfoMessage(`Fetched ${templates.length} templates.`);
  }
}
catch (e) {
  event.owner.addErrorMessage(`Error when attempting to fetch templates: ${e.message}`);
}

content.getTemplate

Retrieve a specified content template.

Example:
const template = connectors.verjio.twilio.content.getTemplate(fields.content_sid.value);

content.getTemplateApprovalStatus

Retrieve approval status for a specified content template.

Example:
const content = connectors.verjio.twilio.content.getTemplateApprovalStatus(fields.content_sid.value);
if (content) {
  event.owner.addInfoMessage(`WhatsApp approval status: ${content.whatsapp.status}`);
}

content.searchTemplates

Retrieve existing content templates that match specified searches.

See:
Examples:
// Search for all templates that include the phrase 'birthday'
const templates = connectors.verjio.twilio.content.searchTemplates('birthday');
event.owner.addInfoMessage(`Found ${templates.length} matching templates.`);
// Search for all templates created before a timestamp
const start = new Date('October 2, 2024 09:30:00').toISOString();
connectors.verjio.twilio.content.searchTemplates(null, { DateCreatedBefore: start });

content.submitTemplateForApproval

Submit an existing content template for approval for a specified messaging service.

Example:
// Fetch a content template and submit it for approval
const template = connectors.verjio.twilio.content.getTemplate(fields.content_sid.value);
connectors.verjio.twilio.content.submitTemplateForApproval(
  template.sid,
  template.friendly_name,
  connectors.verjio.twilio.messagingService.WHATSAPP,
  { category: connectors.verjio.twilio.content.whatsAppCategory.UTILITY }
);

helpers.validateTemplateName

Validates a content template name..

helpers.validateTwilioId

Validates a Twilio ID. Each ID type has its own two-letter prefix. Note that this is just an indication of whether the ID is in the correct format and does not attempt to determine whether the ID is in use.

Example:
// Validate a Twilio Account SID
if (connectors.twilio.helpers.validateTwilioId(accountSid, 'AC')) {
	log('Account SID is valid!');
}

helpers

A collection of helper methods for formatting and querying API data.

Example:
connectors.verjio.twilio.helpers.formatPhoneNumber('5555551234', '1');

Functions

helpers.formatPhoneNumber(phone, countryopt) → (nullable) {string}

Format a phone number to E.164.

Note that the trailing 0 is not removed as this is an optional step.

Parameters:
Name Type Attributes Default Description
phone string    

The phone number to format.

country string <optional> 44

Country calling code, without the preceding +.

Returns:
string

The formatted phone number, or null if the phone was badly formatted.

Example:
var formatted = connectors.verjio.twilio.helpers.formatPhoneNumber('01223510928');
log(formatted); // '+4401223510928'

helpers.validatePhoneNumber(phone) → {boolean}

Determines if a phone number is formatted as per E.164.

Parameters:
Name Type Description
phone string

The phone number to validate.

Returns:
boolean

Returns true if the phone number is valid E.164 or false otherwise.

getAccountDetails() → (nullable) {object}

Retrieve information about the Twilio account. The account is determined by the sid provided to this connector.

See:
Returns:
object

Details of the Twilio account, or null if one was not found.

getPhoneNumber(capabilitiesopt) → (nullable) {object}

Retrieve a phone number that can be used by this Twilio account. If multiple phone numbers are availale, the first is selected.

The phone numbers can be filtered by specifying a capabilities object.

Parameters:
Name Type Attributes Description
capabilities Twilio.PhoneNumberCapabilities <optional>

Optional filter for phone number capabilities.

See:
Returns:
object

Details of the phone number or null, if none were found.

Example:
// Find a phone number that can send SMS and MMS messages
var phone = connectors.verjio.twilio.getPhoneNumber({ sms: true, mms: true });

// Send an SMS using the phone number
connectors.verjio.twilio.sendSms(
	connectors.verjio.twilio.helpers.formatPhoneNumber(tables.customer.mobile.value),
	'Please visit our feedback questionairre at https://example.com/cq123', 
	phone.phone_number
);

getPhoneNumbers() → (nullable) {Array.<object>}

Retrieve all phone numbers that can be used by this Twilio account.

See:
Returns:
Array.<object>

Array of phone number details, represented as objects. Return an empty array if there are no phone numbers available. Returns null if the account SID was not provided.

Example:
var phoneNumbers = connectors.verjio.twilio.getPhoneNumbers();
phoneNumbers.forEach(phoneNumber => {
	tables.phoneNumbers.insertRow();
	tables.phoneNumbers.id.value = phoneNumber.sid;
	tables.phoneNumbers.phoneNumber.value = phoneNumber.phone_number;
});

handleError(response)

Checks an API response for errors. If an error is encountered, the appropriate Error is thrown.

Parameters:
Name Type Description
response object

The response from a services.rest request

Throws:
  • HttpAuthorisationError

    Thrown when an incorrect SID or token are used.

  • HttpNotFoundError

    Thrown when the requested resource is not available.

  • HttpRequestError

    Thrown when a request is malformed or required parameters are not supplied. See the error message for more details.

  • HttpUnknownError

    Thrown when an unhandled error is encountered.

Type definitions

CardItem

Used by content.createCarouselTemplate to define card items that form part of a carousel content template.

Note that the order of action types must be the same for all cards in a content template.

Properties:
Name Type Description
id string

Unique identifier for the item. Not visible to user. Maximum of 200 characters.

title string

Header text for the card. Maximum combined length of title and body is 160 characters.

body string

Body text for the card. Maximum combined length of title and body is 160 characters.

media string

URL of media to appear on card. Only images and videos are supported.

actions Array.<Twilio.TemplateAction>

Array of actions that a user can take in response to the card. A card can have a maximum of 2 actions.

ListItem

Used by content.createListPickerTemplate to define selectable list items that form part of a list picker content template.

Properties:
Name Type Attributes Description
id string  

Unique identifier for the item. Not visible to user. Maximum of 200 characters.

item string  

Friendly name for the list item. Maximum of 24 characters.

description string <optional>

Optional description of the item.

Example:
var listItem = {
  id: 'freegift1',
  item: 'Astronaut Cuddly Toy',
  description: 'An plushy toy representing a famous astronaut or cosmonaut.'
};

MessagingService

Constants used to identify messaging services.

These can be accessed via connectors.verjio.twilio.messagingService.

PhoneNumberCapabilities

Used by getPhoneNumber to filter available phone numbers on their capabilities.

Properties:
Name Type Attributes Description
sms boolean <nullable>

SMS ("text") messages.

mms boolean <nullable>

Multimedia messages.

voice boolean <nullable>

Send and receive voice calls.

TemplateAction

Used by content.createTemplate to define actions (clickable buttons) that a user can take in response to a message.

Actions are required for twilio/quick-reply, twilio/call-to-action and twilio/card content types.

Properties:
Name Type Attributes Description
id string <optional>

Unique identifier for the action. Not visible to user.

title string  

Friendly title for action button.

type Twilio.TemplateActionType  

Type of action.

url string <optional>

URL to open. Only applicable for URL actions.

phone string <optional>

Phone number to dial. Only applicable for PHONE_NUMBER actions.

code string <optional>

Code to copy. Only applicable for COPY_CODE actions.

Example:
var action = {
  id: 'postagetracking',
  title: 'Track order',
  type: connectors.verjio.twilio.content.actionType.URL,
  url: 'https://example.com/track/{{1}}'
};

TemplateActionType

Constants used to identify action types.

These can be accessed via connectors.verjio.twilio.content.actionType.

TwilioSentStatus

Constants used to identify sending status.

These can be accessed via connectors.verjio.twilio.sentStatus.

Properties:
Name Type Description
ACCEPTED string

The message has been accepted via the Twilio Messaging Service.

SCHEDULED string

The message is scheduled for later delivery.

SENDING string

The message is in the process of being sent.

SENT string

The message has been sent.

QUEUED string

The message is queued for sending but has not been sent yet.