如何使用 bot builder sdk v4 中的中间件区分 Bot 到用户和用户到 Bot 消息?

vij*_*jay 3 middleware node.js microsoft-cognitive botframework

我在 sdk V4 Bot 中实现了一个中间件来拦截 bot 和用户之间的每条消息并记录该自定义 mongo Db。我正在尝试为使用 SDK v4 构建的 Bot 实现类似的概念。看起来我可以使用以下代码添加中间件,但是不确定如何区分机器人到用户和用户到机器人之间的消息。

V3 机器人代码

bot.use({
    botbuilder: function (session, next) {
        logUserConversation(session)
        next()
    },
    send: function (event, next) {
        logBotsConversation(event)
        next()
    }
})
Run Code Online (Sandbox Code Playgroud)

中间件的 V4 bot 代码

botAdapter.use(async (turnContext, next) => {
    // How to find which messages/activity object is from user to bot

    await next();
    // How to find which messages/activity object is from bot to user.
});
Run Code Online (Sandbox Code Playgroud)

Dre*_*rsh 5

因此,您传递给的函数.use表示一个中间件,可以对传入的活动进行预处理和后处理。您可以通过turnContext.Activity属性从转弯上下文访问“当前”活动。这些活动可以从用户发送,也可以从通过 DirectLine API 将它们发送到机器人的其他系统发送(假设您使用的是机器人框架服务)。

传出活动,即机器人为响应传入活动而发送的活动,也可以被中间件拦截,但中间件需要更明确地参与这些活动的发送。它通过使用onSendActivitiesAPI向转弯上下文注册处理程序来实现此目的。

所有这些结合起来看起来有点像这样:

botAdapter.use(async (turnContext, next) => {
    // pre-processing of the current incoming activity
    console.log(`Processing activity ${turnContext.activity.id} starting... `);

    // hook up a handler to process any outgoing activities sent during this turn
    turnContext.onSendActivities(async (sendContext, activities, nextSend) => {
       // pre-processing of outgoing activities

       await nextSend();       

       // post-processing outgoing activities
    });

    await next();

    // post-processing of the current incoming activity 
    console.log(`Processing activity ${turnContext.activity.id} finishing. `);    

});
Run Code Online (Sandbox Code Playgroud)

需要注意的一件事是传出活动处理程序可以被0..*多次调用,因为它们基本上是由下游逻辑调用触发的turnContext.sendActivit[y|ies]。因此,如果在回合期间发送了多个活动,则将为每个批次调用您的处理程序。