Use the following built-in functions to get and set session data.

Get and set bot variable

Use the setBotVariable function to set the value of a bot variable, so you can subsequently use it in the bot flow. By default, the function stores the value in request scope, but you can specify the scope as a parameter.

Use the getBotVariable function to get the value of a bot variable. Bot variables that are not set return NULL.

One common question here is, “Is the data stored in its original type or as a string?” This is a good question because it affects your code for retrieving the value, so you can use it. The answer is, “It depends.” That is, if you set a variable and then retrieve it within the same message scope, the data is stored and retrieved in its original type.

Example conversation showing two messages from the consumer each with follow-up responses from the bot, so two instances of message scope

So, in all of the interactions that are evaluated within a single message scope (and there might be several interactions involved)⸺i.e., up until the point that the consumer sends the next message⸺you can use getBotVariable to retrieve the value in its original data type.

However, once the flow of control moves to the next message scope, the data is converted to a string (e.g., number 10 to string “10”). After this point, getBotVariable returns a string, and you must explicitly cast it to its original data type if needed.

The above behaviors apply to both variables and slot variables.

To avoid this complication and be on the safer side, always treat the value as a string, and do explicit type casting.

Function Name Arguments Returns
getBotVariable(name) name (string) — The name for the variable. The object or string defined by name; see the discussion above
setBotVariable(name, value, persistForSession, persistForever) name (string) — The name for the variable

value (object) — The value to be stored

persistForSession (bool) — If true, the variable persists for the current user session. If false, the variable is treated as a request variable, which means the variable is available from the time the user posts a question to the time the bot responds. You can set a request variable in the Pre-Process code and use it in the Post-Process code, as both are evaluated in the same request.

persistForever (bool) — If true, the variable persists for 180 days. Note: Support for a value of "true" will be deprecated in a future release. Use of the Conversation Context Service is recommended instead.
None

Example

In the example below, we're using getBotVariable to retrieve a string. Then we're converting it to an integer before using it as an integer.

// retrieving an integer
var count = botContext.getBotVariable('Howmanyitems');
count = count*1;
if (count > 10) {
      botContext.sendMessage('You have more than 10 items!');
} else {
  botContext.setBotVariable('Howmanyitems',0,true,false);
  botContext.sendMessage('Sorry, you do not have any items with you… ');
}

Get current user message

getCurrentUserMessage is used for getting the most recent message from the user, whether typed or tapped (buttons or quick replies).

Function Name Arguments Returns
getCurrentUserMessage() None (string) The full text of the most recent message from the user

Example

// get what the user just said
var response = botContext.getCurrentUserMessage();
// use the response in a variable
botContext.setBotVariable('newsSource',response,true,false);

Set bot transfer intent by domain

Use the setBotTransferIntentbyDomain function to set an intent ID in the Transfer Bot Context object that can be sent from the sender bot to the receiver bot during a manual, bot-to-bot transfer. The intent ID is derived from the supplied domain name and intent name. You can retrieve the domain name that you need from the UI. And you can retrieve the intent name that you need from the UI or via getDialogStarterIntent. During the transfer, the system uses the domain name and the intent name to ascertain and pass the intent ID.

Function Name Arguments Returns
setBotTransferIntentbyDomain(intentName, domainName) intentName (String) — The name of the intent
domainName (String) — The name of the domain
None

Example

botContext.setBotTransferIntentbyDomain("billing question", "Billing");

Set bot transfer intent ID

Use the setBotTransferIntentId function to set an intent ID in the Transfer Bot Context object that can be sent from the sender bot to the receiver bot during a manual, bot-to-bot transfer. You can retrieve the intent ID that you need from the application URL if you're logged into LivePerson Conversation Builder directly and know how. Otherwise, use setBotTransferIntentbyDomain instead.

Function Name Arguments Returns
setBotTransferIntentId(value) value (String) — The intent ID None

Example

botContext.setBotTransferIntentId("d46688d7-7ec2-44a4-a09c-b500f728ee05");

Set bot transfer user message

Use the setBotTransferUserMessage function to set a user message in the Transfer Bot Context object that can be sent from the sender bot to the receiver bot during a manual, bot-to-bot transfer.

