Chatitive bots are written in JavaScript and are easy to create. The basic format of a bot is as follows:
var bot = {
keywords: {
start: function(message, subscriber) {
say(”Welcome to our example bot. Reply STOP to unsubscribe”);
},
keyword1: function(message, subscriber) {
// Code to handle keyword1
},
keyword2: function(message, subscriber) {
// Code to handle keyword2
}
keyword3: function(message, subscriber) {
// Code to handle keyword3
}
// Add as many keywords as necessary here
},
aliases: {
"keywordA": "keyword1" // KeywordA will be handled by the handler for keyword1
"keywordB": "keyword1" // KeywordB will also be handled by the handler for keyword1.
},
defaultKeyword: function(message, subscriber) {
// The defaultKeyword handler will be called when no other keyword is matched.
/*
* The return value of `defaultKeyword` has special meaning:
*
* Return `true` to send this user to the support inbox.
* Return `false` to leave that state unchanged.
*/
return true;
}
};
Bots need to finish executing in under 60 seconds, or the bot will be killed. This includes time spent running code as well as making AJAX calls.
Keywords are the entry point to your bot's functionality, and define how your bot interacts with customers.
The following keywords have special meaning. See the compliance documentation for more information:
Keyword | Description |
---|---|
start | A bot may implement start in order to send a custom welcome message to a subscriber.
If this method is not implemented, a default welcome message will be sent. |
stop | Bots can not override the behavior of the stop keyword. If a subscriber sends the stop
keyword, they will be unsubscribed and a message acknowledging this will be sent. You may provide your own message. |
unsubscribe | Bots can not override the behavior of the unsubscribe keyword. If a subscriber sends the
unsubscribe keyword, they will be unsubscribed and a message acknowledging this will be sent.
You may provide your own message. |
help | If a subscriber sends the help keyword, they will be sent a default help message, and marked as needing support. Bots may override this functionality. |
Two objects are passed into all keyword handlers: message
and subscriber
The message object has several properties:
Property name | Description |
---|---|
SID | The message's SID. |
body | The body of the message. |
keyword | The active keyword. |
media[] | Array of urls for media included with the message |
The subscriber object has several properties and methods.
Property name | Description |
---|---|
SID | The subscriber's SID. |
channel | The subscriber's Channel. |
phoneNumber | The subscriber's phone number. |
status | Either "subscribed" or "unsubscribed", depending on whether on not the subscriber is subscribed to the channel or not. |
needsSupport | True if the subscriber has been marked as needing support, otherwise false. |
emailAddress | The subscriber's email address. |
externalUserID | The subscriber's external user ID. |
properties | The subscriber's properties. Properties can be treated like a Hash or Object. For example, a property can be set/updated with subscriber.properties['firstName'] = 'Joe' ,
which is equivalent to subscriber.properties.firstName = 'Joe' .
For simplicity, properties can also be managed with the setProperty
and deleteProperty methods.See the documentation on the Session object for details about storing contextual information across messages. |
Method name | Description |
---|---|
markNeedsSupport() | Marks a subscriber as needing support, unless the subscriber is already marked as needing support, in which case calling this method does nothing. |
resolveNeedsSupport() | Marks a subscriber as no longer needing support. |
subscribe() | Marks a subscriber as subscribed. If the subscriber is already marked as subscribed, calling this method does nothing. |
unsubscribe() | Marks a subscriber as unsubscribed. If the subscriber is already marked as unsubscribed, calling this method does nothing. |
blacklist() | Marks a subscriber as blacklisted. Bot code does not run for blacklisted subscribers. |
getLastCampaign() | Returns the last Campaign that was sent to this subscriber. null is returned if no Campaign was found. |
tags() | Returns all the Tag objects on this subscriber |
addTag(tag) | Adds the specified Tag to the subscriber. |
removeTag(tag) | Removes the specified Tag from the subscriber. |
hasTagByName(tag) | Returns true if the subscriber has the named Tag. |
hasTagBySid(tagSid) | Returns true if the subscriber has a Tag with the specified SID. |
setProperty(propertyName, newValue) | Sets the value of the specified property to newValue. |
deleteProperty(propertyName) | Removes the specified property from the subscriber. |
recordFeedback(feedbackName, feedbackValue) | feedbackName can be any string you like, ie ketchup , and feedbackValue is a signed integer to indicate a direction and intensity of the feedback ie +1 for LIKE, and -1 for DISLIKE. |
The channel object has the following properties and methods:
Property name | Description |
---|---|
SID | The channel's SID. |
name | The channel's name. |
Method name | Description |
---|---|
tags() | Returns all the Tag objects for this channel. |
createTag(name) | Returns a newly created Tag with the given name. |
getOrCreateTag(name) | Loads or creates a Tag with the given name. |
getTagByName(name) | Returns the Tag on this channel with the given name. |
getTagBySid(sid) | Returns the Tag on this channel with the given tag SID. |
getNumSubscribersNeedingSupport() | Returns number of subscribers in the support queue for this channel. |
The campaign object exposes properties and methods for campaigns.
Property name | Description |
---|---|
SID | This campaign's SID |
name | Name for campaign |
status | Status of campaign: One of unscheduled, scheduled, sending or completed |
externalRefID | Account-provided reference identifier for a campaign. |
sendAt | Date and time to initiate campaign messages |
body | Message body for campaign |
media | Collection of media URLs for campaign, if any. |
accountSID | Global identifier for the account associated with this campaign object |
createdAt | Date and time this campaign was created |
updatedAt | Date and time this campaign was last updated |
shortenURLs | Boolean value showing whether we should shorten URLs for campaign messages |
Method name | Description |
---|---|
sendMessage(subscriber, body, media_urls=null, options={ shorten_urls: false, force: false, external_owner_id: null }) | Send a message to the subscriber. The message is associated with this campaign. |
recordLike(message, user_response) | Record a user LIKE response to a bot question, such as "Are you happy with your last order? Please respond with LIKE or DISLIKE..." |
recordDislike(message, user_response) | Record a user DISLIKE response to a bot question, such as "Are you happy with your last order? Please respond with LIKE or DISLIKE..." |
The tag object has the following properties and methods:
Property name | Description |
---|---|
SID | The tag's SID. |
name | The tag's name. |
canonicalName | The tag's canonical name. |
Chatitive uses Google's V8 JavaScript engine to provide standard JavaScript functionality to bots. Besides the standard JavaScript methods, the following additional methods are provided when authoring bots.
Method name | Description | Example |
---|---|---|
say | Sends a message to the subscriber. |
|
get | Performs HTTP GET. The parameters are very much like those used by jQuery get(). |
|
post | Performs HTTP POST. The parameters are very much like those used by jQuery post(). |
|
put | Performs HTTP PUT. The parameters are very much like those used by jQuery put(). |
|
The Session object can be used to track information about a subscriber across messages. It can be used to store information like the last purchase date or maintain information about a conversation the bot is having with a subscriber.
The intended difference between Session and Subscriber properties is that subscriber properties describe attributes about the particular customer (name, preferences, settings in an external system), but Session attributes provide information about a Subscriber's messaging interactions.
The session is exposed through a global session
variable. Consider the
following example where a subscriber's last purchase date is used to generate a
coupon code for a frequent purchaser.
// Invoked when the subscriber makes a purchase
session["lastPurchaseDate"] = new Date().toISOString();
// On a subsequent purchase
if (new Date(session["lastPurchaseDate"]).month === new Date().month) {
say('Thanks for being such a great customer! Next time, respond with GOODCUSTOMER for a 10% discount');
}
Subscriber properties can also be set and retrieved through the Chatitive API. For debugging purposes, you the Session can be accessed like a hash e.g. say(session)
Bot objects (Campaign, Channel, Message, Session, Subscriber and Tag ) are all ES6 classes and can be treated as such for debugging. For example, inside a bot function, you could use:
say(message); // or say(JSON.stringify(message));
to print out a simplified JSON serialization of the message object.
By adding a global function called handleVoiceRequest
, you can control how voice
calls to your transport numbers are handled. The function accepts a context object as a parameter, and
should return TwiML. The context object provides the
caller's phone number, as well as their country, state and city if that data is available.
The context object's fields are named as follows:
Field name | Description |
---|---|
from | Caller's phone number |
from_country | Caller's country if available |
from_state | Caller's state or province caller if available |
from_city | Caller's city if available |
function handleVoiceRequest(context) {
const caller = context.from_city ? ` caller from ${context.from_city}` : '';
return
'<?xml version="1.0" encoding="UTF-8"?>' +
`<Response><Say voice="female">Hello${caller}! Please text us for help</Say><Hangup/></Response>`;
}
To disable voice requests completely, have handleVoiceRequest
return the constant VOICE_REQUEST_REJECT
.
function handleVoiceRequest(context) {
return VOICE_REQUEST_REJECT;
}
If you need to override the default method of extracting keywords, you can provide your
own keyword extractor by implementing a function called extractMessageKeywords
. This
function accepts a string parameter containing the entire body of the received message, and should
return a prioritized array of keywords. The system will first look for a matching workflow automation, trying
each of the returned keywords until a match is found. If no match is found, it will look for a matching
bot keyword handler, iterating through all the returned keywords until a matching handler is found. Should
a keyword handler not be found, the default keyword handler will be called as usual.
Should you wish to use the default keyword extractor for a particular message, your extractor can return an empty array.
NOTE: Your keyword extractor MUST return compliance keywords
(start
, stop
, help
, unsubscribe
)
unmodified, otherwise the system will prevent you from deploying your bot.
function extractMessageKeywords(message) {
// Remove all punctuation, then return all the words in the message in an array
return message.replace(/[,.?!;:]/, '').split(/\s+/);
}