Charlotte6789
Charlotte6789

Reputation: 53

BotFramework v4 in WebChat show bot's name and user's name after messages

I've implemented my v4 .NET bot in webchat using direct line and Microsft's sample-webchat. How can I enable the bot's name and the user's name after each message in the chat like this example?

I have gotten it to work using BotChat.App and https://cdn.botframework.com/botframework-webchat/0.11.4/botchat.js as the script but I can't seem to figure it out with window.WebChat like Microsoft's sample is using.

Here's my webchat code:

  <!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>

Upvotes: 0

Views: 2037

Answers (1)

tdurnford
tdurnford

Reputation: 3712

Unfortunately, the development team removed the bot name from the timestamp in Web Chat v4; however, you can use some of Web Chat's middlewares - the Redux Store and Activity middlewares - to add the bot name above each message set. I put together a sample to illustrate how to do this. Basically, in the store middleware, we are labeling which activities should display the bot name by checking the last message in the transcript and adding the showDisplayName to the activities' channel data which is true if the last message was not from the bot and false otherwise. Then in the Activity middleware, we are adding the bot name to the activity in a div if the showDisplayName value is true.

Web Chat v4 - Display Bot Name Sample

<!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/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/react-redux.min.js"></script>
    <script src="https://unpkg.com/[email protected]/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://learn.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>

Screenshot

enter image description here

Note, the sample I put together does get into Web Chat's more advanced topics, so if you need more clarification, I would recommend looking at the Adding Middleware to Redux Store and the Reaction Buttons Web Chat samples.

Hope this helps!

Upvotes: 1

Related Questions