Develop Chat Bot Using Microsoft Bot Builder SDK V4 - Part One - Quick Start For Beginners

In this article, we are going to create a chatbot using Bot Builder SDK v4.0 of Microsoft bot framework. It is the latest SDK available for bot development. It provides .NET, Java, JS, and python SKDs. But it is in the preview so all production bots should be developed using SDK v3.

Prerequisite

  • Download 2017 and update all extensions.
  • Download and install bot application template from here.
  • Download Bot Framework Emulator. The emulator is a desktop application that lets you test a bot application on localhost or running remotely OR you can also get a v4 version of bot emulator from here.
  • Bot Builder SDK v4 uses ASP .NET Core 2.0; hence you should have basic knowledge of ASP .NET Core, async programming, and middleware concept.

You can pull code from GitHub or download from the attachment of article.

Create a bot application

Open Visual Studio and create a new C# project. Choose Bot Builder Echo Bot V4 template. If required, also update NuGet Packages installed in the project.

 

The template contains all components required to build a bot as well as initial code setup. Right-click on the project and click on Properties. In project properties panel, under the Application tab, you can check Target framework as .NET Core 2.0.

 

Let's explore the code.

Startup.cs - ConfigureServices method

ASP.NET Core uses the Startup class as an entry point of application. It includes ConfigureServices( ) method (not mandatory) to configure the app's services.

  1. public void ConfigureServices(IServiceCollection services)  
  2.        {  
  3.            services.AddBot<EchoBot>(options =>  
  4.            {  
  5.                options.CredentialProvider = new ConfigurationCredentialProvider(Configuration);  
  6.                    
  7.                options.Middleware.Add(new CatchExceptionMiddleware<Exception>(async (context, exception) =>  
  8.                {  
  9.                    await context.TraceActivity("EchoBot Exception", exception);  
  10.                    await context.SendActivity("Sorry, it looks like something went wrong!");  
  11.                }));  
  12.                    
  13.                IStorage dataStore = new MemoryStorage();               
  14.                options.Middleware.Add(new ConversationState<EchoState>(dataStore));  
  15.            });  
  16.        }  

Bot Builder SDK V4 provides AddBot extension method for services object (type: IServiceCollection) to integrate bot with ASP .NET Core project. It accepts class which inherits Ibot interface. Here, it is mentioned as EchoBot class.

It takes the second parameter as bot framework options. CredentialProvider is used to lookup App Id and App Secret of Microsoft Bot App. Then middleware is added to handle the exception in bot conversation flow. To maintain the state of the conversation, ConversationState middleware is added with type EchoState and MemoryStorage as storage for conversation state data.

Startup.cs - Configure

Startup class also includes Configure( ) method, to create the app's request processing pipeline i.e. to define how the application will respond on HTTP requests.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  2.       {  
  3.           if (env.IsDevelopment())  
  4.           {  
  5.               app.UseDeveloperExceptionPage();  
  6.           }  
  7.   
  8.           app.UseDefaultFiles().UseStaticFiles().UseBotFramework();  
  9.       }  

Bot Builder SDK v4 provides UseBotFramework extension method to map endpoint handler for AddBot (used in ConfigureServices method) into HTTP request execution pipeline.

EchoBot.cs

EchoBot class implements interface IBot and hence OnTurn() method is part of it. OnTurn() method will be called for any user activity and event for the conversation like user added, user messaged, a user is typing, etc.

  1. public class EchoBot : IBot    
  2.  {              
  3.      public async Task OnTurn(ITurnContext context)    
  4.      {     
  5.          if (context.Activity.Type == ActivityTypes.Message)    
  6.          {    
  7.              var state = context.GetConversationState<EchoState>();    
  8.      
  9.              state.TurnCount++;    
  10.     
  11.              await context.SendActivity($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'");    
  12.          }    
  13.      }    
  14.  }    
  15.   
  16. public class EchoState  
  17. {  
  18.    public int TurnCount { get; set; } = 0;  
  19. }  
Default template contains code which will keep the count of messages from the user and return it back as a reply for each message. When the user starts a conversation or enters a message, the OnTurn method will get called. It will check the type of activity. If it is a Message, it gets the  conversation state which is of type EchoState. We have mentioned it in ConfigureServices method. The state will be retrieved from memory storage and typecasted to EchoState. In its first interaction, TurnCount value will be 0. It increments TurnCount value and sends it to the user using the SendActivity method.

Test

Hit F5 to test a bot application. It will host an application with IIS Express and open the browser with Bot application details. To understand the control flow, insert breakpoints in ConfigureServices, Configure method of Startup.class and OnTurn method of EchoBot class.

 

Now, launch the bot emulator app. Put URL as 'http://localhost:{{port no. from browser url}}/api/{{controller name}}' to connect emulator with bot application. Keep App ID and App Password blank, click on connect. Start chatting with bot and the bot will reply with the number of messages sent. Happy chatting! :)


Similar Articles