我在 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活动。您可以通过以下方式从回合上下文访问“当前”活动turnContext.Activity
财产。这些活动可以从用户发送,也可以从其他系统发送,这些系统通过 DirectLine API 将它们发送到机器人(假设您使用的是机器人框架服务)。
Outgoing活动(即机器人响应传入活动而发送的活动)也可以被中间件拦截,但中间件需要更明确地参与这些活动的发送。它通过使用以下方法向回合上下文注册处理程序来实现此目的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]
。因此,如果在轮次期间发送了多个活动,则将为每个批次调用您的处理程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)