Create An Intelligent Bot Application Using Microsoft Bot Framework

Introduction
 
In our previous article, we learned how to Create and Connect a chatbot with Azure Bot Service. In this article, we are going to create an intelligent bot application using Microsoft Bot Framework.
 
ngrok Software 
 
So first we need to download ngrok software. What is ngrok ?
 
"ngrok" is a network tunneling software. The Bot Framework Emulator works with ngrok to communicate with bots hosted remotely. Click this link https://ngrok.com/download to download ngrok network tunneling software.
 
Bot Framework Emulator
 
The Bot Framework Emulator is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel. So we need to download Bot Framework Emulator for both local and server testing. So please go through this link to download Bot Framework Emulator click here.
 
After successful download please run the exe file for Bot Framework Emulator. Then first time it will open a "App Settings Window" there we need to provide the exact path of ngrok in our system ( Provide "ngrok" saved folder path in our system ).
 
The following screenshot "ngrok" saved into C drive Downloads folder ( C:\Users\RajeeshMenoth\Downloads\ngrok ).
 
Bot Framework
 
Web.config 
 
When you are connecting to remote server or anything other than local host then we need to provide the following credentials "BotId" & "MicrosoftAppId" & "MicrosoftAppPassword" in Web.Config and Bot Framework Emulator. This we will get it from azure "AppSettings" in our created Web App Bot.
  1. <configuration>  
  2.   <appSettings>  
  3.     <!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->  
  4.     <add key="BotId" value="YourBotId" />  
  5.     <add key="MicrosoftAppId" value="" />  
  6.     <add key="MicrosoftAppPassword" value="" />  
  7.   </appSettings>  
  8. </configuration>  
Microsoft Bot Framework In Visual Studio
 
Click on "File -> New -> Project -> Visual C# -> Bot Application"

Bot Framework
 
Note

If the Bot Application Template is not present in the Visual Studio 2015 then please go to "Tools -> Extensions and Updates". Then search and Install the "Bot Application" in our Visual Studio.

Bot Framework  
 
Code
 
I just changed the default code for Web App Bot. Then we added our own logic into this C# Code in Bot Application.
  1. using System;  
  2. using System.Linq;  
  3. using System.Net;  
  4. using System.Net.Http;  
  5. using System.Threading.Tasks;  
  6. using System.Web.Http;  
  7. using Microsoft.Bot.Connector;  
  8.    
  9. namespace Bot_App  
  10. {  
  11.     [BotAuthentication]  
  12.     public class MessagesController : ApiController  
  13.     {  
  14.         ///   
  15.    
  16. <summary>  
  17.         /// POST: api/Messages  
  18.         /// Receive a message from a user and reply to it  
  19.         /// </summary>  
  20.    
  21.    
  22.         public async Task<HttpResponseMessage> Post([FromBody]Activity activity)  
  23.         {  
  24.             if (activity.Type == ActivityTypes.Message)  
  25.             {  
  26.                 ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));  
  27.                 // calculate something for us to return  
  28.                 int length = (activity.Text ?? string.Empty).Length;  
  29.                 Activity reply = activity.CreateReply("");  
  30.    
  31.                 // return our reply to the user  
  32.                 switch (activity.Text)  
  33.                 {  
  34.                     case "hi":  
  35.                     case "hello":  
  36.                         reply = activity.CreateReply($"{activity.Text} buddy, How may I assist you ?");  
  37.                         break;  
  38.                     case "how are you":  
  39.                         reply = activity.CreateReply($"Fine , What about you ?");  
  40.                         break;  
  41.                     case "Where are you ?":  
  42.                         reply = activity.CreateReply($"Bangalore , What about you ?");  
  43.                         break;  
  44.                     case "bye":  
  45.                         reply = activity.CreateReply($"Bye , Thank you !!");  
  46.                         break;  
  47.                     default:  
  48.                         reply = activity.CreateReply($"This is chat bot using Bot Framework !!");  
  49.                         break;  
  50.                 }  
  51.    
  52.                 await connector.Conversations.ReplyToActivityAsync(reply);  
  53.             }  
  54.             else  
  55.             {  
  56.                 HandleSystemMessage(activity);  
  57.             }  
  58.             var response = Request.CreateResponse(HttpStatusCode.OK);  
  59.             return response;  
  60.         }  
  61.    
  62.         private Activity HandleSystemMessage(Activity message)  
  63.         {  
  64.             if (message.Type == ActivityTypes.DeleteUserData)  
  65.             {  
  66.                 // Implement user deletion here  
  67.                 // If we handle user deletion, return a real message  
  68.             }  
  69.             else if (message.Type == ActivityTypes.ConversationUpdate)  
  70.             {  
  71.                 // Handle conversation state changes, like members being added and removed  
  72.                 // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info  
  73.                 // Not available in all channels  
  74.                 IConversationUpdateActivity update = message;  
  75.                 var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());  
  76.                 if (update.MembersAdded != null && update.MembersAdded.Any())  
  77.                 {  
  78.                     foreach (var newMember in update.MembersAdded)  
  79.                     {  
  80.                         if (newMember.Id != message.Recipient.Id)  
  81.                         {  
  82.                             var reply = message.CreateReply();  
  83.                             reply.Text = $"Welcome {newMember.Name}!";  
  84.                             client.Conversations.ReplyToActivityAsync(reply);  
  85.                         }  
  86.                     }  
  87.                 }  
  88.             }  
  89.             else if (message.Type == ActivityTypes.ContactRelationUpdate)  
  90.             {  
  91.                 // Handle add/remove from contact lists  
  92.                 // Activity.From + Activity.Action represent what happened  
  93.             }  
  94.             else if (message.Type == ActivityTypes.Typing)  
  95.             {  
  96.                 // Handle knowing tha the user is typing  
  97.             }  
  98.             else if (message.Type == ActivityTypes.Ping)  
  99.             {  
  100.             }  
  101.    
  102.             return null;  
  103.         }  
  104.     }  
  105.    
  106. }  
Localhost
 
Run our Bot Application in local then it will open our application with a localhost port number. So we can use this in our "Bot Framework Emulator".
 
The bot endpoint like this : "http://your_bots_hostname/api/messages"

Bot Framework
Bot Endpoint
 
In the Bot Framework Emulator we can add our localhost or remote server "bot end point". We can directly connect localhost port number in Bot Framework Emulator. But note that in the actual server endpoint we need to given "Microsoft App ID" and "Microsoft App Password".

Bot Framework  
 
Actual endpoint of our chat bot is getting from Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Bot Framework
 
Application Settings
 
We will get all the credentials of our Web Chat Bot App ( Azure ) in Apps Setting ( for this we need to create a Web Chat Bot in Azure Using Bot Service ).

Bot Framework
 
Output
 
Click on the "Connect" then it will trigger our Bot Application.

Bot Framework  
 
Download
Summary
 
We learned how to Create An Intelligent Bot Application Using Microsoft Bot Framework. I hope this article is useful for all Azure chat bot beginners.
 
Reference
See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.


Similar Articles