0
votes

I have created bot UI with this example https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/12.customization-minimizable-web-chat, but what I would like to do is create button with close chat window and restart conversation. Does anyone know how to implement this feature with bot framework v4?

1

1 Answers

1
votes

There are a couple of steps you need to do to restart the conversation. First, you need to save your DirectLine and Store objects for the conversation in the parent component's state and pass them as props to the Web Chat component. Then you need to add a button to the screen with an onClick handler that dispatches an event to disconnect the DirectLine Object from the conversation. Then in the store's middleware you need to listen for the connection to be disconnected and reinitialize the DirectLine and Store Objects. This will clear the conversation history and start a new conversation. See the code snippet below for an example.

Code Snippet

import React, { useState, useEffect } from 'react';
import ReactWebChat, { createDirectLine, createStore } from 'botframework-webchat';
import directLineDisconnect from 'botframework-webchat-core/lib/actions/disconnect';

const initializeDirectLine = async setDirectLine => {
  const res = await fetch('http://localhost:3978/directline/token', { method: 'POST' });
  const { token } = await res.json();
  setDirectLine(createDirectLine({ token }));
};

const WebChat = props => {
  const { directLine } = props;

  return directLine
    ? <ReactWebChat className={'chat'} {...props} />
    : "Connecting..."
}

export default () => {
  const [directLine, setDirectLine] = useState();
  useEffect(() => {
    initializeDirectLine(setDirectLine);
  }, []);

  const storeMiddleware = () => next => action => {
    if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
      setDirectLine(null);
      setStore(createStore({}, storeMiddleware));
      initializeDirectLine(setDirectLine);
    }
    return next(action)
  };

  const [store, setStore] = useState(createStore({}, storeMiddleware));

  const disconnect = () => store.dispatch(directLineDisconnect());

  return (
    <div className={app}>
      <div className='details'>
        <button onClick={disconnect}>Disconnect</button>
      </div>
      <div className='wrapper'>
        <WebChat directLine={directLine} store={store}/>
      </div>
    </div>
  )
};

Screen capture

enter image description here

Hope this helps!