AThe zure Bot Framework SDKV4 can be used with LUIS models and QnA Maker knowledge bases. It helps to determine which LUIS model or QnA Maker knowledge base best matches the user input.
SPFX (SharePoint Framework) is the recommended and only option to deploy Azure bots into SharePoint Online Modern Sites.
In this article, I am going to extend my
previous article with SPFX (SharePoint Framework).
SPFX (SharePoint Framework) interacts with Azure Bot Services via directline.
Let's get started with implementation steps.
Step 1
Navigate to Deployed Azure Bot and Add Direct Line as Channel & get Secret Key
- Select Channel and add a featured channel option; i.e. Direct Line, Ms Teams and Cortona. Select Direct Line to add.
- As you select direct line as channel, it will be added.
- Click edit to get the secret key. This key will be used in SPFX webpart to post requests to bot via direct line api & secret key.
Step 2 - Create SFPX Project
- Open Command Prompt or Visual Studio Code and Navigate or create a blank folder; i.e. ChatBot, and use CD command to navigate into folder.
- Type yo@Microsoft/SharePoint generator to create a framework.
- Type Solution Name: spfx-chat-bot
- Select SharePoint Online
- Select option to place a file as "Current Folder"
- Place the WebPart Name & Description as ChatBot
- Select framework as React to start.
Step 2 - Install NPM Package
Install the below defined npm packages to SPFX solution.
- npm install botframework-directlinejs
- npm install botframework-webchat
Step 3
Create State Class for Modal Dialog
State will hold variable to switch the modal dialog box.
- export interface IChatBotState {
- showModal: boolean;
- isDraggable: boolean;
- directline: any;
- styleSetOptions: any;
- }
Step 4 - Update Properties Interface
Properties have variables which help to set background color, font etc.
- import { IWebPartContext } from '@microsoft/sp-webpart-base';
- export interface IChatbotProps {
- description: string;
- directLineToken: string;
- bubbleBackground: string;
- bubbleTextColor: string;
- bubbleFromUserBackground: string;
- bubbleFromUserTextColor: string;
- backgroundColor: string;
- botAvatarImage: string;
- botAvatarInitials: string;
- userAvatarImage: string;
- userAvatarInitials: string;
- hideUploadButton: boolean;
- sendBoxBackground: string;
- sendBoxTextColor: string;
- context: IWebPartContext;
- }
Step 5 - React Component Implementation
Define construcutor, which will help to initilaize the defined properties and set the state variable.
- constructor(props) {
- super(props);
-
- this.state = {
- showModal: false,
- isDraggable: true,
- directline: null,
- styleSetOptions: styleOptions
- };
- this._showModal = this._showModal.bind(this);
- this._closeModal = this._closeModal.bind(this);
- }
Show Modal and Close Modal used to set toggle variable.
- private _showModal = (): void => {
- this.setState({ showModal: true });
- this.fetchToken();
- };
-
- private _closeModal = (): void => {
- this.setState({ showModal: false });
- };
Initiate the post request to directline .
- async fetchToken() {
- var myToken ='<<--Secret Key-->>';
- const myHeaders = new Headers()
- myHeaders.append('Authorization', 'Bearer ' + myToken)
- const res = await fetch(
- 'https://directline.botframework.com/v3/directline/tokens/generate',
- {
- method: 'POST',
- headers: myHeaders
- }
- )
- const { token } = await res.json();
- console.log(token);
- this.setState({
- directline: createDirectLine({ token })
- });
- this.state.directline.postActivity({
- from: { id: "serId", name: "USER_NAME" },
- name: "requestWelcomeDialog",
- type: "event",
- value: "token"
- }).subscribe(
- id => console.log(`Posted activity, assigned ID ${id}`),
- error => console.log(`Error posting activity ${error}`)
- );
-
- }
Use component did mount to call this method.
- async componentDidMount() {
- this.fetchToken();
- }
Render Method
On Icon Click call Modal Dialog and which will invoke ReactWebChat Tag with direct line state variable,
- <div className={ styles.chatbot }>
- <DefaultButton style={{ border: 'none', textDecoration: 'none', background: 'none', outline: 'none' }} onClick={this._showModal}>
- <img src="https://data.blob.core.windows.net/boticon/ChatBotIcon.JPG" alt="Chatbot" height="100px" width="100px" />
- </DefaultButton>
- <Modal
- titleAriaId={this._titleId}
- subtitleAriaId={this._subtitleId}
- isOpen={this.state.showModal}
- onDismiss={this._closeModal}
- isBlocking={true}
- containerClassName={contentStyles.container}
- dragOptions={this.state.isDraggable ? this._dragOptions : undefined}
- >
- <div className={contentStyles.header}>
- <span id={this._titleId}>Virtual Assistant</span>
- <IconButton
- styles={iconButtonStyles}
- iconProps={{ iconName: 'Cancel' }}
- ariaLabel="Close popup modal"
- onClick={this._closeModal as any}
- />
- </div>
- <div id={this._subtitleId} className={contentStyles.body}>
- <ReactWebChat directLine={this.state.directline} styleOptions={this.state.styleSetOptions} />
- </div>
- </Modal>
- </div>
Step 6 - Test locally
To run your solution type "Gulp Serve" in the terminal window. It will prompt the new window with local host workbench url " https://localhost:4321/temp/workbench.html"
Click icon to get pop up. Start typing the question as defined into Luis and QnA Maker and results start appearing without any delay.
The previous article can be found from these links.
I hope you have enjoyed and learned something new in this article. Thanks for reading and stay tuned for the next article.