Rasa Webchat

repository·master·Indexed 21 days ago

https://github.com/botfront/rasa-webchat

A chat web widget for React apps and Rasa Core or Botfront chatbots. It supports text, quick replies, images, carousels, and markdown. The widget can be embedded via a script tag or used as a React component, featuring customizable UI props, socket event handling, and a rules engine for triggering messages based on user behavior such as URL patterns or time on page.

Tokens
10.7K
Snippets
27
Records
38
Agent score
73%

What's inside rasa-webchat

  1. Install and use Rasa Webchat as a React component

    master

    To use the widget in a React application, install the package via npm and import the Widget component.

    Key Props:

    • initPayload: The initial message sent to the bot (e.g., /get_started).
    • socketUrl: The URL of your socket server.
    • socketPath: The path to the socket.io endpoint.
    • customData: An object containing arbitrary data to be sent over the socket. Keep this minimal.
    • title: The title displayed in the widget.
    • embedded: Set this prop to true if you want to hide the launcher icon and show the widget directly.
    npm install rasa-webchat
    import Widget from 'rasa-webchat';
    
    function CustomWidget = () => {
      return (
        <Widget
          initPayload={"/get_started"}
          socketUrl={"http://localhost:5500"}
          socketPath={`/socket.io/`}
          customData={{"language": "en"}} // arbitrary custom data. Stay minimal as this will be added to the socket
          title={"Title"}
        />
      )
    }
  2. Integrate with Rasa and Botfront backends

    master

    Rasa

    Use the socketio channel. To process customData in Rasa, you must create a custom channel using rasa_core.channels.socketio as a template. In your custom channel, customData is accessible via data['customData'].

    Botfront

    If using Botfront with a multilingual bot, you must specify the language in the customData prop.

    Example for Botfront:

    customData={{language: 'en'}}
  3. Install and use Rasa Webchat via a `<script>` tag

    master

    You can embed the chat widget into any website by injecting a script tag into the <body>. This method loads the widget from a CDN.

    Important Versioning Note:

    • Use version 1.0.1 for Rasa 2.3.x and 2.4.x.
    • Use version 1.0.0 for other Rasa versions.
    • It is highly recommended to specify a version in the URL (e.g., @1.0.0) to prevent breaking changes. If no version is specified, the latest version will be served.

    Image Scaling: If you provide width and height in the configuration, images in messages will be crop-scaled to those pixel dimensions. If omitted, images scale to the maximum width of the container and the image itself.

    <script>
    !(function () {
      let e = document.createElement("script"),
        t = document.head || document.getElementsByTagName("head")[0];
      (e.src = "https://cdn.jsdelivr.net/npm/rasa-webchat@1.x.x/lib/index.js"),
        // Replace 1.x.x with the version that you want
        (e.async = !0),
        (e.onload = () => {
          window.WebChat.default(
            {
              customData: { language: "en" },
              socketUrl: "https://bf-botfront.development.agents.botfront.cloud",
              // add other props here
            },
            null
          );
        }),
        t.insertBefore(e, t.firstChild);
    })();
    </script>
  4. Define Rules and Triggers

    master

    Rules allow the webchat to automatically send messages based on user behavior. A rule consists of a payload (the message to send) and a trigger object.

    Supported trigger conditions include:

    • url: Match specific URLs or patterns.
    • timeOnPage: Time spent on the page.
    • numberOfVisits / numberOfPageVisits: Frequency of visits.
    • device: Specific device types.
    • when: Set to 'always' or 'init'.
    • queryString: Match specific URL parameters.
    • eventListeners: Trigger based on DOM events (e.g., clicks) using a CSS selector and an event name.
    rules: [
      {
        payload: 'Hello! Welcome back.',
        trigger: {
          when: 'always',
          url: '/contact-us'
        }
      },
      {
        payload: 'Need help?',
        trigger: {
          timeOnPage: 30000, // 30 seconds
          eventListeners: [
            { selector: '.help-button', event: 'click' }
          ]
        }
      }
    ]
  5. Configure conversation storage location

    master

    To specify where the conversation state is stored in the browser, use the storage key inside the params object.

    Supported values:

    • "local": Uses localStorage. Persists after the browser is closed. Cleared when cookies are cleared or localStorage.clear() is called.
    • "session": Uses sessionStorage. Persists on page reload but is cleared when the tab or browser is closed, or when sessionStorage.clear() is called.
    params={{
      storage: 'local' // or 'session'
    }}
  6. Customize message display delay

    master

    Use the customMessageDelay prop to control how long the widget waits before showing a received message. The function receives the message string and must return a number representing milliseconds.

    (message) => {
        let delay = message.length * 30;
        if (delay > 2 * 1000) delay = 3 * 1000;
        if (delay < 400) delay = 1000;
        return delay;
    }
  7. Send messages programmatically from a React app

    master

    To trigger a message from your React application, use a ref to access the RasaWebchat component instance and call its sendMessage method.

    You can send plain text or force an intent with entities using the format: /intentName{"entityName":"value"}.

    function myComponent() {
        const webchatRef = useRef(null);
        
        function callback() {
            if (webchatRef.current && webchatRef.current.sendMessage) {
                // Sends a message with a forced intent and entity
                webchatRef.current.sendMessage('/myIntent{"entityName":"value"}');
            }
        }
        
        return (
            <>
                <button onClick={callback}>Send Intent</button>
                <RasaWebchat ref={webchatRef} />
            </>
        );
    }
  8. Handle socket and widget events

    master

    You can trigger custom code based on socket events or widget lifecycle events using onSocketEvent and onWidgetEvent.

    Socket Events include 'bot_uttered', 'connect', and 'disconnect'.

    Widget Events include 'onChatOpen', 'onChatClose', and `'onChatHidden' .**

    // Example socket events
    onSocketEvent={{
      'bot_uttered': () => console.log('the bot said something'),
      'connect': () => console.log('connection established'),
      'disconnect': () => doSomeCleanup(),
    }}
    
    // Example widget events
    onWidgetEvent={{
      onChatOpen: () => console.log('Chat opened'),
      onChatClose: () => console.log('Chat closed'),
    }}
  9. Configure Widget connection and session behavior

    master

    Use these props to control how the widget connects to the server and manages user sessions:

    • connectOn: Determines when the socket connection is established. Options are 'mount' (connect immediately when component mounts) or 'open' (connect when the chat is opened).
    • autoClearCache: If true, the widget checks the age of the local session. If it's older than 30 minutes, it clears the cache.
    • storage: An object used to manage local session storage (interacts with SESSION_NAME).
    • initPayload: A string sent to the bot as a user_uttered event immediately after the widget is initialized and connected.
    • customData: An object sent along with the initPayload and tooltips to provide additional context to the bot.
  10. Customize message rendering and appearance

    master

    The Widget component provides several ways to customize the look and feel of messages and the UI:

    • customComponent: A function used to render a custom React component when a message type is not recognized by the default processor.
    • customMessageDelay: A required function (text: string) => number that returns the delay in milliseconds before a message is displayed. This is used to simulate human typing or controlled pacing.
    • domHighlight: A shape used to highlight specific DOM elements based on metadata received from the bot. It supports style: 'custom' (using css property), style: 'class' (using css property), or default behaviors.
    • defaultHighlightAnimation: A CSS string defining the @keyframes for the default blinking highlight animation.
    • defaultHighlightCss: The CSS applied when no specific highlight class is provided.
    • defaultHighlightClassname: The CSS class name used for highlighting if style: 'class' is specified.
  11. Configure Widget UI and Tooltip settings

    master

    Control the visual elements and tooltips of the chat interface:

    • tooltipPayload: A string sent to the bot as a user_uttered event to trigger a tooltip (e.g., a 'Help' prompt).
    • tooltipDelay: The delay in milliseconds before the tooltipPayload is sent.
    • isChatVisible: Controls whether the chat widget is visible on the screen.
    • isChatOpen: Controls whether the chat window is expanded/open.
    • fullScreenMode: If true, the chat interface occupies the full screen.
    • badge: A number displayed on the launcher to indicate unread messages.
    • inputTextFieldHint: The placeholder text for the message input field (defaults to 'Type a message...').
    • profileAvatar: URL for the user's profile image.
    • showCloseButton / showFullScreenButton: Boolean flags to toggle visibility of these buttons in the header.