JS Code block
Element name: JavaScript Code block
Categoría: Action Module
Description: Advanced functionality, consisting of an input field for structuring JavaScript code, has a customizable name.
Functionality: Allows the execution of a thread of actions in a complex sequence. It is oriented to the execution of small code scripts, so it is not intended to be an instance of programming for a complementary flow of Lynn. For structuring, most of the established JavaScript programming resources can be used, additionally pre-configured methods are included that will allow interacting with Lynn's resources.
It is important to take into account the following safe operation parameters:
-
The maximum exploitable execution memory is 10MB, so you must take into account the weight of the entities within the Code Block.
-
The maximum execution time of a JS Code Block is limited to 5 seconds, this is a security measure, when exceeding this time a "watchdog" will typify a security error. Keep in mind that each data action against CORE Lynn for entity management takes approximately 3-5 ms.
-
There is a maximum recursion limit, set at 10. Avoid unnecessary loops and, if they exist, make sure not to exceed this threshold.
-
The maximum size of execution lines is 1000 at runtime, exceeding this limit can cause degradation or significant increases in execution times in the JS Code Block.
-
This functionality is supported on ECMAScript 3 and ECMAScript 5, including ES5.
Working with the JS Code Block Action
Definition of System Variables
VARIABLE | DEFINITION |
---|---|
BotName | Bot or application name |
ClientName | Name of the client that initializes the interaction (It can be associated with the criterion according to the channel) |
AgentName | Name of the agent who serves the interaction, the update of this variable depends on the implemented contact center technology. |
ConversationId | Unique conversation ID. |
SessionId | Unique session ID. |
Tenant | Tenant identifier (integer) |
ActionId | Identifier of the executed action numerator (integer). |
CreationDate | Start time of the session. |
ChannelId | Channel identifier (integer). |
Note: You can consult the updated list of system variables or entities directly in the entity viewer of Lynn's flow editor.
Functions or methods included to work with Lynn
FUNCION | DEFINICION |
---|---|
GetEntityValue(string name) | Gets the value of an entity. |
GetGlobalEntityValue(string name) | Gets the value of a Global entity. |
InduceMessage(string text, string voiceText, string audio, bool availableByVoice, bool availableByText) | Presents a simple dialogue as a text bubble. |
InduceDataEvent(string name, string value) | Sends a data-type event to Lynn. This event is not displayed as a dialogue and is especially useful in Lynn API implementations to indicate or transmit markers. |
ClearEntityByName(string name) | Clears the set value of a local entity. |
SetEntityByName(string name, string value) | Sets the value of a local entity by specifying its name. |
RemoveEntityByName(string name) | Deletes a local entity by specifying its name. |
ClearGlobalEntityByName(string name) | clears the value set for a global entity by specifying its name. |
SetGlobalEntityByName(string name) | Sets the value of a global entity by specifying its name. |
RemoveGlobalEntityByName(string name) | Removes a global entity by specifying its name. |
ExecuteDialogActionById(int id) | Executes a dialog configured as an action by specifying its ID. It is executed at the end of the code block. |
AddActionById(int id) | Similar to ExecuteDialogActionByID, adds the execution of an action by specifying its ID. It is executed at the end of the code block. |
GetUnrecognizedText() | In case of cognitive evaluation, returns the unrecognized text. Example: I am Alberto and I want to check my current account balance. Detected intent: Balance, Entity: Current Account, and unrecognized text: Alberto or any text that is not recognized in the cognitive evaluation. |
GetEvaluationText() | Returns the text entered by the client for evaluation purposes. |
GetBaseConfiguration(string key) | Retrieves the value of an application configuration parameter. Note: Can be used as constants. |
GetConfiguration(int actionId, string key) | Returns the value of a configuration parameter associated with an action ID. The key is associated with each configurable field of the action. |
StartChatConversation(int actionId, string from) | Transfers to the chat engine (This method requires that the chat engine configuration be established in the application configuration and only admits one per application) |
FinalizeConverzation() | Ends the current conversation. Example in a queue overflow. |
FinalizeChatConverzation() | Ends the conversation and returns a boolean indicating that the conversation has ended. |
IsOnChatConversation() | Returns a boolean indicating whether the conversation is in chat with an executive. |
GetHistoric(string level) | Returns historical information associated with a specific level of recording. Values: Audit/Debug/Error/Dialog. The returned value is a string in Json format, associated with the current session. |
Importante:
-
Execution methods for variable manipulation take effect at the end of the action execution.
-
Pay special attention to code validation, including the closing semicolon ";" and curly brackets "{}" in conditions and loops. We recommend using a JS syntax validator for this purpose, as there are many free tools available online.
Action Configuration Fields
[Name] Unique descriptor of the configuration box for identification purposes in the flow.
[Code Implementation] Code input space for implementing logic in JavaScript.
[Error Handler] Selection box where the intention that will be activated in case of a Code Block error is identified. When an error overflow occurs, the Code_Block_Error entity will be loaded with error details if available.
Examples of JS Code Block Implementation
Example 1: Using conditions and loops. (if/for)
-- JS Code block input::
var count = GetEntityValue('Iteration');
if (count > 10) {
InduceMessage('Maximum limit exceeded: 10', '', '', true, true);
count = 10;
} else {
InduceMessage('Repeat the message -Hello world Lynn: ' + count + ' times', '', '', true, true);
}
for (var i = 1; i <= count; i++) {
InduceMessage('Hello world Lynn -\>' + i, '', '', true, true);
}
InduceMessage('\*---\*', '', '', true, true);
-- Result 1. Precondition> NumberMessagesPrint --> 3:
Now I am going to repeat the message 'Hello World Lynn' 3 times
Hello World Lynn ->1
Hello World Lynn ->2
Hello World Lynn ->3
*---*
Please note that each dialogue message corresponds to a text bubble.
-- Result 2. Precondition>NumberMessagesPrint --> 11:
You entered in number 11, I'm going to limit the number of iterations to only 10
Hello World Lynn ->1
Hello World Lynn ->2
Hello World Lynn ->3
Hello World Lynn ->4
Hello World Lynn ->5
Hello World Lynn ->6
Hello World Lynn ->7
Hello World Lynn ->8
Hello World Lynn ->9
Hello World Lynn ->10
*---*
Example 2: Formatting Json from weather Web services and unit conversion.
-- Input JS Code block:**
try {
var JsonResponse = GetEntityValue('JsonWebRequestResult');
if (JsonResponse !== null) {
var obj = JSON.parse(JsonResponse);
var weatherWindSpeed = obj.wind.speed;
var weatherTemp = Number(obj.main.temp).toPrecision(2) - Number('273.15');
var weatherPressure = obj.main.pressure;
var weatherHumidity = obj.main.humidity;
var weatherCodeResponse = obj.cod;
if (weatherCodeResponse === 200) {
InduceMessage('Wind speed: ' + weatherWindSpeed + 'm/s', '', '', true, true);
InduceMessage('Temperature: ' + weatherTemp.toPrecision(2) + ' Celsius', '', '', true, true);
InduceMessage('Pressure: ' + weatherPressure + 'mbar', '', '', true, true);
InduceMessage('Humidity: ' + weatherHumidity + '%', '', '', true, true);
}
}
SetEntityByName('JsonWebRequestResult', '');
SetEntityByName('WeatherCityToFind', '');
JsonResponse = null;
}
catch (error)
{
InduceMessage('City not found', '', '', true, true);
}
-- Result. Precondition>Input Json>JsonWebRequestResult
{
coord:
{
lon: -70.6483,
lat: -33.4569
},
weather: [
{
id: 804,
main: Clouds,
description: overcast clouds,
icon: 04d
}
],
base: stations,
main:
{
temp: 288.35,
feels_like: 287.34,
temp_min: 283.84,
temp_max: 290.92,
pressure: 1024,
humidity: 54
},
visibility: 7000,
wind: {
speed: 2.06,
deg: 260
},
clouds: { all: 100 },
dt: 1662053921,
sys: {
type: 2,
id: 2075413,
country: CL,
sunrise: 1662030043,
sunset: 1662071095
},
timezone: -14400,
id: 3871336,
name: Santiago,
cod: 200
}
Output:
description: overcast clouds
Wind speed: 3.09m/s
Temperature: 17 Celsius
Pressure: 994mbar
Humidity: 70%
Note that the information from the JSON response of a web service has been taken and formatted for presentation, including transformations from Fahrenheit to Celsius temperature units.
Advanced Functions
Not declared.