Andy
Andy

Reputation: 2140

How to automatically join conversation in Microsoft web chat (bot framework)

I'm using https://github.com/Microsoft/BotFramework-WebChat/blob/master/README.md

I want the bot to receive a "join" message whenever the web-chat widget is displayed on the site.

The idea is that the human does not have to initiate the conversation. The bot can respond to somebody joining the conversation with a welcome message.

How is this possible?

Upvotes: 1

Views: 2274

Answers (1)

Nicolas R
Nicolas R

Reputation: 14619

This "Welcome feature" has been a long term discussion and topic since Webchat v3. It looks like it has been fixed 2 days ago with this pull request: https://github.com/Microsoft/BotFramework-WebChat/pull/1286

There is now a sample on how to do that, located here: https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/15.d.backchannel-send-welcome-event/index.html

In a few words, the demo is the following:

  (async function () {
    // 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();

    // We are using a customized store to add hooks to connect event
    const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
      if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
        // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
        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();
  })().catch(err => console.error(err));

Please note that due to the fact that this PR is quite new, it's not embedded in the latest release so you have to point to the master version of webchat.js file, not latest:

<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>

And it's working: your bot side is notified of an activity of type Event, where you will be able to reply to your user, before he typed anything:

demo

Upvotes: 4

Related Questions