In this article, we are going to see what all things we require before starting with development of bot applications using Microsoft bot framework.
Prerequisite
- Download Visual Studio 2015/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.
Create bot application
Open Visual Studio and create a new C# project. Choose the Bot Application template. If required, also update NuGet Packages installed in project.
Template contains all components required to build a bot as well as initial code setup.
Code
In solution explorer, you will see WebApiConfig.cs file, Controllers and Dialogs folders. 'MessageController' is inherited from 'System.Web.Http.ApiController'. Bot application is nothing but webapis which will be called from chat window to get response.
When user is going to enter query in chat window, 'post( )' method within controller will get called. Then controller will invoke specified dialog (in our case, its RootDialog), which will process the query and return the result.
MessageController.cs
- [BotAuthentication]
- public class MessagesController: ApiController {
-
-
-
-
- public async Task < HttpResponseMessage > Post([FromBody] Activity activity) {
- if (activity.Type == ActivityTypes.Message) {
- await Conversation.SendAsync(activity, () => new Dialogs.AnswerDialog());
- } else {
- HandleSystemMessage(activity);
- }
- var response = Request.CreateResponse(HttpStatusCode.OK);
- return response;
- }
- private Activity HandleSystemMessage(Activity message) { ...
- }
- }
RootDialog.cs
- [Serializable]
- public class RootDialog: IDialog < object > {
- public Task StartAsync(IDialogContext context) {
- context.Wait(MessageReceivedAsync);
- return Task.CompletedTask;
- }
- private async Task MessageReceivedAsync(IDialogContext context, IAwaitable < object > result) {
- var activity = await result as Activity;
-
- int length = (activity.Text ? ? string.Empty).Length;
-
- await context.PostAsync($ "You sent {activity.Text} which was {length} characters");
- context.Wait(MessageReceivedAsync);
- }
- }
When controller invokes RootDialog, control will come to 'StartAsync( )' method of dialog. It will invoke MessageReceivedAsync ( )' method which will return number of characters in text entered by user.
Test
Hit F5 to test a bot application. It will host application with IIS Express and open browser. To understand the control flow, insert breakpoints in Post( ) method of MessageController and StartAsync( ) method of RootDialog.
Now launch 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 bot will reply with number of characters in your text. Happy chatting! :)