XBot
  • Overview
    • Introduction
    • How xBot Works
    • Target Audience
    • Key Benefits of xBot
    • Core Concepts of xBot
  • Quick Start
    • Quick Setup
    • Getting Started
      • Zalo Channel
      • Azure Bot Framework
      • FaceBook Channel
      • Team Channel
      • Webchat Channel
      • Email Channel
    • Basic Configuration
    • First AI Flow Setup
    • Initial Testing and Go Live
  • Features
    • Using xBot to Handle End-User Queries
    • Communication Channels
      • Zalo OA
      • Facebook
      • Teams
      • WebChat
      • Email
    • Understanding the Message Handling Flow
    • Understanding AI Bots in xBot
    • Configuring Dispatch Rules in xBot
    • User Functions and Permissions
      • Custom Roles and Permissions
      • Auditing and Monitoring User Activities
    • Cross-Platform Message Type Compatibility
    • AI Flow
      • Core Concepts
      • AI Services
        • Knowledge Base Agent
        • AI Agent
        • AI Proxy Agent
      • Knowledge Base
      • Functions
      • Evaluation Metrics
        • Essential Information
        • Basic Metrics
        • Extra Metrics
  • Integration Guide
    • Integrates with multiple channels
      • API reference
        • Webhook
          • ZaloPushToXBot
          • AzbotPushToXBot
        • Webchat
          • InitForClient
  • References
    • Industry-Specific Use Cases
      • Media and Entertainment
      • Wholesale
      • Transportation and Logistics
      • Manufacturing
      • Energy and Utilities
      • Real Estate
      • Agriculture
      • Travel and Hospitality
      • Healthcare and Wellness
      • Retail and E-Commerce
      • Public Administration
      • Legal
      • Training
      • Education
      • xBot Use Case: Insurance
      • Securities -Use Case
      • Banking - Use Case
      • xBot Use Case: Finance
Powered by GitBook
On this page
  • Implementation Steps
  • Step 1: Obtain the Bot User Token (TBD)
  • Step 2: Initialize the Chatbot
  • Step 3: Integrate the Chatbot into Your Application
  • React Example
  • Angular Example
  • Customization
  • Example of Custom Style Options:
  • Additional Resources
  1. Features
  2. Communication Channels

WebChat

This guide provides detailed instructions on implementing a chatbot using the Microsoft Bot Framework WebChat JavaScript library. The implementation involves obtaining a token from a backend service a

Implementation Steps

Step 1: Obtain the Bot User Token (TBD)

Use the following endpoint to obtain the bot user token: {host_url}/partner/xpbot/api/webchat/initForClient

To ensure that the backend correctly transmits the information required by the client to initialize the token using the API endpoint provided by XBot. To handle token expiration and refresh the token for the client, you can implement a mechanism that checks the token's expiration time and automatically refreshes it before it expires

Example function to get the token:

import axios from 'axios';

export enum BOT_CODE_ENUM {
    ISIGN = 'ISIGN_WEBCHAT'
}

const getBotToken = async () => {
  try {
    const response = await axios.post('https://initForClient', { 
      botCode: 'YOUR_BOT_CODE' // Defined by Backend, eg: BOT_CODE_ENUM.ISIGN
    });

    return response.data.token;
  } catch (error) {
    console.error('Error fetching bot token:', error);
  }

Step 2: Initialize the Chatbot

Create a function to initialize the chatbot using the Microsoft Bot Framework WebChat SDK:

import * as WebChat from 'botframework-webchat';

const initChatBot = async (data, botWindowElement) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const store = WebChat.createStore({}, ({ dispatch }) => (next) => (action) => {
    if (action.type === 'DIRECT_LINE/POST_ACTIVITY' || action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
      const activityDate = new Date(action.payload.activity.timestamp);

      if (action?.payload?.activity?.type === 'typing') {
        return false;
      } else {
        dispatch({
          type: 'WEB_CHAT/SET_SEND_TYPING',
          payload: { sendTyping: true },
        });
      }
    }

    if (action.type === 'WEB_CHAT/SET_SEND_TYPING') {
      if (!action.payload.sendTyping) {
        console.log('Bot is not Typing...');
        this.isTyping = false;
        clearTimeout(this.typingTimeout);
      } else {
        console.log('Bot is Typing...');
        this.isTyping = true;
        clearTimeout(this.typingTimeout);
        this.typingTimeout = setTimeout(() => {
          this.isTyping = false;
        }, 120000); // 2 minutes
      }
    }

    if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' && action.payload.activity.type === 'message') {
      dispatch({
        type: 'WEB_CHAT/SET_SEND_TYPING',
        payload: { sendTyping: false },
      });
    }

    return next(action);
  });

  const styleOptions = {
    botAvatarInitials: 'AD',
    bubbleBackground: 'rgba(0, 0, 255, .1)',
    bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
    typingAnimationDuration: 5000,
    typingIndicatorBackgroundImage: 'url("https://support.signal.org/hc/article_attachments/360016877511/typing-animation-3x.gif")',
    typingIndicatorHeight: 20,
    typingIndicatorWidth: 20,
  };

  WebChat.renderWebChat(
    {
      directLine: WebChat.createDirectLine({ token: data?.token }),
      userID: this._appState.appState?.userCode,
      username: this._appState.appState?.fullName,
      locale: 'vi-VN',
      styleOptions,
      store,
      sendTypingIndicator: true,
    },
    botWindowElement
  );
};

Step 3: Integrate the Chatbot into Your Application

React Example

import React, { useEffect, useRef } from 'react';
import { getBotToken, initChatBot } from './path/to/your/utils';

const ChatbotComponent = () => {
  const botWindowRef = useRef(null);

  useEffect(() => {
    const setupChatbot = async () => {
      const token = await getBotToken();
      initChatBot(token, botWindowRef.current);
    };

    setupChatbot();
  }, []);

  return <div ref={botWindowRef} style={{ height: '500px', width: '100%' }} />;
};

export default ChatbotComponent;

Angular Example

import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { getBotToken, initChatBot } from './path/to/your/utils';

@Component({
  selector: 'app-chatbot',
  template: '<div #botWindow style="height: 500px; width: 100%"></div>',
})
export class ChatbotComponent implements AfterViewInit {
  @ViewChild('botWindow') botWindowElement: ElementRef;

  async ngAfterViewInit() {
    const token = await getBotToken();
    initChatBot(token, this.botWindowElement.nativeElement);
  }
}

Customization

You can customize the appearance and behavior of the Web Chat control using the styleOptions property. For example, you can change the avatars, colors, and typing indicators.

Example of Custom Style Options:

const styleOptions = {
  botAvatarInitials: 'AD',
  bubbleBackground: 'rgba(0, 0, 255, .1)',
  bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
  typingIndicatorBackgroundImage: 'url("https://support.signal.org/hc/article_attachments/360016877511/typing-animation-3x.gif")',
  typingIndicatorHeight: 20,
  typingIndicatorWidth: 20,
};

Additional Resources

For more detailed information and examples, refer to the following resources:

PreviousTeamsNextEmail

Last updated 10 months ago

Web Chat Overview
Web Chat Customization
Direct Line Authentication