Design And Develop A Greeting Bot using Microsoft Bot Framework On VS 2019 Community Version

Introduction 

 
In my previous article, we tried to understand the basics of the Microsoft Bot Framework. Now, in this article, we will develop a basic Echo Bot for you guys to understand how to set up a hello world application. Next, we will implement a greeting bot that will greet us and will ask for our name, and then we will see that it will be able to remember our name with the help of our user ID. As of now, we will use Microsoft bot Builder's MemoryStorage, which is a storage layer that uses an in-memory dictionary. I will also place the code for you guys to use AzureBlobStorage attaching your storage account and storage container name if you guys wish to use Azure services and it will enable our Bot to always remember your user ID.
 
So, without wasting more time, let's dive into it. Below are the following prerequisites that we should have on our system:
After installing the prerequisites, open your Visual Studio and select the Project Extension, just like below:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
It will ask you to give the project name and browse the location for the projects, etc. You can fill them and refer to the below screen.
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Click on Create. You should be able to see the below solutions with folders:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You will find this project structure similar to .NET core projects, where you have a www-root folder and have a Startup.cs class file as well. You might be wondering why, but since bot applications are a web application, and when we use the VSIX template, then it generates an ASP.NET MVC Core application, and these files are similar to the core app, which is required for all web apps and are not bot specific.
 
The appsettings.json is the configuration file that contains information specific to your bot such as app ID, passwords, etc. You can later add on your keys or URL to this configuration file according to your environment. But for this example, its empty which is quite normal and because right now we don’t need it.
 
As I have already told you, a bot is a web application. Here, because we are using an ASP.NET MVC core application, the folder you will see controllers and bots are only related to that. We will talk more about the classes which these folders have but you can keep in mind that it is the same as MVC core web application.
 
Bots folder contains one class EchoBot which extends ActivityHandler which implements the IBot interface. For now, you will notice that we have two methods which already override for us. OnMessageActivityAsync is used when your bot receives a message activity. Whenever the turn handler sees any incoming activity, then it will send it to the OnMessageActivityAsync activity handler. So, we will use this method for handling and responding to message with our own logic while building our bot.
 
Another method which is OnMemeberAddedAsync handler will be used the same as OnMessageActivityAsync but rather than the message we will be handling members.
 
These two methods are for you to implement your own logic for building your bot specific to your needs. There will be times when you want to override base turn handler for maybe saving states and all. So, you have to make sure that you are calling await base.OnTurnAsyn(turnContext, cancellationToken); first, just to make sure base implementation is run before your additional logic.
 
turnContext provides information about an incoming activity, which corresponds to the inbound HTTP request. You will find strongly typed activity in handler turn context.
In this sample, you will see that we will just welcome a new user or echo back the message the user sent using the SendActivityAsync call.
  1. public class EchoBot : ActivityHandler  
  2.     {  
  3.         protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)  
  4.         {  
  5.             var replyText = $"Echo: {turnContext.Activity.Text}";  
  6.             await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);  
  7.         }  
  8.   
  9.         protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)  
  10.         {  
  11.             string welcomeText = "Hello and welcome!";  
  12.             foreach (var member in membersAdded)  
  13.             {  
  14.                 if (member.Id != turnContext.Activity.Recipient.Id)  
  15.                 {  
  16.                     await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText, welcomeText), cancellationToken);  
  17.                 }  
  18.             }  
  19.         }  
  20.     }  

Run Your First Bot

 
In order to run your bot for the first time, we first need to start our bot emulator which we have downloaded earlier. Once it’s up and running you should be able to see the below screen.
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Now just rebuild your solution on Visual Studio and run it using the below configuration:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Select EchoBot profile and run it. You will see events on command prompt just like below:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You will observe that your bot has now started on https://localhost:3979/ and you will see the below screen. If it asks for an https certificate, then you can always release the certificate for your localhost.
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You must pay attention to the above-highlighted URL, which is your bot’s endpoints. You will use this URL to connect to your bot on bot emulator. So, copy this URL and paste it on Emulator just like below.
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Click on connect and you should be able to see the below screen:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You can type your message to see if that Echo is back again to us or not. Just like shown below:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You will notice on the right-hand side of the emulator your request is logged as well and displayed to you so you know which request is getting processed.
 
So, you have now successfully created your EchoBot. You will see our bot just said, “Hello and welcome!”. In the next segment, we will debug our code.
 

Debug your Code

 
So, to debug your code, put the debugger point at the  below line in the EchoBot class:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Now, on your bot emulator click on "restart the conversation - New User Id. As soon as you click on this your debugger, it will hit the OnMemberAddedAsync method and you will see as we are setting the welcome text and sending this activity to our users. just press f5 and see you will receive the welcome message on your Bot Emulator.
 

