1

我在 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 的父级。谁能给我一些指导?

4

1 回答 1

2

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

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”的新事件,它将接收来自机器人的有效负载。

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

最后,正如您在代码中所做的那样,将 传递给storerenderWebChat 组件。

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`);
  }
})

网络聊天窗口:

在此处输入图像描述

Bot 的控制台记录日志:

在此处输入图像描述

浏览器的开发者控制台:

在此处输入图像描述

我经常使用这样的东西,所以它应该适合你。

希望有帮助!

于 2019-06-21T19:17:49.517 回答