Code Editor
Learn how to steer the conversation by writing JavaScript code with the Code Action.
The code action allows developers to quickly build custom logic on top of their bot by writing their own Javascript code blocks. Typically, the code editor is used to perform requests to external systems, or to do operations with variables.

Getting Started

To get started with the Code Action, create a new 'Action Dialogstate' and select the Code plugin as an action.

Arguments in the Code Editor

You can pass arguments to your Code actions by assigning them keys. Your keys will be made available to the args variable inside the Code Editor.

ChatlayerResponseBuilder function

The ChatlayerResponseBuilder function returns a helper instance that allows you to steer your conversation by sending messages as a bot, navigating to bot dialogs, or even creating session data.
To start manipulating conversation data in your code action, simply call the function ChatlayerResponseBuilder() which will return a ChatlayerResponseBuilder instance.
The ChatlayerResponseBuilder has a fluent interface, this means that every function you call will return the same instance. This makes it easy to chain multiple function calls when, for example, you want to show a message and manipulate session data at the same time.
Whenever you want to publish your changes to the conversation, you must call the send() function.
If you don't call the send() function anywhere in your Code Action, users will not see any of your results after the code has executed.
1
ChatlayerResponseBuilder()
2
.addSessionVariable("user", { address: { ... } })
3
.addMessage("Thank you for sharing your address!")
4
.send();
Copied!
Another way to accomplish the same result:
1
const builder = ChatlayerResponseBuilder();
2
builder.addSessionVariable("user", { address: { ... } });
3
builder.addMessage("Thank you for sharing your address!");
4
builder.send();
Copied!
​

Set variables or send messages

The ChatlayerResponseBuilder has the ability to set variables or adding messages to the chatbot. Both are shown in the example below:
addSessionVariable(namespace: string, data: any): Insert a variable on a certain namespace within the session.
addMessage(message: string): Adds a text message to be sent by the bot.
1
ChatlayerResponseBuilder()
2
.addSessionVariable("user", 'Joachim')
3
.addMessage("addSessionVariable done.")
4
.send();
Copied!
To enhance your variables even more, you can store multiple variables about the user in an object.
1
ChatlayerResponseBuilder()
2
.addSessionVariable("user", { firstName: "Joachim", lastName: "Chatbot" })
3
.send();
Copied!
If you would like to use this information in a bot message, simply type {user.lastName} and the information is visible in the chatbot!

Next or previous dialogs

Based on code, variables or other input, you can steer the conversation to other dialogstates. With the code below you can go to a next dialogstate.

setNextDialogState(dialogstateId: string)

Route the conversation to the given dialogstate ID.
1
const { introductionDialogstate } = args;
2
​
3
const chatlayer = ChatlayerResponseBuilder();
4
chatlayer.setNextDialogState(introductionDialogstate);
5
chatlayer.send();
Copied!

Bot Message functionalities

In the code editor, some 'bot message' functionalities are also available, such as quick replies or buttons. For more in depth functionality, these same options can be created using code.

addCarousel

In the Code Editor it is also possible to add a carousel, just like in Bot messages. This can be of added value when dynamic content needs to be shown or to combine a Bot message and Action dialog in one.
1
ChatlayerResponseBuilder().addCarousel([
2
{
3
title: 'Item 1',
4
imageUrl: 'https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg',
5
buttons: [
6
{ type: 'web_url', url: 'https://docs.chatlayer.ai', title: 'Docs' }
7
]
8
},
9
{
10
title: 'Item 2',
11
// This is optional
12
subTitle: 'Item 2 Subtitle',
13
// This is also optional, it will redirect a user to a certain website when they click the carousel image
14
webUrl: 'https://docs.chatlayer.ai',
15
imageUrl: 'https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg',
16
buttons: [
17
{ type: 'web_url', url: 'https://docs.chatlayer.ai', title: 'Docs' }
18
]
19
}
20
]).send();
Copied!

addQuickReplies

