如何使用Bot Builder SDK V4中的中间件区分Bot与用户以及用户与Bot消息?

时间:2019-01-17 02:04:38

标签: node.js botframework middleware microsoft-cognitive

我已经在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.
});

1 个答案:

答案 0 :(得分:2)

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

传出活动(即从机器人发送来的响应传入活动的活动)也可以被中间件拦截,但是中间件需要更多地参与到这些活动的发送中明确地。通过使用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. `);    

});

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