Chatlayer Documentation
Get in touchAbout Chatlayer
  • Welcome
  • What's new
  • Send feedback
  • start quickly
    • Leadzy tutorial
      • 0. Introduction
      • 1. New bot, new block
      • 2. Understand your users
      • 3. Collect and display user input
      • 4. Steer the conversation with Conditions
      • 5. Empower your bot with Actions
      • 6. Set up a channel and publish your bot
    • Templates
      • Banking
      • E-Commerce Returns
      • E-Bike Shop
      • E-Scooter Support
      • Feedback
      • Find Nearest Location
      • GPT
      • 🆕Gym
      • Job applications
      • Knowledge base AI template
      • Lead generation
      • 🆕NPS
      • Restaurant
      • Retail
  • navigation
    • Analytics
      • Dashboard
      • Customers
      • Conversations
      • User flow
      • Intents
      • 🆕Funnels [Beta]
    • Bot builder
      • Flows
        • Canvas functionalities
        • Collaborate with team members
        • Manage your flows
        • 🆕[Beta] Export and import flows
      • Bot dialogs view
      • Translations
      • Events
    • NLP
      • Dashboard
      • Intents
      • Expressions
      • Entities
      • Train
      • NLP settings
      • Improve
    • Knowledge base AI
      • Add content to your KBAI
      • Build your KBAI flow
      • Use your KBAI source URL in a button
      • Use tags to limit your KBAI content
      • 🆕Use Tables to store your KBAI questions
      • 🆕Manage handover where KBAI is unsatisfactory
    • History
      • Conversations
      • Execution logs
      • Versions
    • Channels
    • Tables
      • Create a table with records
      • Column types
      • Operate on your records
        • Insert record
        • Update record
        • Retrieve record
        • Delete record
      • API
    • Settings
      • Bot settings
      • Offloading
      • Variables
      • Voice
      • Import/Export
  • build your bot
    • Conversation design
      • Plan your bot
      • Conversation design workflow
    • Flow logic
      • Blocks
        • Message
        • Condition
        • Collect input
        • Action
      • Go-to connections
    • 🆕Emulator
    • Tips & best practices
      • Route your flow depending on the time
      • Improve the Not understood block
        • How to create better not understood messages
        • Not understood counter
        • Not understood Google search
      • Go to previous block
      • Recognizing a returning user
      • Skip introduction message
      • Route your flow depending on the channel
      • Reuse flows
      • Connect two bots to each other
  • understand users
    • Natural language processing (NLP)
      • Basic NLP concepts
      • Detect information with entities
        • Match entities
        • Contextual entities
        • System entities
        • Composite entities
      • NLP best practices
        • Word order and diversity of expressions
      • AI intent booster
      • Train your NLP
      • Context
      • NLP import & export
      • Sentiment analysis
    • Languages
      • Supported languages
      • Make your bot multilingual
      • Change language within the conversation
  • set up channels
    • Add a channel to your bot
    • All channels
      • 🚨Facebook Messenger [Deprecated soon]
        • Facebook Admin Removal
        • Facebook Webview Whitelisting
        • Facebook Messenger API updates for Europe
      • 🚨Google Assistant [Deprecated soon]
      • Webhook
      • Web
        • 🚨Web V1 [Deprecated]
          • Customize web widget
          • Live example web widget
        • 🆕Web V2
          • 🆕From Web V1 to V2
          • 🆕Web V2 methods and options
    • Sinch Conversation API
      • Configure your Sinch Conversation API
      • 🆕 Make the most of RCS with Carousels
      • WhatsApp Business API
  • integrate & code
    • API calls
      • Configure your API integration
      • Advanced API features
      • V1 API Reference
      • Custom integrations 101
    • Code editor
      • [Example] Sending data to Airtable (POST)
      • [Example] Retrieving data from Airtable (GET)
      • [Example] Making SOAP requests
    • App integrations
      • Airtable
      • Freshdesk
      • Freshdesk Messaging
      • 🆕Gmail
      • Intercom
      • Mailgun
      • OpenAI: GPT-3, ChatGPT and GPT-4
      • Salesforce
      • 🆕Slack
      • Topdesk
      • Zendesk Support
      • Zendesk Sunshine (beta)
    • 🆕Expression syntax
    • Human handover & live chat
      • Sinch Contact Pro
      • #Interact
      • Genesys Cloud
      • Offloading Webhook
      • Salesforce Service Cloud
      • Sparkcentral by Hootsuite
      • Zendesk Chat
    • Chatlayer messages specifications
  • Publish
    • Publish your bot
      • Publish a flow
  • Analyze & maintain
    • Analytics definitions
    • Data retention
    • Maintenance
    • Session
    • Track events for analytics
  • VOICE
    • 🆕Send bot response as audio
    • Voicebots
      • Create a voicebot
      • Voicebot-specific actions
      • Test your voicebot
      • From chat to voice
  • access & support
    • Identity & Access
      • Single Sign-On (SAML SSO)
    • Billing & subscription
    • Get in touch
    • Chatlayer glossary
    • SaaS Regions & IP Ranges
    • Status
    • Debug your bot
      • No correct response
      • Collect input not working
      • Video isn't working
