如何在Webchat / DirectLine中检测对话结束?

时间:2019-06-18 11:18:08

标签: node.js botframework direct-line-botframework web-chat

我在Node.js中使用botbuilder创建了一个简单的聊天机器人。由于给定的环境,我通过自定义iframe包含了聊天机器人。前端是带有DirectLine的WebChat。 如何在父窗口中检测对话框的结尾?

在WebChat / DirectLine中找不到如何捕获对话框结尾的正确方法。

我在iframe中使用以下代码渲染聊天记录:


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: "thisismytoken" }),
   store,
   userID: '1',
   username: username,
   styleOptions: {
    botAvatarImage: "https://mylink.azurewebsites.net/avatar_user_1.png",
    userAvatarImage: "https://mylink.azurewebsites.net/avatar_user_1.png"
   }
 }, document.getElementById('webchat'));

在Node.JS中,我使用以下代码结束对话:

            return await step.endDialog();

运行endDialog后,我要提交iFrame的父级。谁能给我一些指导?

1 个答案:

答案 0 :(得分:1)

要做到这一点,只需对您的代码进行一些修改。

首先,在您的漫游器中,在step.endDialog()调用之前发送活动。此活动将是一个事件,并将发送状态要由您的页面拾取的数据。

在此示例中,我包括用户数据,以便查看谁退出了。我也在使用sendActivities()方法,因此我可以在发送事件的同时感谢用户。当然,您可以只使用sendActivity()发送单个事件。

  async finalStep(step) {
    const user = stepContext.context.activity.from;
    const data = { user: user, dialogStatus: 'complete' };

    await stepContext.context.sendActivities([
      { text: 'Thank you for visiting my bot!', type: 'message' },
      { name: 'data', type: 'event', channelData: { 'data': data } }
    ]);
    return await stepContext.endDialog();
  }

接下来,在页面中,使用createStore()方法并检查action.type中的DIRECT_LINE/INCOMING_ACTIVITY。在任何传入活动中,您都将创建一个名为“ incomingActivity”的新事件,该事件将从机器人接收到的有效负载中获取。

您还将添加一个名为“ incomingActivity”的window.addEventListener,它将捕获传入的数据并根据需要进行解析。

最后,就像您已经在代码中所做的一样,将store传递到renderWebChat组件中。

const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
  if ( action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' ) {
    const event = new Event('incomingActivity');

    event.data = action.payload.activity;
    window.dispatchEvent(event);
  }

  return next( action );
} );

window.addEventListener('incomingActivity', ({ data }) => {
  const type = data.type;
  if (type === 'event' && data.channelData.data.dialogStatus) {
    const status = data.channelData.data.dialogStatus;
    const user = data.channelData.data.user;
    console.log(`User '${user.name}', with an id of '${user.id}', reached the end of the dialog`);
  }
})

“网络聊天”窗口:

enter image description here

Bot的控制台记录记录:

enter image description here

浏览器的开发者控制台:

enter image description here

我相当定期地使用这样的内容,因此它应该为您工作。

希望有帮助!