Base Conversation object methods

The following methods are available in Xenioo as additional functions of the javascript engine that can be used during Cloud Script Action execution. These methods can be used to interact directly with variable values, conversation state and much more.

To avoid type mismatch errors ensure that the parameters you're supplying to the following methods contain the expected type.

Chatbot Variables and Tags

GetVariable

This method will return the current value of a specified variable. If the variable does not exist, an empty string is returned.

conversation.GetVariable( variablename:string );

SetVariable

This method will update the value of a variable with a given name. Multiple overloads are available for additional call details.

conversation.SetVariable( variablename:string, variablevalue:string );
conversation.SetVariable( variablename:string, variablevalue:string, setmode:number );
conversation.SetVariable( variablename:string, variablevalue:string, replacewith:string, setmode:number );

The setmode parameter defines the mode used to update the target variable. You can use the following table as a reference for the parameter.

value

mode

0

Default. The value will be overwritten

1

Append. The value will be added to the end of the current value

2

Concatenate. The value will be added to the end of the current value, separated by a comma

3

Add. Xenioo will attempt to sum the given value to the current value of the variable

4

Subtract. Xenioo will attempt to subtract the given value from the current value of the variable

5

Divide. Xenioo will attempt to divide current value of the variable by the given value

6

Multiply. Xenioo will attempt to multiply current value of the variable by the given value

7

ReplaceString. All occurences of the given value inside the current value will be replaced by replacewith value

8

RemoveString. The given value will be removed from the current variable value

9

ClearValue. The current value of the variable will be set to an empty string value

SetTag

This method will create a new tag and attach it to the current conversation.

conversation.SetTag( tagname:string );

DropTag

This method will drop a specific tag from the current conversation. No error is returned if the tag does not exist.

conversation.DropTag( tagname:string );

HasTag

This method will check the existence of specific tag and return true if found otherwise false.

conversation.HasTag( tagname:string );

Global Variables

Global variables differ from standard chatbot variables as they are global to all conversations. Updates to any global variable is immediately reflected to every conversation. Additionally, global variables have an expiration time: if you try to access an expired variable value after the expiration period an empty string will be returned.

Global Variables are ephemeral. Any value stored in a global variable is lost as soon as the bot is published again.

GetGlobalVariable

This method will return the current value of the specified global variable. If the variable does not exist, an empty string is returned.

conversation.GetGlobalVariable( variablename:string );

SetGlobalVariable

This method will create or update the value of a global variable with a given name. An additional overload of the function can be used to set the automatic expiration of the value in minutes: accessing the variable value after the expiration date will return an empty string.

conversation.SetGlobalVariable( variablename:string, variablevalue:string );
conversation.SetGlobalVariable( variablename:string, variablevalue:string, expireminutes:number );

Conversation Flow and Data

GoTo

This method will redirect the conversation to the behaviour specified in targetbehaviour and the interaction specified in targetinteraction. If targetinteraction is empty or null, the conversation will be redirected to the start interaction of targetbehaviour. Conversation will be redirected as soon as the script action completes. No additional operations or actions will be executed, even if child of the current scripting action.

conversation.GoTo( targetbehaviour:string, targetinteraction:string );

SwitchChannel

The SwitchChannel method will change the current conversation channel. Any pending message created during the method execution will be delivered to the new channel. The target channel must be online.

conversation.SwitchChannel( channelname:string );

The method will return true if the switch is successful, otherwise false.

The method does not check the conversation data against the new channel: switching a Web conversation to a WhatsApp conversation without a user phone number will not deliver any message.

GetShareURL

This method will generate a new share URL for the current conversation. The expiretime parameter indicates after how many hours the generated URL will expire. Setting takeover as true will generate a take over URL while setting it as false will generate a view only URL. Setting autohandover to true, will automatically hand over the conversation to Xenioo as soon as the take over URL expires.

conversation.GetShareURL( expiretime:number, takover:boolean, autohandover:boolean );

DropAllShares

This method will delete and invalidate any shared URL currently active for the current conversation.

conversation.DropAllShares( );

Log

This method will log a user text to the current chat Execution Diagram. The log will be displayed as system, following the standard script action logging.

conversation.Log( text:string );

If you only need to write text to the Execution Diagram, using the Log Message action would be a much better performing option.

LogIssue

This method will log an issue text to the current chat execution diagram. The log will be displayed as system, following the standard script action logging. An issue text is displayed with an alert and a red color accent.

conversation.Log( text:string );

AddReplyPart

