Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Create an Intelligent Bot Application Using Microsoft Bot Framework

DZone's Guide to

Create an Intelligent Bot Application Using Microsoft Bot Framework

Learn how to use the Bot Framework Emulator, Microsoft Bot Framework, and ngrok to create an AI-based robot application.

· AI Zone ·
Free Resource

Insight for I&O leaders on deploying AIOps platforms to enhance performance monitoring today. Read the Guide.

In my previous article, we learned how to create and connect a chatbot with Azure Bot Service. Today, we're going to create an intelligent bot application using Microsoft Bot Framework.

First, we need to download ngrok software. But what is ngrok?

ngrok is a network tunneling software. The Bot Framework Emulator works with ngrok to communicate with bots hosted remotely. See here to download the ngrok network tunneling software.

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. We need to download Bot Framework Emulator for both local and server testing. See here to download Bot Framework Emulator.

After successful download, please run the exe file for Bot Framework Emulator. The first time you do this, it will open an App Settings window where we need to provide the exact path of ngrok in our system (provide the ngrok saved folder path in our system).

The following screenshot is saved into the C drive downloads folder (C:\Users\RajeeshMenoth\Downloads\ngrok).

When you connecting to a remote server or other than localhost, we need to provide BotId, MicrosoftAppId, and MicrosoftAppPassword in web.config and Bot Framework Emulator.We will get these from the Azure app settings in our created web app bot.

Microsoft Bot Framework in Visual Studio

Click on File > New > Project > Visual C# > Bot Application.

Note: If Bot Application Template is not present in Visual Studio 2015, go to Tools > Extensions and Updates. Then search for and install the bot application in Visual Studio.

Code

I just changed the default code for web app bot. Then, we added our own logic into this C# code in our bot application.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Connector;

namespace Bot_App
{
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        /// 

<summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>


        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // calculate something for us to return
                int length = (activity.Text ?? string.Empty).Length;
                Activity reply = activity.CreateReply("");

                // return our reply to the user
                switch (activity.Text)
                {
                    case "hi":
                    case "hello":
                        reply = activity.CreateReply($"{activity.Text} buddy, How may I assist you ?");
                        break;
                    case "how are you":
                        reply = activity.CreateReply($"Fine , What about you ?");
                        break;
                    case "Where are you ?":
                        reply = activity.CreateReply($"Bangalore , What about you ?");
                        break;
                    case "bye":
                        reply = activity.CreateReply($"Bye , Thank you !!");
                        break;
                    default:
                        reply = activity.CreateReply($"This is chat bot using Bot Framework !!");
                        break;
                }

                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

        private Activity HandleSystemMessage(Activity message)
        {
            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                IConversationUpdateActivity update = message;
                var client = new ConnectorClient(new Uri(message.ServiceUrl), new MicrosoftAppCredentials());
                if (update.MembersAdded != null && update.MembersAdded.Any())
                {
                    foreach (var newMember in update.MembersAdded)
                    {
                        if (newMember.Id != message.Recipient.Id)
                        {
                            var reply = message.CreateReply();
                            reply.Text = $"Welcome {newMember.Name}!";
                            client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return null;
        }
    }

}

Localhost

Run the bot application on the localhost. This will open our application with a localhost port number that we can use in Bot Framework Emulator.

The bot endpoint looks like this

http://your_bots_hostname"/api/messages&#8221;

Bot Endpoint

In the Bot Framework Emulator, we can add our localhost or remote server bot endpoint. We can directly connect the localhost port number in Bot Framework Emulator. Note that in the actual server endpoint, we need to give the Microsoft App ID and Microsoft App Password:

The actual endpoint of our chatbot comes from Apps Settings (for this, we need to create a web chatbot in Azure using Bot Service).

Application Settings

We will get all the credentials of our web chatbot app (Azure) in App Settings (for this, we need to create a web chatbot in Azure using Bot Service).

Output

Click on Connect to trigger the bot application.

Summary

We learned how to create an intelligent bot application using Microsoft Bot Framework. I hope this article is useful for all Azure chatbot beginners.

References

Download

See Also

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

TrueSight is an AIOps platform, powered by machine learning and analytics, that elevates IT operations to address multi-cloud complexity and the speed of digital transformation.

Topics:
ai ,tutorial ,bot development ,microsoft bot framework ,ngrok

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}