How to close and restart bot conversation from UI

余生长醉 提交于 2019-12-14 03:33:47

问题


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:


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

Hope this helps!



来源:https://stackoverflow.com/questions/56848336/how-to-close-and-restart-bot-conversation-from-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!