This method will add a new reply part to the current conversation block. You can use this method to add new text or advanced controls to the current conversation. The added parts are volatile and will not become part of the runtime chatbot build design. This method has multiple overloads that can be used to further define you action.

conversation.AddReplyPart( text:string );
conversation.AddReplyPart( type:number, text:string, command:string );
conversation.AddReplyPart( type:number, text:string, command:string, commandvariable:string );
conversation.AddReplyPart( type:number, text:string, command:string, commandvariable:string, targetbehaviour:string, targetinteraction:string );

The type parameter defines the type of chat content that the method should add to the current conversation. Refer to the table below for a list of all types supported by this method.

Type value

Content Type

0

Text

1

Quick Button

3

Image

6

Question (Blocking)

9

Video

10

Audio

11

File

17

Url

The following cloud script snippet shows how to add dynamic buttons inside a chat flow:

/*
  The Xenioo variable colors_list holds a simple JSON built like this:
  
  [
    {
      "colorid": "A",
      "color": "Red"
    },
    {
      "colorid": "B",
      "color": "Blue"
    },
    {
      "colorid": "C",
      "color": "Yellow"
    }
  ]
  
  JSON.parse transform it into a full object that can be iterated to 
  create multiple chat buttons
  
*/

var colors = JSON.parse( conversation.GetVariableValue( "colors_list" ) );
for( var i=0; i < colors.length; i++ ){
  conversation.AddReplyPart( 
                              "1"                 /* part type. 1 is button */, 
                              colors[i].color,    /* part text. We're using color name */
                              colors[i].colorid,  /* command payload. Its the value we want in our postback. We are using ID */ 
                              "picked_color",     /* postback target variable name. we can use this later in our chatbot */
                              "",                 /* button target behaviour. We leave it empty: its the current one */
                              "Color Selected"    /* button target interaction. We go to "Selected Color" you see in the diagram */
                            );
  
}

GetConversationEntriesCount

This method will return the amount of entries found in the current conversation. Each entry represent a reply block from Xenioo or a reply block from a user.

conversation.GetConversationEntriesCount( );

Conversation Entries access from scripting is always limited to the last 15 history entries, hence the maximum value GetConversationEntriesCount can return is 15.

Access to conversation entries is not enabled on preview chatbots. This function will always return 0 (zero) when used in a preview chatbot.

GetConversationEntry

Return the a model representation of conversation entry at a specific index. The conversation entry can be either a Xenioo reply block or a user reply block.

conversation.GetConversationEntry( index:number );

The entry model has the following properties:

Field

Value

Source

Indicates what generated this entry. It can be:

0: User

1: Xenioo (your chatbot)

2: System (any issue)

Date

The date of the entry in dd/MM/yyyy HH:mm:ss format

PartsCount

The number of parts contained in this entry.

GetConversationEntryPart

Return the full model of a conversation entry part at a specific index and part index. As an example a Xenioo reply block made by a text bubble and two buttons will be represented by a single conversation entry made by three parts.

conversation.GetConversationEntryPart( index:number, partindex:number );

The part model has the following properties:

Field

Value

Type

The type of the entry. Refer to the AddReplyPart function for a short list of possible types.

SubType

The subtype of the part

Text

The text associated to the part

Command

The command, if any, associated to the part. If the part is a button this will be the unique payload

TypeDelay

The calculated type delay, in milliseconds.

PartsCount

The amount of child parts that create this part. Some parts, like a card carousel may be comprised of multiple subparts.

If the parent conversation entry is generated by Xenioo (your chatbot) or by the System, the maximum length of the text property will be cut at 128 characters maximum.

This brief script example can be copied and pasted in a Cloud Script action to create a variable containing the latest conversation entries:

var chatlog = "";

for( var i=0; i < conversation.GetConversationEntriesCount(); i++ ){
    
    var entry = conversation.GetConversationEntry( i );
    switch( entry.Source ){
        case 0:
            chatlog += "User:";
            break;
        case 1:
            chatlog += "Chatbot:";
            break;
        case 2:
            chatlog += "System:";
            break;
    }
    
    for( var p=0; p < entry.PartsCount; p++ ){
        var part = conversation.GetConversationEntryPart( i, p );
        chatlog += part.Text + "\r\n";
    }
    
    chatlog += " (" + entry.Date + ")\r\n";
    chatlog += "\r\n";
    
}

conversation.SetVariable( "chatlog", chatlog );

GetConversationEntrySubPart

Return the full model of a conversation entry sub-part. As an example a Xenioo reply block made by a carousel will be represented by a single entry with one part (the element) containing at least two sub-parts (the carousel page and at least one button).

