How to develop code on the platform?

Here you will learn how to create code within the Botmaker platform.
Estimated Reading Time: 10 minutes

From the main menu, click on Code :

Client Actions are useful for developing more complex intents or when you want to add arbitrary code into a conversation. It is an excellent alternative that allows you to connect external services to acquire relevant information in real-time while holding a conversation with the user.

For example:

You can ask the user to say a color. Once they send their message, you can connect the Google Translation API to make the bot respond with the same color, but in a different language.

How to trigger code

First, you must create a Client Action on the Codes screen. See below:

Assign a name to the action (don’t forget) and click on “save”.

To activate the action, click on “+ Action”, choose “Client Action” and select the code that will be executed:

Code features

We support Node.js v6.14.0, along with the list of libraries below:

  {
    "@turf/helpers": "^6.1.4", // accessed by "turfHelpers" var
    "@turf/turf": "^5.1.6", // accessed by "turf" var
    "bluebird": "^3.5.1", // accessed by "bluebird" var
    "googleapis": "^32.0.0", // accessed by "google" var
    "js-sha256": "^0.9.0", // accessed by "sha256" var
    "jsonwebtoken": "^8.3.0", // accessed by "jwt" var
    "lodash": "^4.17.10", // accessed by "_" var
    "md5": "^2.2.1", // accessed by "md5" var
    "moment": "^2.22.2", // accessed by "moment" var
    "redis": "^2.8.0",
    "request": "^2.87.0",
    "request-promise": "^4.2.2", // accessed by "rp" var
    "secure-random": "^1.1.1", // accessed by "securedRandom" var
    "xml2js": "^0.4.19", // accessed by "xml2js" var
    "aws-sdk": "^2.485.0"  // accessed by "awsSdk" var
  }

In case you want to use another library, please write us an email to architecture@botmaker.com, and our team will accept your request, if possible.


Client action entry

When the code is activated, all the information we have about the user, conversations and general settings will be provided. The json below describes the entry that can be used on a cloud function.

{
  "context": {
    "userData": {
      "CHAT_PLATFORM_ID": "webchat",
      "CHAT_CHANNEL_ID": "YPDXTZKM8Y3NXLXVQYAN-webchat-null",
      "PLATFORM_CONTACT_ID": "0BBSX05QRF-3318782UBYKNLUIRBM0KL8XMDTM",
      "LAST_MODIFICATION": "2018-07-23T03:43:51.243Z",
      "HAS_TALKED": true,
      "_id_": "O0IUBYCHJYSA4PNB0QH7",
      "LAST_SEEN": "2018-07-23T03:43:52.279Z",
      "variables": {
        "svar": "sdas"
      },
      "tags": [
        "testtest2"
      ]
    },
​
    "message": {
      "BUSINESS_ID": "YPDXTZKM8Y3NXLXVQYAN",
      "CREATION_TIME": "2018-07-23T03:43:52.281Z",
      "FROM_NAME": "Usuario",
      "CUSTOMER_ID": "O0IUBYCHJYSA4PNB0QH7",
      "_id_": "LBIJGWZN4SJADFT2HUD2",
      "FROM": "0BBSX05QRF-3318782UBYKNLUIRBM0KL8XMDTM",
      "OBJECT_TYPE": "Message",
      "SESSION_CREATION_TIME": "2018-07-23T03:43:52.281Z",
      "AUDIOS_URLS": [],
      "MESSAGE": "test",
      "CHAT_PLATFORM_ID": "webchat",
      "CHAT_CHANNEL_ID": "YPDXTZKM8Y3NXLXVQYAN-webchat-null",
      "LAST_MODIFICATION": "2018-07-23T03:43:52.281Z",
      "TO": "me",
      "TAGS": {}
    },
​
    "params": {}
  }
}

The Context object

A read-only object that has relevant information that may require a code action. It provides:

  • userData: all user’s information, including tags and variables, if any;
  • message: information about the user’s last message;
  • params: optional parameters that can be sent via a rule.

For example:

const userFirstName = context.userData.FIRST_NAME;

The User object

This object allows you to read and write variables that will persist on the user. It’s a very handy tool that lets you store data related to the user.

