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

百般思念 提交于 2020-06-15 06:22:07

问题


I have implemented a middleware in sdk V4 Bot to intercept each message between bot & user and log that custom mongo Db. I am trying to implement similar concept for Bot built using SDK v4. Looks like I can use following piece of code to add a middleware but, not sure how to differentiate message between bot to user & user to bot.

V3 bot code

bot.use({
    botbuilder: function (session, next) {
        logUserConversation(session)
        next()
    },
    send: function (event, next) {
        logBotsConversation(event)
        next()
    }
})

V4 bot code for Middleware

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:


So the function that you pass to .use represents a piece of middleware that can do pre and post processing of an incoming activity. You access the "current" activity from the turn context via the turnContext.Activity property. Those activities can either be sent from the user or from some other system that sends them via the DirectLine API to the bot (assuming you're using the Bot Framework Service).

Outgoing activities, that is activities that are sent from the bot in response to the incoming activities, can also be intercepted by middleware, but the middleware needs to involve itself in the sending of those activities more explicitly. It does this by registering a handler with the turn context using the onSendActivities API.

This all comes together to look a little something like this:

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

});

The one thing to note is that outgoing activity handlers can be invoked 0..* times as they are basically triggered by downstream logic calling turnContext.sendActivit[y|ies]. So if, during the turn, there are multiple activities sent, your handler will be invoked for each batch.



来源:https://stackoverflow.com/questions/54227991/how-to-differentiate-bot-to-user-and-user-to-bot-messages-using-middleware-in-bo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!