Function Name Arguments Returns
setBotTransferUserMessage(value) value (String) — The user message None

Example

botContext.setBotTransferUserMessage("order status");

Get environment variable

getEnvVariable is used for getting an environment variable. An environment variable that isn't set returns NULL.

Function Name Arguments Returns
getEnvVariable(name) name (string) — The name of the variable. The object defined by name

Example

In the example below, we use getEnvVariable to retrieve a string which will provide for us the correct skillId for routing depending upon the environment that the bot is currently in.

switch(intent){
case "billing":
    transferMessage = "Hold on while I transfer you to someone who can help with your billing issue…";
    skillId = botContext.getEnvVariable('billing');
    skillName = intent;
    break;
case "account":
    transferMessage = "Hold on while I transfer you to someone who can help with your account issue…";
    skillId = botContext.getEnvVariable('account');
    skillName = intent;
    break;
case "help":
    transferMessage = "Hold on while I transfer you to someone who can help with your issue…";
    skillId = botContext.getEnvVariable('help');
    skillName = intent;
    break;
}

Get bot ID

The getChatBotId function retrieves the bot ID for the current conversation.

Function Name Arguments Returns
getChatBotId() None Bot ID (string)

Example

// store the bot's ID in a variable inside your current pre/post process code
var botId = botContext.getChatBotId();

Get conversation ID

The getConversationId function will retrieve the conversation ID for the current conversation.

Function Name Arguments Returns
getConversationId() None Conversation ID (string)

Example

// store the conversation id in a variable inside your current pre/post process code
var convId = botContext.getConversationId();

You can also use the {$conversationId} system variable to display the conversation ID as text in interactions or post bodies.

Get LP account ID

The getLPAccountId function retrieves the Conversational Cloud account ID for the current conversation.

Function Name Arguments Returns
getLPAccountId() None LP account ID (string)

Example

// store the LP account ID in a variable inside your current pre/post process code
var acctId = botContext.getLPAccountId();

Get LP engagement attribute

The getLPEngagementAttribute function retrieves the specified LivePerson engagement attribute for the current conversation.

When getting engagement attributes, some time is required to retrieve the results. Therefore, LivePerson strongly recommends that you call this function in the Global Functions in the initConversation function, which runs immediately when the conversation begins. This is a best practice.

The above said, there are times when you’ll want to call this function right at the point where it’s needed. For example, when retrieving a bearer token for authentication/authorization in an integration, you’ll want to call this function in the Pre-Process code of the Integration interaction.

Function Name Arguments Returns
getLPEngagementAttribute(arg) sharkVisitorId — The ID of the real-time visitor,
sharkSessionId — The ID of the session,
sharkContextId — Conversational Cloud's interactionContextId
campaignId — The ID of the campaign,
engagementId — The ID of the engagement,
startTs — The start time of the engagement,
os — The consumer's operating system,
appId — The ID of the app on the consumer's mobile device,
brandId — The ID of the brand,
BearerToken — The authentication credential,
currentSkillId — The ID of the current skill, or
previousSkillId — The ID of the previous skill
leAgentId — The ID of the agent user
rtSesssionIdChat-specific; the session ID for the chat engagement
chatSessionKeyChat-specific; the unique key of the agent session (when the agent talks to the consumer)
agentSessionIdChat-specific; the agent's login session ID (specific to the agent that's logged in, who can be talking to multiple consumers)
String

previousSkillId only works for Messaging. If used in a Chat conversation, it will be set to the same ID as the current skill ID.

Example

The following example shows how to use the function to access the current skill and previous skill IDs and set them to a botContext variable.

var currentSkill = botContext.getLPEngagementAttribute("currentSkillId");
var previousSkill = botContext.getLPEngagementAttribute("previousSkillId");

botContext.setBotVariable("currentSkill", currentSkill, true, false);
botContext.setBotVariable("previousSkill", previousSkill, true, false);

Messaging connector requirements:

  • Ensure that the bot is set up with API OAuth login rather than password login.
  • Ensure that the OAuth keys have permission to Engagement History.

Get conversation metadata