Powered by GitBook
On this page
  • Getting Started
  • ChatlayerResponseBuilder function
  • Next or previous blocks
  • Bot Message functionalities
  • Add HTML or Iframe
  • Add media
  • Utility library and API calls
  • Creating a slight delay between bot dialogs

Was this helpful?

  1. integrate & code

Code editor

Learn how to steer the conversation by writing JavaScript code with the Code Action.

PreviousCustom integrations 101Next[Example] Sending data to Airtable (POST)

Last updated 9 months ago

Was this helpful?

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.

Please note that the term dialog state refers to the same thing as block, in the context of development tools.

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 blocks, 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.

ChatlayerResponseBuilder()
    .addSessionVariable("user", { address: { ... } })
    .addMessage("Thank you for sharing your address!")
    .send();

Another way to accomplish the same result:

const builder = ChatlayerResponseBuilder();
builder.addSessionVariable("user", { address: { ... } });
builder.addMessage("Thank you for sharing your address!");
builder.send();

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.

ChatlayerResponseBuilder()
    .addSessionVariable("user", 'Joachim')
    .addMessage("addSessionVariable done.")
    .send();

To enhance your variables even more, you can store multiple variables about the user in an object.

ChatlayerResponseBuilder()
    .addSessionVariable("user", { firstName: "Joachim", lastName: "Chatbot" })
    .send();

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 blocks

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.

const { introductionDialogstate } = args;

const chatlayer = ChatlayerResponseBuilder();
chatlayer.setNextDialogState(introductionDialogstate);
chatlayer.send();

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 Messages. This can be of added value when dynamic content needs to be shown or to combine a Message and Action block in one.

ChatlayerResponseBuilder().addCarousel([
    {
        title: 'Item 1',
        imageUrl: 'https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg',
        buttons: [
            { type: 'web_url', url: 'https://docs.chatlayer.ai', title: 'Docs' }
        ]
    },
    {
        title: 'Item 2',
        // This is optional
        subTitle: 'Item 2 Subtitle',
        // This is also optional, it will redirect a user to a certain website when they click the carousel image
        webUrl: 'https://docs.chatlayer.ai',
        imageUrl: 'https://st.depositphotos.com/1708346/1858/i/600/depositphotos_18582903-stock-photo-carousel-at-night.jpg',
        buttons: [
            { type: 'web_url', url: 'https://docs.chatlayer.ai', title: 'Docs' }
        ]
    }
]).send();

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.