Take into account that the values will have to be of the string type.

  • To read a value: user.get(‘valueKey’) => will return a string with a value in it or null
  • To write a value: user.set(‘valueKey’, ‘value’)

For example:

if ( !user.get('neverWasHere') )
  user.set('neverWasHere', 'true');

The value of neverWasHere will be true forever, even when another clients action sets a different value.

In the variable settings section, it’s possible to change the variable type and whether it will be visible or not to operators.

Also, the variable can expire along with the session, i.e., after one hour of inactivity.


Using entityLoader entities

When a cvs file is uploaded in the “records” menu of the platform, the client actions will have access to it. A saved list can be filtered.

id | name
 1 | Gabriel
 2 | Dario
*/
​
//Use the entityLoader function to read the loaded entities
entityLoader('entity name', json => {
​
  // here you got your entity object loaded as json
  if (!json) {
    user.set('error', 'No hay datos');
    result.done();
    return;
  }
​
  //You are looking for the data you need
  const data = json.find(row => row.id === 2);
  
  result.text('I show the name ->' + data.name);
    
});

The conncetRedis object

One instance of db is available for use with Client Actions. You can:

const redis = connectRedis();
const myKey = redis.get('key');

Redis is fully supported. Check out the official library: Redis Library


Client Action result

Any additional result that a client action wants to create must be done using the resulting object:

  • To tell the user something using text: result.text(‘a message’)
  • To display an image to the user: result.image ('https://example.com/image.jpg') `
  • To show a video to the user: result.video ('https://example.com/video.mp4')
  • To show a file to the user: result.image ('https://example.com/myfile.doc')
  • To send audio file to the user: result.audio ('https://example.com/audio.mp3')
  • It is also possible to send the user a text with action buttons.
  .text('select an option')
  .addURLButton('click me', 'https://www.google.com') // a button that will open a page
  .addLocationButton() // ask the user for its location using GPSs
  .quickReplies() // marks the button so it's showed as pills
  .addPhoneButton('call me', '+11233212312')
  .addButton('click me', 'rule with name XX') // when user clicks it will fire the rule named XX
  .send(); // send must by always called to finalize


Go To another rule

It is possible to have a rule that executes itself after completing a client action very easily. This is useful because, after telling the user something, changing some data, or modifying their status, you may want to continue the flow of the conversation by activating a rule.

result.gotoRule('a rule name');

Client Action termination

result.done() must be executed when the client action is complete.

It is crucial that you call result.done () in every flow that has a client action, to properly end its execution.

The following code shows you a properly implemented Client Action, with the done () method being called in all of the flow.

    .then(json=> {
        // saying the time
        result.text('The time in Tokyo is ' + json.fulldate);
​
        // do not forget to end the execution
        result.done();
    })
    .catch(error => {
        result.text('Problems: ' + error + '|' + JSON.stringify(error));
        result.done();
    });

Using custom lists (JSON lists)

If you want to use options for a dynamically configured question that changes over time, it is possible to add a value to a particular variable within a client action.

In the Javascript code, you will need to create a list of objects, each with an “id” field and a “name” field. You can add other keys to these objects, but it’s not mandatory. Have a look at the example:

​
myJSONList = COUNTRIES.map((country, index) => { return { id: index, name: country }; });
​
//result.text(JSON.stringify(myJSONList)); user.set('countries', JSON.stringify(myJSONList));
​
result.done();

To use this variable in an intent, you will need to declare that valid values for the question are from a custom JSON list and refer to the variable used in the code.

Finally, you should see something like this:

Creating a Client Action with parameters

They can be created using the “Customer Actions with Params” option:

Or from code, using a button that calls another Client Action:

	.addClientActionButton('button name',   //Name that will appear on the button
												 'Client Action Name, //Client action name
												 { 
												    'key': 'value',
												    'key2': 'other_value'
												 })  //Json Object with the parameters that will be sent
  .buildButtons();

To use the parameters sent to Client Action:

const myVar = context.params.key
const myVar2 = context.params.key2 

Running an external API query from a Botmaker client action

To execute a query to an external API from a Botmaker client action, see the following example:

Written by: Botmaker
Updated: 11/26/2021