Understanding the context of a consumer message can be valuable. This context or metadata can empower the bot with relevant information that’s actionable. For example, in the case of a conversation on a social messaging platform, it can be helpful to retrieve the platform in use, the page the consumer is on, the type of message (direct message, comment to post, comment to comment, etc.), and so on.

Use the getMetadata function to retrieve conversation metadata from the most recent consumer message received by the bot. Some notes on this:

  • The list of metadata types that you can retrieve is in this section.
  • Remember: The metadata is always retrieved from the most recent consumer message. Also, the metadata changes with each consumer message.
  • Conversation metadata can be set by any service that can inject it into the conversation: a social messaging event, a button click event in a Structured or Button question in a Conversation Builder bot, etc.
  • If you use this function in the Process User Response code of a question, the metadata comes from the consumer response to the current question. If you use this function elsewhere in a question (or in a statement or integration), the metadata comes from the last consumer message. So keep in mind the order of operations in interactions.
Function Name Arguments Returns
getMetadata(metadataEventTypeName) metadataEventTypeName (String) — The name of the metadata type. For the list of types, see this section. If the metadata type exists, the JSON list is returned. If it does not, returns null/undefined.

Example

var socialMetaData = botContext.getMetadata(SocialMessagingEventData)

The socialMetaData variable receives the SocialMessagingEventData from the metadata Javascript object array:

[{
    "type": "SocialMessagingEventData",
    "event": {
        "source": "Facebook",
        "type": "{DirectMessage | Post | CC |CP }", // Post - User post into page community wall | CC - Comment to Comment | CP - Comment to Post
        "parent": { // not required
            "attachmentUrl": "{post_url}",
            "pageName": "{FB Page Name}",
            "postId": "{Parent Post or Comment Id}",
            "postText": "{Parent text}",
            "timestamp": 1594995901
        }
    },
    "channel": "{Public|Private}",
    "replyToId": "{The id of the message which will be send the response - used from Agent->Consumer}" // not required - from Consumer to Agent
    "conversationState": {
        "dmChatId": "{Messenger Id}",
        "currentChannel": "{Public|Private}",
        "enabledChannels": { // not required - channels enabled for this Facebook Page - configured on Connector
            "private": true,
            "public": true
        }
    },
    "actions": [{ // not required
        "name": "{Name of the action or field to be used on the connector}",
        "payload": "{payload or field content}"
        }
    ]
}]

Currently, it isn’t possible to convert the object array to JSON. However, you can extract it and save it to the botContext like so:

var metadataByType = botContext.getMetadata("SocialMessagingEventData");

var metadataType = metadataByType[0]["type"];
var metadataSource = metadataByType[0]["event"]["source"];

botContext.setBotVariable("metadataType", metadataType, true, false);
botContext.setBotVariable("metadataSource", metadataSource, true, false);

Get matched intent

getDialogStarterIntent is used to retrieve the intent (associated with a Dialog Starter interaction) that was matched to the most recent user utterance.

This method returns the name of the intent. If you are using a meta intent, it returns the name of the child or sub-intent.

This scripting function only works within the current bot; it doesn’t work across the bots in a collaborative bot group. If you invoke this function in Bot A but the intent is ultimately matched to a dialog starter in Bot B, this function returns null.

Example

var intentName = botContext.getDialogStarterIntent();

Get named entities

Use getNamedEntities to access user utterances that are recognized by the NLU engine as entities.

To access the actual phrases used, call getPhrase() on the entity objects.

Function Name Arguments Returns
getNamedEntities(entity_name) entity_name (string) array of namedEntity() objects

Example

The following returns an array of toppings found. So, in an utterance like "I would like a pizza with pepperoni, sausage and peppers," it would return [pepperoni, sausage, peppers]:

var toppingObjects = botContext.getNamedEntities('toppings');
var toppings = [];
if (toppingObjects != null && toppingObjects.length > 0) {
    for (j = 0; j < toppingObjects.length; j++) {
        toppings.push(toppingObjects[j].getPhrase())
    }
}

Can an entity return a different value?

Sometimes, you'll want an entity match to return a value, say for sending to an API. For example, if you have an entity for "sizes" with values like small, medium, and large, but your API is expecting numeric data values like small: 10, medium: 11, and large: 12, how would you create this mapping?

