how to intercept messages in botbuilder sdk v4 using middleware?

Viewed 1467

I have a Bot running on botbuilder V3 where I am using a middleware explained here to intercept the messages.

bot.use({
    botbuilder: function (session, next) {
        myMiddleware.logIncomingMessage(session, next);
    },
    send: function (event, next) {
        myMiddleware.logOutgoingMessage(event, next);
    }
})

We are planning to migrate on sdk v4 so looking for similar capabilities in sdk v4. Are there any ?

I didn't find example on this page.

1 Answers

The BotAdapter base class exposes the use method to register middleware. So in your startup logic you'll create a specific implementation of a BotAdapter, typically BotFrameworkAdapter, and then add the middleware to it. Like so:

const botAdapter = new BotFrameworkAdapter( { /* credential stuff here*/ });

// Simple handler based
botAdapter.use(async (turnContext, next) => {
    // pre logic

    await next();

    // post logic
});

// Or class based
botAdapter.use(new MyMiddleware());
Related