Intercept messages

Note

This topic applies to SDK v3 release. You can find the documentation for the latest version of the SDK v4 here.

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.

Intercept and log messages

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

First, create a DebugActivityLogger class and define a LogAsync method to specify what action is taken for each intercepted message. This example just prints some information about each message.

public class DebugActivityLogger : IActivityLogger
{
    public async Task LogAsync(IActivity activity)
    {
        Debug.WriteLine($"From:{activity.From.Id} - To:{activity.Recipient.Id} - Message:{activity.AsMessageActivity()?.Text}");
    }
}

Then, add the following code to Global.asax.cs. Every message that is exchanged between user and bot (in either direction) will now trigger the LogAsync method in the DebugActivityLogger class.

	public class WebApiApplication : System.Web.HttpApplication
	{
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<DebugActivityLogger>().AsImplementedInterfaces().InstancePerDependency();
            builder.Update(Conversation.Container);

            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }

Although this example simply prints some information about each message, you can update the LogAsync method to specify 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 .NET, see the Middleware sample in GitHub.

Additional resources