In Intent Manager, when creating your entities, you can provide data with additional values by adding a "~" between the phrase and the data value like this: small~10, medium~11, etc. When calling the entity, you would use the following to get the data value:

var size = botContext.getNamedEntities('sizes');

var whichSize = '';

if (size != null && size.length > 0) {

    for (j = 0; j < size.length; j++) {

        whichSize = size[j].getDataValue();

    }

}

How do I use multiple entities to map to a single value?

Sometimes you need a number of entities to map to a single value. For instance, multiple misspellings or alternative utterances that all mean the same thing. Use the data value to be the unifier for these different possible utterances.

Using a similar script to the above color example, which returns the data value, would get you the value that you need.

Get NLP responses

This function is intended to be used in bots using domains that use the LivePerson (Legacy) NLU engine for intent matching. Brands are encouraged to migrate to the LivePerson NLU engine as soon as possible. There are many benefits to switching engines.

getNlpResponse is used to get an array of results derived from Conversation Builder’s Natural Language Processing algorithms.

For instance, the sentence, “The quick brown fox jumped over the lazy dog” returns the following nouns [dog, fox], the verb [jumped], the phrases [the quick brown Fox, the lazy Dog] and tokens: [the, over, quick, lazy, jumped, brown, Dog, Fox].

Function Name Arguments Returns
getNlpResponse() None array of NLP results (nouns, verbs, phrases, sentences, tokens)

Example

// get the results
var nlpResponse = botContext.getNlpResponse();
var nlpNouns = nlpResponse.nouns;
var nlpVerbs = nlpResponse.verbs;
var nlpPhrases = nlpResponse.phrases;
var nlpTokens = nlpResponse.tokens;

botContext.sendMessage('I found the following nouns: '+ nlpNouns + ' and verbs: '+ nlpVerbs + ' and phrases: ' + nlpPhrases + ' and tokens: ' + nlpTokens);

Get sentiment

This function is intended to be used in bots using domains that use the LivePerson (Legacy) NLU engine for intent matching. Brands are encouraged to migrate to the LivePerson NLU engine as soon as possible. There are many benefits to switching engines.

getSentiment is used for having the sentiment conversation chatbox messages with the user. Instead of using the sentiments in the intents of the bot, this function relies on programmatically checking the sentiment of the user.

Function Name Arguments Returns
getSentiment() None returns a string (Positive, Neutral, Negative) based on the most recent user message

Example

// get the sentiment results
var sentiment =  botContext.getSentiment();
if(sentiment == "Positive"){
    botContext.sendMessage('Excellent!');
} else if(sentiment == "Neutral"){
    botContext.sendMessage('Hmmmm, not too sure about that…');
} else {
    botContext.sendMessage('Well that’s not good.');
}

Get quick reply payload

getQuickReplyPayload is used to access the Quick Reply buttons that are selected by the user. These buttons have a hidden payload that may be different than the text shown to the user. For instance, Quick Replies asking you to select your favorite color might show: Red, Blue, Green, Purple, etc., but the payloads could be color01, color02, color03, etc.

This function is used in Process User Response, where the code for assessing user interaction resides.

Function Name Arguments Returns
getQuickReplyPayload() None (string) The payload associated with the user-selected Quick Reply option

Example

//get what the user just said
var response = botContext.getCurrentUserMessage();
//accessing the user selected payload
var payload = botContext.getQuickReplyPayload();
//sending an Immediate reply to the user with the desired output
botContext.sendImmediateReply('Hey you picked option ' + response  +' with a payload of '+ payload);

Get disambiguated intent

getDisambiguatedIntentName and getDisambiguatedIntentId can be used in preProcess/postProcess/processUserResponse code to get the relevant disambiguated intent data.

Function Name Arguments Returns
getDisambiguatedIntentName() None selected intent name from the disambiguation interaction (string)
getDisambiguatedIntentId() None selected intent ID from the disambiguation interaction (string)

Example