Develop a Greeting Bot that Remembers Your Name

 
Until now, we were just using the template version of our EchoBot which comes with the template which we installed at the starting of this article. Now, we will extend the functionality of our bot to remember our name and store it in the in-memory dictionary. You can follow this blog up or you can just clone my repository from GitHub, below is the URL:
So let's start. First, we will create our new Greeting Bot. So, go ahead and create the GreetingBot class in Bots folder and paste the below code for this class.
  1. public class GreetingBot : ActivityHandler   
  2.    {  
  3.        #region Variables  
  4.        private readonly BotStateService _botStateService;  
  5.        #endregion  
  6.   
  7.        public GreetingBot(BotStateService botStateService)  
  8.        {  
  9.            _botStateService = botStateService ?? throw new System.ArgumentNullException(nameof(botStateService));  
  10.        }  
  11.        protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)  
  12.        {  
  13.            await GetName(turnContext, cancellationToken);  
  14.        }  
  15.   
  16.        protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)  
  17.        {  
  18.            foreach (var member in membersAdded)  
  19.            {  
  20.                if (member.Id != turnContext.Activity.Recipient.Id)  
  21.                {  
  22.                    await GetName(turnContext, cancellationToken);  
  23.                }  
  24.            }  
  25.        }  
  26.   
  27.        private async Task GetName(ITurnContext turnContext, CancellationToken cancellationToken)  
  28.        {  
  29.            UserProfile userProfile = await _botStateService.UserProfileAccessor.GetAsync(turnContext, () => new UserProfile());  
  30.            ConverstationData converstationData = await _botStateService.ConversationDataAccessor.GetAsync(turnContext, () => new ConverstationData());  
  31.            if (!string.IsNullOrEmpty(userProfile.Name))  
  32.            {  
  33.                await turnContext.SendActivityAsync(MessageFactory.Text(String.Format("Hi {0}. How can I help you today?", userProfile.Name)), cancellationToken);  
  34.            }  
  35.            else  
  36.            {  
  37.                if (converstationData.PromptedUserForName)  
  38.                {  
  39.                    //set the name to what the user provided  
  40.                    userProfile.Name = turnContext.Activity.Text?.Trim();  
  41.   
  42.                    //Acknowledge that we got their name.  
  43.                    await turnContext.SendActivityAsync(MessageFactory.Text(String.Format("Thanks {0}. How can I help you today?", userProfile.Name)), cancellationToken);  
  44.   
  45.                    //Reset the flag to allow the bot to go through the cycle again.  
  46.                    converstationData.PromptedUserForName = false;  
  47.                }  
  48.                else  
  49.                {  
  50.                    //introduce your bot   
  51.                    await turnContext.SendActivityAsync(MessageFactory.Text("Hi GoodMorning!! I am MPBot."), cancellationToken);  
  52.   
  53.                    //Prompt the user for their Name  
  54.                    await turnContext.SendActivityAsync(MessageFactory.Text("What is your name?"), cancellationToken);  
  55.   
  56.                    //set the flag to true, so we don't prompt in the next turn  
  57.                    converstationData.PromptedUserForName = true;  
  58.                }  
  59.   
  60.                //Save any state changes that might have occured during the turn.  
  61.                await _botStateService.UserProfileAccessor.SetAsync(turnContext, userProfile);  
  62.                await _botStateService.ConversationDataAccessor.SetAsync(turnContext, converstationData);  
  63.   
  64.                await _botStateService.UserState.SaveChangesAsync(turnContext);  
  65.                await _botStateService.ConversationState.SaveChangesAsync(turnContext);  
  66.   
  67.            }  
  68.        }  
  69.    }  
We need our models, so create below two model classes as well: ConversationData.cs and Userprofile.cs
  1. public class ConverstationData  
  2.    {  
  3.        // Track whether we have already asked the user's name  
  4.        public bool PromptedUserForName { get; set; } = false;  
  5.    }  
  1. public class UserProfile  
  2.     {  
  3.         public string Name { get; set; }  
  4.     }  
We need one state service to initialize the conversation state accessors and the user state. So, go ahead create one service class called BotStateService.cs and paste the below code:
  1. public class BotStateService  
  2.    {  
  3.        #region Variables  
  4.        //state variables  
  5.        public ConversationState ConversationState { get; }  
  6.        public UserState UserState { get; }  
  7.   
  8.        //Ids  
  9.        public static string UserProfileId { get; } = $"{nameof(BotStateService)}.UserProfile";  
  10.        public static string ConverstationDataId { get; } = $"{nameof(BotStateService)}.ConversationData";  
  11.   
  12.        //Accessors   
  13.        public IStatePropertyAccessor<UserProfile> UserProfileAccessor { get; set; }  
  14.        public IStatePropertyAccessor<ConverstationData> ConversationDataAccessor { get; set; }  
  15.        #endregion  
  16.   
  17.        public BotStateService(ConversationState conversationState, UserState userState)  
  18.        {  
  19.            ConversationState = conversationState ?? throw new ArgumentNullException(nameof(ConversationState));  
  20.            UserState = userState ?? throw new ArgumentNullException(nameof(userState));  
  21.   
  22.            InitializeAccessors();  
  23.        }  
  24.   
  25.        private void InitializeAccessors()  
  26.        {  
  27.            // Initialize Conversation State Accessor   
  28.            ConversationDataAccessor = ConversationState.CreateProperty<ConverstationData>(ConverstationDataId);  
  29.   
  30.            //Initialize User State   
  31.            UserProfileAccessor = UserState.CreateProperty<UserProfile>(UserProfileId);  
  32.        }  
  33.    }  
