| Developers Guide

| Developers Guide

  • Docs
  • API
  • Help
  • Blog

›Channels

Notes on Versions Released

  • Migrating & Updating
  • Updating to New Releases

Getting Started

  • Introduction
  • Installation
  • Quick Start

Main Concepts

  • Overview
  • Glossary
  • CMS
  • Dialog Engine
  • Actions & Hooks
  • Memory
  • Modules
  • NLU
  • Emulator

Advanced Guides

  • Debug
  • Configuration
  • Authentication Methods
  • Custom Module
  • Performances
  • Hosting
  • Version Control
  • Development Pipelines
  • Clustering

Channels

  • Website Embedding
  • Facebook Messenger
  • Telegram
  • Microsoft Teams
  • Converse API
  • Slack
  • Smooch (Sunshine Conversations)
  • FAQ

Tutorials

  • Deploying a cluster on Digital Ocean
  • How to act on an intent
  • Acting Proactively
  • Using Carousel Postback
  • How to use Slot Skill
  • How to use Call API Skill
  • Calling an API in a Custom Action
  • Shortlinks
  • Connecting your bot with your existing backend
  • Supported databases
  • Timeouts
  • Human in the loop
  • Jump To
  • Inter-bot Communication / Delegation
  • Contextual FAQ
  • Authenticate a user against a 3rd Party OAuth
  • Listening for file changes
  • Using a 3rd party NLU
  • Using the UiPath integration for Botpress

Pro Edition

  • About
  • Licensing
  • Configuring RBAC
  • Monitoring & Alerting
  • Bot Pipelines
  • Internationalization

Website Embedding

Embedding

Embedding a chatbot to a website is relatively straightforward. As long as your chatbot is hosted on a physical or virtual server and is accessible via a URL, you can connect and embed it to a website. Add the following script tag to the end of your index.html (or the default webpage, whichever it's named).

Remember to replace <your-url-here> with the URL of your bot!

<script src="<your-url-here>/assets/modules/channel-web/inject.js"></script>

After the import script above, you need to locate and use the chatbot by initializing it to the window object:

<script>
  window.botpressWebChat.init({ host: '<your-url-here>', botId: '<your-bot-id>' })
</script>

That's it! Once you add these changes and save them to your website, the bot will become available, and its button will appear on your site the next time you browse it.

There is an example in the default botpress installation at http://localhost:3000/assets/modules/channel-web/examples/embedded-webchat.html

Additional Options

PropertyDescription
refThe trusted reference of the user origin (generated by security sdk)

Bot Information page

The information page displays information like the website URL, a phone number, an e-mail contact address, and links to terms of services and privacy policies. You can also include a cover picture and an avatar for your bot.

Bot Info Page

How to set up the information page:

  1. On the Admin UI, click on the link Config next to the name of the bot you want to change.
  2. Edit your bot information in the More details and Pictures sections.
  3. Edit the file data/global/config/channel-web.json and set showBotInfoPage to true **
  4. Refresh your browser.

You will see the page when starting a new conversation. The page is always accessible by clicking on the information icon in the top right corner of the chat window.

** We edited the global configuration file for the sake of simplicity. To enable the bot information page on a single bot, visit that bot's studio UI and select config (the last icon on the left-side menu with a cog).

Show and hide automatically

If the default Botpress button doesn't work for you, pass the hideWidget key to your init function. By so doing, the default chat button will not show up on your website.

<script>
  window.botpressWebChat.init({ host: '<your-url-here>', botId: '<your-bot-id>', hideWidget: true })
</script>

You can then add a click event listener to any element on your web page. Below is a code sample showing how to add event listeners to your custom elements.

<script>
  document.getElementById('show-bp').addEventListener('click', () => {
    window.botpressWebChat.sendEvent({ type: 'show' })
    window.botpressWebChat.sendEvent({ type: 'message', text: 'Hello!' })
  })
  document.getElementById('hide-bp').addEventListener('click', () => {
    window.botpressWebChat.sendEvent({ type: 'hide' })
  })
</script>

Events Available

Obtaining visitor's User ID

The most widely used object property under events is userId. It fetches the current visitor ID to either save it in your database or update some Botpress DB attributes.

Since the webchat is running in an iframe, posting messages can achieve communication between frames. The chat will dispatch an event when a user id is set. You can listen for this event on your page.

window.addEventListener('message', message => {
  if (message.data.userId) {
    console.log(`The User ID is ` + message.data.userId)
    //Add code to use the user ID here
  }
})

Other Events

There are more events you can trigger by calling the window.botpressWebChat.sendEvent() function. Below are some of them:

nameDescription
showThis event opens the webchat
hideThis event closes the webchat
toggleThis event open or close the webchat depends on its current state
messageThis event sends a message (see example above)
toggleBotInfoThis event switches between bot infos and conversation page

Show

The following function shows the chat window when you click the show-bp element.

      document.getElementById('show-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'show' })
      })