conversation.GetConversationEntrySubPart( index:number, partindex:number, subpartindex:number );

SetMessageText

Changes the text of the current user message. The change happens only in the reply processing pipeline. The original user message is still displayed in the conversation.

conversation.SetMessageText( text:string );

Operators And Conversation Control

GetOnlineOperatorsCount

This function will return the number of online operators available for the current bot.

conversation.GetOnlineOperatorsCount( );

GetOnlineOperator

This function will return an instance of the online operator found at index. This function must be called after requesting the total count of online operators using GetOnlineOperatorsCount.

conversation.GetOnlineOperator( index:number );

Each operator instance will have the following structure:

{
    Id:string;       //The unique id of the operator 
    Email:string;    //The email associated with the operator account 
    Group:string;    //The operator group assigned during invitation
}

GetOnlineOperators

This function will return a string containing all the emails of the operators detected as online for a chatbot. Each email is separated by a semicolon (;).

conversation.GetOnlineOperators( );

TakOver

This function will take over the current conversation and assign it to the operator with the specified email. This function will return true if the operator is online and the conversation can be assigned, false otherwise.

conversation.TakeOver( email:string );

When previewing your chatbot, online operator count will always be equal to one. All functions will return your current user details.

The following sample showcases a simple loop on all online operators. The resulting operators variable can be set in a text bubble to display the result.

var count = conversation.GetOnlineOperatorsCount();
var tx = "";

for( var i=0; i < count; i++ ){
    var operator = conversation.GetOnlineOperator( i );    
    tx += operator.Email + " (" + operator.Group + ")\n";
}

conversation.SetVariable( "operators", tx );

Phone Numbers and Region Code

GetPhoneRegionCode

This function will return the 2 letters region code associated with the supplied phone number.

conversation.GetPhoneRegionCode( phone_number:string );

GetPhoneRegionCodeAlpha3

This function will return the 3 letters region code associated with the supplied phone number.

conversation.GetPhoneRegionCodeAlpha3( phone_number:string );

Form Upload

UploadFromStorage

Use this method to upload a file from the Xenioo cloud storage to another URL, using standard form-data POST.

conversation.UploadFromStorage( targeturl:string, storagefile:string );
conversation.UploadFromStorage( targeturl:string, storagefile:string, fields:array, headers:array );

The storagefile parameter must be a valid Xenioo storage file name without the full URL.

The example below illustrate the upload of a file just received by a Media Input action to another server with additional fields and headers.

/*
the file is already in the server storage
we need to specify the single name, not the whole url
*/
var parts = conversation.GetVariable( "user_attachment" ).split('/');
var name = parts[ parts.length - 1 ];

var somedata = {
    DataCode:'SomeValue'
};


var result = conversation.UploadFromStorage( "https://mycustomserver.com/api/upload", 
                                             name,
                                             [ 
                                                "data", JSON.stringify( somedata  ) 
                                             ],
                                             [ 
                                                "Authorization", "bearer <someauthorizationcode>",
                                                "Accept", "application/json"
                                             ] );
                                             
conversation.SetVariable( "result", result );

The method will return any value that the invoked URL will return.

Utilities

Format

This method can return a formatted string for a number or date value according to a format specification string. The type of data supplied can be explicitly specified or can be guessed by the method.

conversation.Format( value:string, format:string );
conversation.Format( value:string, format:string, datatype:string );
conversation.Format( value:string, format:string, datatype:string, culture:string );

Datatype can be set to date or number. If datatype is supplied the method will attempt to convert value to the specified datatype. If no conversion is possible an error will occur.

The culture parameter can be used to specified the source culture of the value. The source culture can determine how a value is represented. As an example a en-US culture will expect a dot as a decimal separator and and date in mm/dd/yyyy format.

Some examples below:

var money = conversation.Format( 100000, "#,###€" );    // == 100.000€
var cut = conversation.Format( 10.5301, "0.00" );     // == 10.53
var date = conversation.Format( new Date(), "dd/MM/yyyy" ); // == day/month/year

GetNextRandom

This method can generate a random integer number ranging from min to max value (both included).

conversation.GetNextRandom( minvalue:number, maxvalue:number );

XmlToJSon

This method will try to parse a given XML source text and transform it into a valid JSON representation. The JSON representation can then be transformed to an object instance using standard JavaScript parse method. This method is particularly useful when you need to transform a SOAP API Xml response into a format that Xenioo can use for dynamic parsing.

conversation.XmlToJSon( xmlsource:string );

Last updated