We are almost done. Now, we have to change the logic of our startup class to make sure we are running our greeting bot with our configurations. Change your startup class just like shown in the below code:
  1. public class Startup  
  2.    {  
  3.        public Startup(IConfiguration configuration)  
  4.        {  
  5.            Configuration = configuration;  
  6.        }  
  7.   
  8.        public IConfiguration Configuration { get; }  
  9.   
  10.        // This method gets called by the runtime. Use this method to add services to the container.  
  11.        public void ConfigureServices(IServiceCollection services)  
  12.        {  
  13.            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  14.   
  15.            // Create the Bot Framework Adapter with error handling enabled.  
  16.            services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();  
  17.   
  18.            //Configure State  
  19.            ConfigureState(services);  
  20.   
  21.            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.  
  22.            services.AddTransient<IBot, GreetingBot>();  
  23.        }  
  24.   
  25.        public void ConfigureState(IServiceCollection services)  
  26.        {  
  27.            //Create the Storage we'll be using for User and Converstation state. (Memory is great for testing purpose.)  
  28.            services.AddSingleton<IStorage, MemoryStorage>();  
  29.   
  30.            //var storageAccount = "DefaultEndpointsProtocol=https;AccountName=Your_Account_Name;AccountKey=Your_Azure_Account_Key;EndpointSuffix=core.windows.net";  
  31.            //var storageContainer = Your_Azure_Container;  
  32.   
  33.            //services.AddSingleton<IStorage>(new AzureBlobStorage(storageAccount, storageContainer));  
  34.   
  35.            //Create the user state.  
  36.            services.AddSingleton<UserState>();  
  37.   
  38.            //Create the Conversation state.  
  39.            services.AddSingleton<ConversationState>();  
  40.   
  41.            //Create an instance of the state service  
  42.            services.AddSingleton<BotStateService>();  
  43.        }  
  44.   
  45.        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  46.        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  47.        {  
  48.            if (env.IsDevelopment())  
  49.            {  
  50.                app.UseDeveloperExceptionPage();  
  51.            }  
  52.            else  
  53.            {  
  54.                app.UseHsts();  
  55.            }  
  56.   
  57.            app.UseDefaultFiles();  
  58.            app.UseStaticFiles();  
  59.            app.UseWebSockets();  
  60.            //app.UseHttpsRedirection();  
  61.            app.UseMvc();  
  62.        }  
  63.    }  
As I told you earlier, you can use Azure service as well for storage and I have commented out that code which you can use for your account. You have to provide your Account Name, Key and Container Name and instead of using MemoryStorage you can use AzureBlobStorage. All you need is to set up these in your Azure Account. 
One more thing I wanted to talk about is that you also have one file MpTeams Bot.bot in your solution which contains the configuration of your Bot just like in my case I have below configurations.
  1. {  
  2.     "name""MpTeams Bot",  
  3.     "description""",  
  4.     "services": [  
  5.         {  
  6.             "type""endpoint",  
  7.             "appId""",  
  8.             "appPassword""",  
  9.             "endpoint""http://localhost:3978/api/messages",  
  10.             "id""853a8e50-7e42-11ea-9ea2-5b5aa38ed7d7",  
  11.             "name""Development"  
  12.         }  
  13.     ],  
  14.     "padlock""",  
  15.     "version""2.0",  
  16.     "overrides"null,  
  17.     "path""C:\\Users\\ba35925\\Desktop\\MSTeamsBot\\MPTeams\\MpTeams Bot.bot"  
  18. }  
So, we are all set now lets run our Greeting Bot and see the changes. Once you connect your bot to your emulator, you should be able to see the below message:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
As you can see that our bot first greeted us and then asked for our name to store in its memory. Now as we have provided our name now let's see if it can remember our name next time when we start our conversation with our same userId. Now, select the below option on your emulator and check that our bot remembers our name or not.
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
You will see below message that our bot remembers our name and greet us:
 
Design And Develop A Greeting Bot using Microsoft Bot Framework On VS2019 Community Version
 
Awesome!!! So this is how you can use your bot to remember your names and many more things just like this one. I hope you enjoyed this tutorial. let me know for anything you want to know. I will try to help you out.


Similar Articles