Microsoft ChatBot SDK v4 Introduction with C#

Chatbots are fun to develop and use. And, although our current chatbots are not near nirvana of conversational AI, there's just something different and magical about receiving and sending messages to a chatbot. As scripted as most currently are, you can't deny chatbots seem magical. Now, how can you build a chatbot? There’s many different options today ranging from fully building your own framework from scratch to using existing frameworks provided by small and large tech companies. Each with their own pros and cons. We won’t go into the pro’s and cons of each but rather focus on one of them from Microsoft called the Bot Framework. In this blog, I’ll help you get started using this very powerful (and still evolving) chatbot framework.  

ChatBot

Microsoft Bot Framework

Microsoft’s framework to help develop conversational interfaces aka Bots is called the Microsoft Bot Framework. Microsoft provides you with a free open source SDK hosed on github called the Bot Builder SDK. This project provides you with everything you need to build your own chatbots in multiple languages such as C#, Node js Python and others. 

The current stable release of the SDK is v3, but, nearing the release stage is the completely revamped v4 which brings significant breaking changes. If you are just getting started with the Microsoft bot framework, I suggest you start with v4, be aware though that functionality might change before it is released.

Requirements

In order for you to get started building chatbots you’ll need the following:

 

Your First Chat-Bot

Once you have installed the above requirements, it’s quite easy to get working a very very simple bot which just repeats what we write to it. It’s usually used in bot samples and quite aptly is called an Echo Bot. 

To begin, open up Visual Studio and create a new project of type Bot Builder Echo Bot v4 as below:

ChatBot Microsoft Bot Framework

This template is what you recently installed from Microsoft. Under the hood it’s an Asp.net Core web app together with additional powerful sdk’s that enable the chatbot functionality.

Bot Framework Project Settings

To better understand what is going on, take a look at the startup.cs file, a standard class in ASP.net Core Web, here is important services are being hooked up. Look closely at the ConfigureServices method. 

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddBot<EchoBot>(options =>
            {
                options.CredentialProvider = new ConfigurationCredentialProvider(Configuration);

                options.Middleware.Add(new CatchExceptionMiddleware<Exception>(async (context, exception) =>
                {
                    await context.TraceActivity("EchoBot Exception", exception);
                    await context.SendActivity("Sorry, it looks like something went wrong!");
                }));
 
                IStorage dataStore = new MemoryStorage();

                options.Middleware.Add(new ConversationState<EchoState>(dataStore));
            });
        }

What is happening? First off, the EchoBot service is added. This EchoBot class implements the IBot interface, we will get into more detail in just a sec. The CatchExceptionMiddleware (new to SDK v4) is added to capture exceptions. To maintain state, MemoryStorage class is initialized. As described in the template comments, only use MemoryStorage for development purposes but not in production. Lastly, the ConversationState middleware is initialized to use Memory Storage. Note here, an EchoState class was added to the conversation state. This class will hold a count that we will keep track of throughout our conversations.

Now, turn your attention to the EchoBot.cs file. This class inherits from the IBot interface and is responsible for handling incoming activities. To better understand, you need to have an idea of what the IBot interface is. Read along to find out more.

    public interface IBot
    {
        Task OnTurn(ITurnContext turnContext);
    }

The IBot interface has one method called OnTurn. It’s input parameter is a turnContext object that provides information about the incoming activity and additional information that is needed to process the activity. This is provided by a Microsoft.Bot.Builder.Bot adapter of the channel your bot is communicating to/from. Upon completion, it returns a Task, which is just work queued to be executed. 

Now, it’s the time to implement the IBot interface. This is done in the EchoBot.cs file and the template provides a simple implementation for you.

Take a look at the code below. As stated, we receive a turnContext object. In this object, we check if the activity is of type ActivityTypes.Message. If it is, we will respond. First, we obtain the EchoState object from the conversation state. Next, we increment the count by one and reply back with a message displaying the number of turns together with the received message.

        public async Task OnTurn(ITurnContext context)
        {
            // This bot is only handling Messages
            if (context.Activity.Type == ActivityTypes.Message)
            {
                // Get the conversation state from the turn context
                var state = context.GetConversationState<EchoState>();

                // Bump the turn count. 
                state.TurnCount++;

                // Echo back to the user whatever they typed.
                await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'");
            }
        }

That is all, your echo-bot ready to go! Next, I’ll show you how to chat with your echo-bot using the bot framework emulator. 

Debugging your ChatBot

This is the easiest part, assuming you have the chat-bot emulator already installed. Go ahead and run your project. Once it’s running, you’ll see webpage open up with the url you’ll need to use to connect to your chatbot. 

Chatbot Bot Framework

Copy the url you see on your web page like above onto the emulator like the image below and click on connect. Don’t worry about the other settings, they aren’t needed when running locally. 

You’ll start to see debugging messages on the log pane to the right.

Bot Framework Emulator

Start your first chatbot conversation by sending messages to your chatbot. This is an echo-bot, so you’ll see it respond with your same message and the number of turns that have passed.

Chatbot Messages Emulator

 

Conclusion

Congratulations! You just built your very first chatbot using the Microsoft Bot Framework library. This is a powerful framework that allows you to build sophisticated chatbots. There is much more to learn and we barely scratched the surface. In my next posts I’ll build upon this template and delve further into the Microsoft Bot Framework Sdk. Happy coding!

MJ

Advanced analytics professional currently practicing in the healthcare sector. Passionate about Machine Learning, Operations Research and Programming. Enjoys the outdoors and extreme sports.

Related Articles

>