Azure 机器人框架 - 连接打开和关闭

Azure bot framework - Connection open and close

我是 Azure 机器人服务的新手。我创建了一个机器人并在本地托管。我想知道用户和机器人之间的连接何时关闭。 我实际上需要它在连接关闭之前将聊天历史记录存储到数据库中。 我正在使用 Directline API。 机器人连接会保持很长时间吗? 连接关闭前是否有任何事件触发? 使用和机器人之间的实际连接是如何创建和关闭的?

如果您在自己的网站中使用直线频道,则以下方法应该有效。本质上,当用户结束与您的机器人的聊天时,您只需向您的机器人发送 backchannel message

确保按如下方式定义您的直线,以便连接可用于反向信道消息

botConnection = new BotChat.DirectLine({
    secret: "<secret>"
  });

您需要在 html 主体或 div 上注册一个 "onunload" 方法,如下所示:

 <body onunload="closeBotChat();">

然后在此方法中,您只需从您的网站向您的机器人发送一个事件,表明对话结束

 function closeBotChat(){
  botConnection
  .postActivity({
    from: { id: '<user>' },
    value: "chat <conversationId> closed", //send whatever information you need about the conversation here
    type: 'event',
    name: "ConversationUpdate"
  })
  .subscribe(id=> console.log("closed" + id)) // this will likely not be shown unless the botchat is in a modal within the page somewhere
}

在您的机器人中使用以下代码将能够听到并处理此事件:

bot.on("event", function(e){
    console.log(util.inspect(e)); // do whatever with the conversation end event here
});

请注意,您无需为机器人网络聊天的 "open connection" 事件添加任何内容,因为 ConversationUpdate 事件会在新对话开始时自动发送。