// get the disambiguated intent name
var intentName = botContext.getDisambiguatedIntentName() ;
// get the disambiguated intent ID
var intentID = botContext.getDisambiguatedIntentId();
// display the results…
botContext.printDebugMessage('The intent name = ' + intentName + 'and the intent ID = ' + intentID);

Get Web View variables

getWebViewVariable and getWebViewVariables retrieve session-scoped variables that were set via the Web View API.

Function Name Arguments Returns
getWebViewVariable(variableName) variableName — the name of the variable to retrieve string
getWebViewVariables() none object:list of strings

Example

    botContext.getWebViewVariable('name'); // This returns the value as PaymentId
    botContext.getWebViewVariable('PaymentStatus'); // This returns the value as PROCESSED

For the corresponding curl example, see the Web View API documentation.

Get type of hours

Given an array of hours classified by type and a time zone, getHoursType returns the type of hours.

This method is commonly used to provide a different experience or messaging to the consumer during regular or after hours. Additionally, the method is able to handle generalized hours, hours for specific days of the week, and specific dates. Note the following:

  • Keys: The keys are user-defined and arbitrary (REG_HOURS, AFTER_HOURS, etc.). If you want to specify a shift/time period for a particular day, use the name of the day (“FRIDAY|”, “SATURDAY|”, etc.) as appropriate. You can also use a specific date (e.g., 12.25.2018 for Christmas).
  • Values: If two time frames overlap, the later time frame is used.
  • Time zone: The time zone value should be the time zone of the agent call center, not the user. Use the appropriate format.

getHoursType is a basic function to specify agent time shifts.

Function Name Arguments Returns
getHoursType(hoursSpec, zoneIdStr) hoursSpec (String array) — The hours classified by type

zoneIdStr (String) — The time zone, e.g., “America/Los_Angeles”
The String that defines the type of hours, e.g., “AFTER_HOURS”

Example

var hoursSpec = [
    "REG_HOURS~8:00~20:00",
    "AFTER_HOURS~20:00~8:00",
    "FRIDAY|WKEND_REG_HOURS~8:00~17:00",
    "FRIDAY|WKEND_AFTER_HOURS~17:00~08:00",
    "SATURDAY|WKEND_REG_HOURS~8:00~17:00",
    "SATURDAY|WKEND_AFTER_HOURS~17:00~08:00",
    "SUNDAY|WKEND_REG_HOURS~8:00~17:00",
    "SUNDAY|WKEND_AFTER_HOURS~17:00~08:00",
    "11.22.2018|HOLIDAY_THANKS~0:00~23:59",
    "12.25.2018|HOLIDAY_XMAS~0:00~23:59"
];

var type = botContext.getHoursType(hoursSpec, "America/Los_Angeles");

// TEST FOR type and set the transferMessage to result
switch(type){
  case "REG_HOURS":
  case "WKEND_REG_HOURS":
    msg = "Let me connect you to an Agent who can help you.";
    botContext.setBotVariable('transferMessage',msg,true,false);
    botContext.setTriggerNextMessage('LivePerson Transfer');
    break;

  case "AFTER_HOURS":
  case "WKEND_AFTER_HOURS":
    msg = "You have reached us after our business hours. We are open 7 days a week; 8AM – 8PM PST Monday through Thursday and 8AM – 5PM PST Friday through Sunday.";
    botContext.setBotVariable('noTransferMessage',msg,true,false);
    botContext.setTriggerNextMessage('No Transfer');
    break;

  case "HOLIDAY_THANKS":
    msg = "We are closed for the Thanksgiving holiday today. We will resume regular hours tomorrow. We are open 7 days a week; 8AM – 8PM PST Monday through Thursday and 8AM – 5PM PST Friday through Sunday.";
    botContext.setBotVariable('noTransferMessage',msg,true,false);
    botContext.setTriggerNextMessage('No Transfer');
    break;

  case "HOLIDAY_XMAS":
    msg = "We are closed for the Christmas holiday today. We will resume regular hours tomorrow. We are open 7 days a week; 8AM – 8PM PST Monday through Thursday and 8AM – 5PM PST Friday through Sunday.";
    botContext.setBotVariable('noTransferMessage',msg,true,false);
    botContext.setTriggerNextMessage('No Transfer');
    break;
}