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

How to differentiate Bot to user AND user to Bot messages using middleware in bot builder sdk v4?

我在 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()
    }
})

中间件的 V4 机器人代码

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

因此,您传递给 .use 的函数代表了一个中间件,可以对 incoming [=29= 进行预处理和 post 处理].您可以通过 turnContext.Activity 属性 从回合上下文访问 "current" activity。这些活动可以从用户发送,也可以从通过 DirectLine API 将它们发送到机器人的其他系统发送(假设您使用的是 Bot 框架服务)。

Outgoing activities,即bot为响应传入的activity而发送的activities,也可以被中间件拦截,但是中间件需要自己介入更明确地发送这些活动。它通过使用 onSendActivities API.

向转弯上下文注册一个处理程序来做到这一点

这一切看起来有点像这样:

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

});

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