Bot Documentation

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;
  }
};

Note about execution time

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

Keywords are the entry point to your bot's functionality, and define how your bot interacts with customers.

Reserved keywords

The following keywords have special meaning. See the compliance documentation for more information:

KeywordDescription
startA 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.
stopBots 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.
unsubscribeBots 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.
helpIf 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

Message object

The message object has several properties:

Property nameDescription
SIDThe message's SID.
bodyThe body of the message.
keywordThe active keyword.
media[]Array of urls for media included with the message

Subscriber object

The subscriber object has several properties and methods.

Properties

Property nameDescription
SIDThe subscriber's SID.
channelThe subscriber's Channel.
phoneNumberThe subscriber's phone number.
statusEither "subscribed" or "unsubscribed", depending on whether on not the subscriber is subscribed to the channel or not.
needsSupportTrue if the subscriber has been marked as needing support, otherwise false.
emailAddressThe subscriber's email address.
externalUserIDThe subscriber's external user ID.
propertiesThe 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.

Methods

Method nameDescription
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.

Channel object

The channel object has the following properties and methods:

Properties

Property nameDescription
SIDThe channel's SID.
nameThe channel's name.

Methods

Method nameDescription
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.

Campaign object

The campaign object exposes properties and methods for campaigns.

Properties

Property nameDescription
SIDThis campaign's SID
nameName for campaign
statusStatus of campaign: One of unscheduled, scheduled, sending or completed
externalRefIDAccount-provided reference identifier for a campaign.
sendAtDate and time to initiate campaign messages
bodyMessage body for campaign
mediaCollection of media URLs for campaign, if any.
accountSIDGlobal identifier for the account associated with this campaign object
createdAtDate and time this campaign was created
updatedAtDate and time this campaign was last updated
shortenURLsBoolean value showing whether we should shorten URLs for campaign messages

Methods

Method nameDescription
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..."

Tag object

The tag object has the following properties and methods:

Properties

Property nameDescription
SIDThe tag's SID.
nameThe tag's name.
canonicalNameThe tag's canonical name.

Bot methods and properties

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.

Methods

Method nameDescriptionExample
saySends a message to the subscriber.
say("Welcome to the Sample Bot.");
getPerforms HTTP GET. The parameters are very much like those used by jQuery get().
get({
  url: "http://fortunecookieapi.com/v1/fortunes",
  data: {limit: 1, skip: offset},
  success: function(result) {
    var fortunes = result.responseJSON;
    if (fortunes !== null && fortunes.length > 0) {
      say(fortunes[0].message);
    } else {
      // our response didn't actually contain a fortune!
      say("We are having trouble reading your fortune right now.");
    }
  },
  error: function() {
    say("We are having trouble reading your fortune right now.");
  }
});
postPerforms HTTP POST. The parameters are very much like those used by jQuery post().
post({
  url: "http://example.com/message-callback",
  data: {foo: 123, bar: "yes please", isGreat: true}, // JavaScript object will get serialized
  headers: {
    // Basic authentication using Aladdin / "open sesame"
    Authorization: "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
  }
});
putPerforms HTTP PUT. The parameters are very much like those used by jQuery put().
put({
  url: "http://example.com/message-callback",
  data: {foo: 123, bar: "yes please", isGreat: true}, // JavaScript object will get serialized
  headers: {
    // Basic authentication using Aladdin / "open sesame"
    Authorization: "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
  }
});

Session

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)

Debugging Bot Javascript using toJSON

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.

Global functions

Incoming Voice Call Handling

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 nameDescription
fromCaller's phone number
from_countryCaller's country if available
from_stateCaller's state or province caller if available
from_cityCaller's city if available

Example

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.

Disable Voice Requests

function handleVoiceRequest(context) {
  return VOICE_REQUEST_REJECT;
}

Keyword extractor

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.

Example

function extractMessageKeywords(message) {
  // Remove all punctuation, then return all the words in the message in an array
  return message.replace(/[,.?!;:]/, '').split(/\s+/);
}