Intercept messages in the v3 JavaScript SDK

APPLIES TO: SDK v3

The middleware functionality in the Bot Framework SDK enables your bot to intercept all messages that are exchanged between user and bot. For each message that is intercepted, you may choose to do things such as save the message to a data store that you specify, which creates a conversation log, or inspect the message in some way and take whatever action your code specifies.

Note

The Bot Framework does not automatically save conversation details, as doing so could potentially capture private information that bots and users do not wish to share with outside parties. If your bot saves conversation details, it should communicate that to the user and describe what will be done with the data.

Example

The following code sample shows how to intercept messages that are exchanged between user and bot by using the concept of middleware in the Bot Framework SDK for Node.js.

First, configure the handler for incoming messages (botbuilder) and for outgoing messages (send).

server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector);
bot.use({
    botbuilder: function (session, next) {
        myMiddleware.logIncomingMessage(session, next);
    },
    send: function (event, next) {
        myMiddleware.logOutgoingMessage(event, next);
    }
})

Then, implement each of the handlers to define the action to take for each message that is intercepted.

module.exports = {
    logIncomingMessage: function (session, next) {
        console.log(session.message.text);
        next();
    },
    logOutgoingMessage: function (event, next) {
        console.log(event.text);
        next();
    }
}

Now, every inbound message (from user to bot) will trigger logIncomingMessage, and every outbound message (from bot to user) will trigger logOutgoingMessage. In this example, the bot simply prints some information about each message, but you can update logIncomingMessage and logOutgoingMessage as necessary to define the actions that you want to take for each message.

Sample code

For a complete sample that shows how to intercept and log messages using the Bot Framework SDK for Node.js, see the Middleware and Logging sample in GitHub.