Features 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:
Copy 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:
Copy 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
Copy 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
Copy 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:
Copy 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:
Last updated 10 months ago