Hide

The following function hides the chat window when you click the hide-bp element.

      document.getElementById('hide-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'hide' })
      })

Toggle

The following function includes a ternary operator that toggles the chat to either be hidden or shown when you click the toggle-bp element.

      document.getElementById('toggle-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: webchatOpen ? 'hide' : 'show' })
      })

Message

The following function lets you programmatically send a message to the user when you click the send-message-bp element.

      document.getElementById('send-message-bp').addEventListener('click', function() {
        window.botpressWebChat.sendEvent({ type: 'message', text: 'Hello!' })
      })

Runtime configurations

The method window.botpressWebChat.configure allows you to change the chat's configuration during a conversation without having to reload the page.

The example below shows how you can change the chatbot's language to French when you click change-lang-bp on your website.

      document.getElementById('change-lang-bp').addEventListener('click', function() {
        lastConfig.locale = 'fr'
        window.botpressWebChat.configure(lastConfig)
      })

Advanced Customization

All messages which the bot sends to a user consist of a payload. That payload has a type property that tells the webchat how the other information included on that payload should be rendered on screen.

There are different ways to send that payload to the user:

  • Sending a Content Element via the Flow Editor example here
  • Sending an event via Hooks or Actions (https://github.com/botpress/botpress/blob/master/examples/custom-component/src/hooks/after_incoming_middleware/sendoptions.js)

There are multiple types already built-in Botpress (these are listed at the bottom of this page), but you can create them easily if you require more advanced components.

Prevent storing sensitive information

By default, the complete payload is stored in the database, so the information is not lost when the user refreshes the page. However, on some occasions, we may want to hide some properties deemed "sensitive" (ex: password, credit card, etc..).

To remove this information, there is a special property that you need to set: sensitive. Here's an example:

const payload = {
  type: 'login_prompt',
  username: 'someuser',
  password: 'abc123',
  sensitive: ['password']
}

// This is the information that will be persisted: { type: 'login_prompt', username: 'someuser' }

Changing avatar for messages

If you need to display a different bot's avatar for some of the messages (like imitating changing author), you can achieve that by setting botAvatarUrl like this:

"`js const payload = { type: 'text', botAvatarUrl: 'http://some.url' text: 'Lorem ipsum' }


## Creating a Custom Component

We already have an [example module](https://github.com/botpress/botpress/tree/master/examples/custom-component) showing how to create them. We will make a quick recap here. The Debugger is implemented entirely as a custom component in the [extensions module](https://github.com/botpress/botpress/tree/master/modules/extensions/src/views/lite/components/debugger), so don't hesitate to take a look at how it was implemented there.

Custom components leverage the `custom` payload type, which allows you to inject any valid React component exported from a custom module.

1. Create a module (we have [example templates here](https://github.com/botpress/botpress/tree/master/examples/module-templates))
2. Develop your component
3. Export your component in the `lite.jsx` file ([here's a couple of different ways to do it](https://github.com/botpress/botpress/blob/master/examples/custom-component/src/views/lite/index.jsx))
4. Send a custom payload to the user:

"`js
payload: {
  type: 'custom' // Important, this is how the magic operates
  module: 'myModule'// The name of your module, must match the one in package.json
  component: 'YourComponent'// This is the name of the component, exported from lite.jsx
  // Feel free to add any other properties here, they will all be passed down to your component
  myCustomProp1: 'somemorestuff'
  someOtherProperty: 'anything'
}

Component Properties

A couple of properties are passed down to your custom component. These can be used to customize the displayed information and/or to pursue interactions.

PropertyDescription
...propsThe payload properties are available on the root object (this.props.)
onSendDataThis method can be used to send a payload to the bot on behalf of the user
onFileUploadInstead of sending an event, this will upload the specified file
sentOnThis is the timestamp of the message.
isLastGroupIndicates if your component is part of the group of messages sent by the bot
isLastOfGroupIndicates if your component is the last message in its group
keyboardThis object allows you to manipulate the keyboard (more below)
wrappedRepresent any child components (more below)
incomingEventIdThe ID of the incoming event which was processed
storeGrants access to the MOBX store of Channel Web (more on that below)

isLastGroup and isLastOfGroup can be combined to let your component know if the current message is the last one the user is seeing. This can be used, for example, to display feedback buttons, a login form, or anything else, that will disappear when the user continues the discussion.

The Store

The store orchestrates everything happening on the webchat: whether those buttons are displayed, which page is currently displayed, how to handle configuration changes, etc. This means that your component has a lot of flexibility. Here's a sample of the methods that you can use click here to see all of them:

  • Hide or Show the chat
  • Add or Remove header buttons
  • Change the size of the chat window
  • Send messages or payloads
  • Create a new conversation
  • Update any configuration option
  • Set a wrapper that will wrap every single message (more on that below)

Anything you can do while clicking on the UI can be done by your component.

Injecting your components

Some components can be replaced by your own. There are also some placeholders that don't have any components, but you can inject yours. When you inject a component, it will receive the original component, so you can wrap it or change it completely. If there's a problem with your component, it will be replaced by the original one.

LocationDescription
below_conversationThis component would be displayed just below the composer
before_containerThis is displayed before the chat container (the debugger uses it)
composerThis allows you to replace the zone where the user is typing

How to configure them:

window.botpressWebChat.init({
...
  overrides: {
    before_container: [
      {
        module: 'extensions',
        component: 'Debugger'
      }
    ]
  }
})

Wrappers

Wrappers allow you to transform a payload's content before passing it down to the renderer or another component. We have some example components here

Here's an example of a wrapped text message:

payload: {
  type: 'custom',
  module: 'myModule',
  component: 'MyComponent'
  wrapped: {
    type: 'text'
    text: 'Hello user!'
  }
}

It is also possible to chain multiple custom components using the wrapped property.

Keyboards

The keyboard allows you to add elements before or after the composer. Keyboard items can be buttons or any other type of valid component. Use Keyboard.Prepend to display it before the composer, and Keyboard.Append to display it after.

"`js ... render(){ // First of all, import the keyboard object const Keyboard = this.props.keyboard

// Create any type of component const something =

This will be displayed over the composer, as long as visible is true

// Your custom keyboard will only be displayed if that message is the last one displayed const visible = this.props.isLastGroup && this.props.isLastOfGroup

return ( <Keyboard.Prepend keyboard={something} visible={visible}> This text will be displayed in the chat window </Keyboard.Prepend>à ) }


##### Using a Button Keyboard

There is a built-in hook that makes it easy to add buttons to any element. You can pass down an array of buttons or an array of array of buttons.

```js
const payload = {
  type: 'text'
  text: 'hello',
  quick_replies: [
      [{ label: 'row 1, button 1', payload: 'something' }, { label: 'row 1, button 2', payload: 'something' }],
      [{ label: 'row 2, button 1', payload: 'something' }],
      [{ label: 'row 3, button 1', payload: 'something' }]
    ]
}

Customizing Web Chat Style

Step 1: Styling (CSS)

Paste the following CSS file in the <botpress_dir>/data/assets/modules/channel-web folder. Feel free to change the style here—original Botpress theme can be found here.

.bpw-from-bot .bpw-chat-bubble {
  background-color: #ececec;
}

.bpw-chat-bubble:last-of-type {
  border-bottom-right-radius: 20px;
  border-bottom-left-radius: 20px;
}

.bpw-chat-bubble:first-of-type {
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.bpw-from-user .bpw-chat-bubble:last-of-type {
  border-bottom-right-radius: 0px;
}

.bpw-from-bot .bpw-chat-bubble:last-of-type {
  border-bottom-left-radius: 0px;
}

.bpw-from-user .bpw-chat-bubble {
  background-color: #4278f3;
  color: #ffffff;
}

.bpw-date-container .bpw-small-line {
  border-bottom: none;
}

.bpw-date-container {
  font-weight: 700;
  font-size: 14px;
}

.bpw-header-container {
  background-color: #f8f8f8;
  border-bottom: none;
}

.bpw-bot-avatar img,
.bpw-bot-avatar svg {
  border: none;
  border-radius: 50%;
}

.bpw-composer {
  padding: 10px;
  background: none;
  border: none;
}

.bpw-composer textarea {
  background: #ececec;
  border-radius: 20px;
  font-size: 1.25rem;
  overflow: hidden;
}

.send-btn {
  position: absolute;
  right: 30px;
  bottom: 28px;
  border: none;
  border-radius: 5px;
  background: #fff;
  padding: 5px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}

.send-btn:hover {
  background: #d8d8d8;
}

Step 2: Loading CSS File

Now, we need to instruct Botpress to use this custom CSS file for theming the webchat. For this, place the following code snippet in the <botpress_dir>/data/global/hooks/after_bot_mount folder. In our case, we used 01_create_shortlink.js as the file name.

const chatOptions = {
  hideWidget: true,
  config: {
    enableReset: true,
    enableTranscriptDownload: true,
    extraStylesheet: '/assets/modules/channel-web/chat.css'
  }
}

const params = {
  m: 'channel-web',
  v: 'Fullscreen',
  options: JSON.stringify(chatOptions)
}

setTimeout(() => {
  try {
    bp.http.deleteShortLink(botId)
  } catch (e) {}

  // Bot will be available at $EXTERNAL_URL/s/$BOT_NAME
  bp.http.createShortLink(botId, `${process.EXTERNAL_URL}/lite/${botId}/`, params)
}, 500)

Feel free to change the webchat config there; the critical line to keep is the extraStylesheet property.

Result

Restart Botpress Server, and now your bot's default webchat will use your custom CSS theme! Here's our example: WebChat Customization

← ClusteringFacebook Messenger →
  • Embedding
    • Additional Options
  • Bot Information page
  • Show and hide automatically
  • Events Available
    • Obtaining visitor's User ID
    • Other Events
  • Runtime configurations
  • Advanced Customization
    • Prevent storing sensitive information
    • Changing avatar for messages
    • Component Properties
    • The Store
    • Injecting your components
    • Wrappers
    • Keyboards
  • Customizing Web Chat Style
    • Step 1: Styling (CSS)
    • Step 2: Loading CSS File
  • Result
| Developers Guide
Docs
Getting Started (or other categories)Guides (or other categories)API Reference (or other categories)
Community
User ShowcaseStack OverflowProject ChatTwitter
More
BlogGitHubStar
Facebook Open Source
Copyright © 2021 Botpress Inc.