Controlling Web Chat using JavaScript

Controlling the Webchat Widget

This library is a toolkit that provides various tools (or functions) to interact with the Botpress Webchat.

window.botpressWebChat = {

Initializing the Widget

This function initializes the webchat and connects it to your bot. You must do this before anything else.

  botId: '<botID>',
  hostUrl: '',
  messagingUrl: '',
  clientId: '<clientID>',

You can find information on the configuration parameters here.

Changing the Widget's Configuration

After initializing the widget, if you want to update it, send a configuration object for the changes you want. You don't need to re-include everything else.

window.botpressWebChat.mergeConfig({ showTimestamp: false })

You can find information on the configuration parameters here.

Send user data from your website to Botpress

You can send data from your website to the webchat using the init function. Important : the mergeConfig doesn't allow you to pass user data.
To send information, submit a flat (without nested objects) object to the userData property.

  userData: {
    name: 'Jack Black',
All the parameters sent to the userData object should be string typed.

You can receive data from the webchat in Botpress by using Get User Data Card in the flow. In the User ID field, add {{event.userId}}.

Trigger Widget Actions

This function allows you to send a custom event to the chat. Think of it as sending a signal to the chat for it to do something specific.

// Show the chat
window.botpressWebChat.sendEvent({ type: 'show' })

// Hide the chat
window.botpressWebChat.sendEvent({ type: 'hide' })

// Toggle the chat
window.botpressWebChat.sendEvent({ type: 'toggle' })

// Toggle the bot info page
window.botpressWebChat.sendEvent({ type: 'toggleBotInfo' })

// Create a new conversation
window.botpressWebChat.sendEvent({ type: 'createConversation' })

// Load a conversation by ID
window.botpressWebChat.sendEvent({ type: 'loadConversation', conversationId: '6ffe8622-49fd-4de9-81e5-412ba2296913' })

To load a conversation, you must provide the conversation ID. You can get the conversation ID from the event payload of a MESSAGE.SENT event.

Sending messages or instructions from your website

You can use the sendPayload function to send a specific message (or instruction) to the chatbot. For sending instructions, please refer to Triggers.

window.botpressWebChat.sendPayload({ type: 'text', text: 'I am a message sent through code' })

You can see examples of all of the message types you can send to the chatbot here.

Listening to Widget Events

This function lets you listen for certain events happening in the chat and then do something when they happen. It's like setting up a watch for specific actions.
You can find the list of events here.

  (event) => {
    if (event.type === 'MESSAGE.RECEIVED') {
      console.log('A new message was received!')

Next Steps