const quickReplies = [
[
  {
    title: "Option 1",
    payload: {
      nextDialogstateId: args.setNextDialogstateDs,
      params: [
        // This will be set on the session.0
        { key: "choice", value: "option1" },
      ],
    },
  },
  {
    title: "Option 2",
    payload: {
      nextDialogstateId: args.addHtmlDs,
      params: [
        // This will be set on the session.
        { key: "choice", value: "option1" },
      ],
    },
  },
];

ChatlayerResponseBuilder()
    .addQuickReplies({
        title: 'How can we help you?', // this is the title of the Quick Replies
        quickReplies,
    })
    .send();

addButtonGroup

With bot messages we can also add buttons, but with code there is more variety than the bot message.

const invoices = [
 "123",
 "456",
 "789"
]

const buttons = invoices.map((invoiceNumber, index) => ({
    type: 'postback',
    title: 'Choose ' + invoiceNumber,
    payload: {
        nextDialogstateId: args.nextDialogstate,
        params: [
            { key: 'chosenNumber', value: invoiceNumber },
        ],
    },
}));

ChatlayerResponseBuilder()
    .addButtonGroup({
        title: "These 'postback' buttons can be used to navigate to a certain bot dialog and set a variable when a users clicks on them.",
        buttons,
    })
    .addButtonGroup({
        title: 'You can also add URL buttons.',
        buttons: [
            { type: 'web_url', title: 'docs', url: 'https://docs.chatlayer.ai' },
            { type: 'phone_number', title: 'Call 1207', payload: '1207'}
        ]
    })
    .send();

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.

ChatlayerResponseBuilder()
    .addHtml(`
        <h1>This is a header</h1>
        <p>Unfortunately, html messages will only work on the web widget.</p>
    `, { withBalloon: true })
    .send();

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.

ChatlayerResponseBuilder()
    .addIframe("https://www.youtube.com/watch?v=yaYzSQn9rL4", {
        withBalloon: false,
        height: "200px"
    })
    .send();

Add media

The addMediaMessage method supports sending images, audio & video files through code actions.

// Send an image
ChatlayerResponseBuilder()
    .addMediaMessage({
        type: "image",
        url: "<IMAGE_URL>"
    })
    .send();

// Send an audio file
ChatlayerResponseBuilder()
    .addMediaMessage({
        type: "audio",
        url: "<AUDIO_URL>"
    })
    .send();

// Send a video
ChatlayerResponseBuilder()
    .addMediaMessage({
        type: "video",
        url: "<VIDEO_URL>"
    })
    .send();

Utility library and API calls

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

lodash (_)

const introductionDialogstate = _.get(args, 'introductionDialogstate');

const chatlayer = ChatlayerResponseBuilder();
chatlayer.setNextDialogState(introductionDialogstate);
chatlayer.send();

fetch

const url = 'https://gorest.co.in/public/v1/users';
const response = await fetch(url).then((res) => {
    // res.status >= 200 && res.status < 300
    if (res.ok) {
        return res;
    } else {
        throw new Error(res.statusText);
    }
});

const json = await response.json();

const person = _.get(json, 'results[0]');

const chatlayer = ChatlayerResponseBuilder();
chatlayer.addSessionVariable('profile', userProfile);
chatlayer.send();

CryptoJS

Creating a slight delay between bot dialogs

To create a delay in between the integer seconds, like 1500 miliseconds or 1,5 seconds, add a Code widget to your action instead of the Delay pictured above and paste the following code:

const builder = ChatlayerResponseBuilder();

await new Promise((resolve)=>{_.delay(resolve,1500)});
builder.send();

You can adjust the length of the delay by replacing the 1500 with 2500 (2,5 seconds) etc.

Lodash is a JavaScript utility library. You can find more info .

Fetch allows you to perform API calls. Please refer to their to learn more.

CryptoJS is a collection of standard and secure cryptographic algorithms implemented in JavaScript. Please access their to learn more.

We recommend using the delay block to create a delay between bot dialogs. You can learn more about how that works here:

here
documentation
documentation
These buttons are created with the code below
Delay