【问题标题】:BotFramework v4 in WebChat show bot's name and user's name after messagesWebChat 中的 BotFramework v4 在消息后显示机器人的名称和用户名
【发布时间】:2020-01-11 02:48:48
【问题描述】:

我已经使用直线和 Microsft 的 sample-webchat 在网络聊天中实现了我的 v4 .NET 机器人。如何在聊天中的每条消息后启用机器人的名称和用户的名称,例如this 示例?

我已经使用 BotChat.Apphttps://cdn.botframework.com/botframework-webchat/0.11.4/botchat.js 作为脚本让它工作,但我似乎无法像 Microsoft 的示例那样使用 window.WebChat 来解决它。

这是我的网络聊天代码:

  <!DOCTYPE html>
<html lang="en-US">
  <head>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
      html, body { height: 100% }
      body { margin: 0 }

      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
        <div style="display: flex">
            <div style="position: relative; height: 500px; width: 370px"><div id="webchat" ></div></div>
        </div>
    <script>
      (async function () {

        const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer my direct line secret' } });
        const { token }  = await res.json();

       const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
         if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
           dispatch({
             type: 'WEB_CHAT/SEND_EVENT',
             payload: {
               name: 'webchat/join',
               value: { language: window.navigator.language }
             }
           });
         }
         return next(action);
       });

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
        store
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();

        BotChat.App({
        botConnection:  botConnection,
        user: { id: '1234', name: 'user'},
        bot: { id: 'botid' },
        chatTitle: "I'm a custom chat title"
        }, document.getElementById("webchat"));


      })().catch(err => console.error(err));
    </script>
  </body>
</html>

【问题讨论】:

    标签: reactjs botframework web-chat


    【解决方案1】:

    不幸的是,开发团队从 Web Chat v4 中的时间戳中删除了机器人名称;但是,您可以使用一些 Web Chat 的中间件——Redux Store 和 Activity 中间件——在每个消息集上方添加机器人名称。我整理了一个示例来说明如何执行此操作。基本上,在商店中间件中,我们通过检查脚本中的最后一条消息并将showDisplayName 添加到活动的通道数据中来标记哪些活动应该显示机器人名称,如果最后一条消息不是来自机器人并且否则为假。然后在 Activity 中间件中,如果 showDisplayName 值为 true,我们会将机器人名称添加到 div 中的 Activity。

    网络聊天 v4 - 显示机器人名称示例

    <!DOCTYPE html>
    <html lang="en-US">
      <head>
        <title>Web Chat: Custom attachment with GitHub Stargazers</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!--
          For simplicity and code clarity, we are using Babel and React from unpkg.com.
        -->
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
        <script src="https://unpkg.com/react@16.5.0/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16.5.0/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/react-redux@5.0.7/dist/react-redux.min.js"></script>
        <script src="https://unpkg.com/glamor@2.20.40/umd/index.js"></script>
        <script src="https://unpkg.com/simple-update-in/dist/simple-update-in.production.min.js"></script>
        <!--
          This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to pointing to Web Chat's MyGet feed:
          https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
        -->
        <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
        <style>
          html, body { height: 100% }
          body { margin: 0 }
          #webchat {
            height: 100%;
            width: 100%;
          }
        </style>
      </head>
      <body>
        <div id="webchat" role="main"></div>
        <script type="text/babel">
          (async function () {
            'use strict';
    
            const { connectToWebChat, ReactWebChat } = window.WebChat;
            const { css } = window.Glamor;
            const { Fragment } = window.React;
            const { simpleUpdateIn } = window;
    
            const displayNameStyle = css({ 
              color:'#767676', 
              fontFamily: "Calibri, Helvetica Neue, Arial, sans-serif", 
              fontSize: '80%', 
              paddingBottom: '5px',
              paddingLeft: '10px',
            });
    
            const activityMiddleware = () => next => card => {
            const { activity: { channelData: { showDisplayName } = {}, from: { name: botName }}} = card;
              return (children) => (
                <Fragment>
                  { showDisplayName && <div className={displayNameStyle}>{ botName }</div> }
                  { next(card)(children) }
                </Fragment>)
            };
            const store = createStore(
              {},
              ({ getState }) => next => action => {
                if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
                  const { activities } = getState();
                  const { from: { role: lastRole } = {}} = activities.filter(({ type }) => type === 'message')[activities.length - 1] || {}; 
                  const { from: { role: incomingRole }} = action.payload.activity;
                  action = simpleUpdateIn(action, ['payload', 'activity', 'channelData', 'showDisplayName'], () => incomingRole === 'bot' && lastRole !== 'bot')
                }
                return next(action)
              }
            );
    
            // In this demo, we are using Direct Line token from MockBot.
            // To talk to your bot, you should use the token exchanged using your Direct Line secret.
            // You should never put the Direct Line secret in the browser or client app.
            // https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
            const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
            const { token } = await res.json();
    
            window.ReactDOM.render(
              <ReactWebChat
                activityMiddleware={ activityMiddleware }
                store={store}
                directLine={ window.WebChat.createDirectLine({ token }) }
              />,
              document.getElementById('webchat')
            );
            document.querySelector('#webchat > *').focus();
          })().catch(err => console.error(err));
        </script>
      </body>
    </html>
    

    截图

    请注意,我整理的示例确实涉及网络聊天的更高级主题,因此如果您需要更多说明,我建议您查看Adding Middleware to Redux StoreReaction Buttons 网络聊天示例。

    希望这会有所帮助!

    【讨论】:

    • 以上链接已失效。
    • 我更新了答案中的链接。谢谢你告诉我。
    • 另外,网络聊天开发团队目前正在努力添加一个中间件来自定义时间戳组件。此功能应包含在 3 月的下一个版本中。您可以跟踪功能here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多