Just like the example above, Quick Replies can also be created in the code editor. By copying the code below you can add as many Quick reply buttons as needed.
1
const quickReplies = [
2
[
3
{
4
title: "Option 1",
5
payload: {
6
nextDialogstateId: args.setNextDialogstateDs,
7
params: [
8
// This will be set on the session.0
9
{ key: "choice", value: "option1" },
10
],
11
},
12
},
13
{
14
title: "Option 2",
15
payload: {
16
nextDialogstateId: args.addHtmlDs,
17
params: [
18
// This will be set on the session.
19
{ key: "choice", value: "option1" },
20
],
21
},
22
},
23
];
24
​
25
ChatlayerResponseBuilder()
26
.addQuickReplies({
27
title: 'How can we help you?', // this is the title of the Quick Replies
28
quickReplies,
29
})
30
.send();
Copied!

addButtonGroup

With bot messages we can also add buttons, but with code there is more variety than the bot message.
These buttons are created with the code below
1
const invoices = [
2
"123",
3
"456",
4
"789"
5
]
6
​
7
const buttons = invoices.map((invoiceNumber, index) => ({
8
type: 'postback',
9
title: 'Choose ' + invoiceNumber,
10
payload: {
11
nextDialogstateId: args.nextDialogstate,
12
params: [
13
{ key: 'chosenNumber', value: invoiceNumber },
14
],
15
},
16
}));
17
​
18
ChatlayerResponseBuilder()
19
.addButtonGroup({
20
title: "These 'postback' buttons can be used to navigate to a certain bot dialog and set a variable when a users clicks on them.",
21
buttons,
22
})
23
.addButtonGroup({
24
title: 'You can also add URL buttons.',
25
buttons: [
26
{ type: 'web_url', title: 'docs', url: 'https://docs.chatlayer.ai' },
27
{ type: 'phone_number', title: 'Call 1207', payload: '1207'}
28
]
29
})
30
.send();
Copied!
Here, the 'invoices' are the different button options displayed. With the .addButtonGroup you can add these buttons or create URL buttons.

Add HTML or Iframe

HTML can de added in the chatbot to show more diverse output to the user.
1
ChatlayerResponseBuilder()
2
.addHtml(`
3
<h1>This is a header</h1>
4
<p>Unfortunately, html messages will only work on the web widget.</p>
5
`, { withBalloon: true })
6
.send();
Copied!
Iframes can be used to embed other pages in the chatbot. A perfect example of why you would need an iframe is embedding Youtube videos.
1
ChatlayerResponseBuilder()
2
.addIframe("https://www.youtube.com/watch?v=yaYzSQn9rL4", {
3
withBalloon: false,
4
height: "200px"
5
})
6
.send();
Copied!

Add media

The addMediaMessage method supports sending images, audio & video files through code actions.
1
// Send an image
2
ChatlayerResponseBuilder()
3
.addMediaMessage({
4
type: "image",
5
url: "<IMAGE_URL>"
6
})
7
.send();
8
​
9
// Send an audio file
10
ChatlayerResponseBuilder()
11
.addMediaMessage({
12
type: "audio",
13
url: "<AUDIO_URL>"
14
})
15
.send();
16
​
17
// Send a video
18
ChatlayerResponseBuilder()
19
.addMediaMessage({
20
type: "video",
21
url: "<VIDEO_URL>"
22
})
23
.send();
Copied!

Utility library and API calls

The following functionality exists inside the Code action's scope:

lodash (_)

Lodash is a JavaScript utility library. You can find more info here.
1
const introductionDialogstate = _.get(args, 'introductionDialogstate');
2
​
3
const chatlayer = ChatlayerResponseBuilder();
4
chatlayer.setNextDialogState(introductionDialogstate);
5
chatlayer.send();
Copied!

fetch

Fetch allows you to perform API calls. We use node-fetch as the default fetch library.
1
const url = 'https://gorest.co.in/public/v1/users';
2
const response = await fetch(url).then((res) => {
3
// res.status >= 200 && res.status < 300
4
if (res.ok) {
5
return res;
6
} else {
7
throw new Error(res.statusText);
8
}
9
});
10
​
11
const json = await response.json();
12
​
13
const person = _.get(json, 'results[0]');
14
​
15
const chatlayer = ChatlayerResponseBuilder();
16
chatlayer.addSessionVariable('profile', userProfile);
17
chatlayer.send();
Copied!

Creating a slight delay between bot messages

Sometimes you want to create a slight delay between bot messages, either to create a natural pauze between them or because you need a few seconds to make an API call and don't want the bot to just be silent. Either way, slight pauzes can improve the user experience a lot.
To create a short delay of two seconds, add an 'Action' dialog and paste the following code:
1
const builder = ChatlayerResponseBuilder();
2
​
3
await new Promise((resolve)=>{_.delay(resolve,2000)});
4
builder.send();
Copied!
You can adjust the length of the delay by replacing the 2000 with 3000 (3 seconds) etc.
Last modified 1mo ago