Introduction
Chatbots are becoming more popular nowadays with the release ofChatGPT, Google Bard, etc. ChatGPT is an etc.AI chatbot developed by Open AI that can write articles, give answers to questions, compose essays, etc. A chatbot is an application program that simulates human conversation and replies to users based on the data and rules on which the chatbot is trained. Chatbots are integrated intomobile application, websites, Facebook Messenger, etc. Chatbots utilize natural language processing (NLP) to understand the user’s intent and respond using AI-based decision-making.

In this guide, I’ll showyou to develop a chatbot for a real-world scenario. We will develop a chatbot to takedetails from users to register them for a conference.
Learning objectives
In this guide, we will learn:
- Understand the basics of bots and scenarios in which bots can be used.
- Steps to follow for developing a bot using Microsoft Bot Framework
- Learn about Microsoft Bot Framework’s important concepts and terminologies such as Activities, Turns, Bot Templates, etc.
- Bot design principles to design great bot conversation flow
- Develop a chatbot to take details from users to register them for a conference.
This article was published as a part of the Data Science Blogathon.
What is Bot?
Abotis an application program thatsimulates human conversationand replies to users based on the data and rules on which the bot is trained. Users communicate with a bot usingadaptive cards, forms, text, audio, images,etc. Bots can be used to perform tasks such as gathering information from users for booking a flight ticket, paying electricity bills, resolving user queries based on a FAQ document, etc. Bots recognize the intent of the user questions usingNLPand respond to them usingAI-based decision-making.

Design the botby keeping in mind the phrase, syntax, and other things used in human conversation. A great bot doesn’t require users to repeat themselves manytimes, has a good flow while gathering information, and gives a satisfactoryresponse to questions when asked in a twisted way. Based on the configuration,
the bot can respond to user messages using video, images, documents, etc. Bots are designed to intelligently respond to user queries, provide customerservices to the users, or help the user to perform tasks like ticket booking,paying bills, etc.

Users can interact withbots through a channel such as Slack, mobile applications, websites, FacebookMessenger, etc. Depending on the user’s response to a question, the bot can askthe additional relevant information from the user or access the services on theuser’s behalf. Then from the bot’s response, users can understand what the bothas done and make the required corrections based on the prompts provided by thebot.
ChatbotUse Case Scenarios
- Customer Service:Chatbots easily provide responses to common customer questions using FAQs. Many organizations use chatbots for providing customer service as chatbots can provide 24/7 support to users and boost the user experience with faster response time.

- Booking Appointment:Chatbot takes input from the users and based on user choices chatbots can easily book flight tickets, restaurant seats, etc.
- News Bots: Many news portals have chatbot services to recommend top news to their customers based on their area of interest.
What is Microsoft Bot Framework ?
Microsoft Bot Frameworkis a collection of functions, libraries, tools, and services that helpsdevelopers easily develop, debug, test, and deploy bots. Using Microsoft Bot Framework,developers can create bots having advanced capabilities such as NLP, gettingmore trained and increasingly valuable from user inputs, etc. Design the bot by keeping in mind the phrase, syntax, and other things used in humanconversation. Users can interact with bots through a channel such as Slack,mobile applications, websites, Facebook Messenger, etc.

Integrating other Azure Services with Microsoft Bot Framework
We can develop bots inC#, Python, Java, or JavaScript programming language using Bot Framework SDK.Bots developed using Microsoft Bot Framework can easily use other AzureServices such as Azure SQL, Azure Blob Storage, or Azure Cosmos DB for storagepurposes. We can use Azure Cognitive Services such as Custom QuestionAnswering, Azure LUIS, etc. in the bot to add NLP capabilities.
How to build a bot using Microsoft Bot Framework?
Follow the below steps tobuild a bot using Microsoft Bot Framework:
- Plan: Before building a bot, itis important to understand user needs to build a successful bot. For example, abot developed to resolve user queries based on a FAQ document should be able toidentify similar words and give a relevant response to the user.
- Build: We can develop a botusing Microsoft Bot Framework and deploy it to various channels using Azure BotService. For better usability, we can send responses to users in the form ofimages, audio, video, etc. Bots developed using Microsoft Bot Framework can easilyuse other Azure Services such as Azure SQL, Azure Blob Storage, or Azure CosmosDB for storage purposes. We can use Azure Cognitive Services such as CustomQuestion Answering, Azure LUIS, etc. in the bot to add NLP capabilities.

- Test: With the current versionof Bot Framework SDK, we can add Unit Tests to the bot. We can test the botlocally using Bot Framework Emulator.
- Publish: Once you complete development and testing, you can deploy bots to Azure or a web service.
- Connect: Connect the bot through achannel such as Slack, mobile applications, websites, Facebook Messenger, etc.
- Evaluate: We can analyze the datacollected after the bot deployment, to implement the bot performance.
KeyDevelopment Concepts in Microsoft Bot Framework
Below are some importantDevelopment Concepts in Microsoft Bot Framework:
Activities and Turns
All the interactions between users and botsare known as activities. Theinteraction may happen in the form of images, audio, video, text, etc. Innormal human conversation, people speak one at a time to express their opinion.Similarly, in bot conversation, thebot responds to the user when the bot turn came. Generally, at the start of a bot conversation, the bot greets the user. Based on the user’s query or action, the bot responds to the user using the data.
Event-Driven Conversations
The bot does event-driven conversations with the help of an activity handler. Based on the activity or sub-activity type, the bot decodes which activity handler will handle that activity. For example, whenever you add a new member to the bot conversation OnMembersAddedAsync()gets called to handle the user-welcoming logic.

Managing State and Storage in Bots
Microsoft Bot Framework SDKprovides state management functionalityand a storage layer to manage the data storage and states efficiently.Maintaining state helps in having better conversation flow as we can save theprovided by users in the previous turns which is very beneficial in amulti-turn conversation. Depending on the type of data, budget, andrequirement, we can use different data storage services such as Memory Storage, SharePoint Online, AzureSQL, Cosmos DB, Azure Blob storage, etc. for storing data.

Bot Templates
Microsoft Bot Framework provides several templatesfor developing bots in C# and Python. An emptybot template provides a basic code structure for the bot and greets theuser. The echo bot template providesthe functionality of echoing the text entered by the user. The core bot template provides LUIS, CustomQuestion Answering capabilities, component dialog, and child dialog toeffectively manage user conversations.
Intents, Entities, and Utterances
Intent is a task that the user wants to perform. Entities are important information orkeywords in a text. Utterances are the inputs given by the user. Forexample, in a flight booking scenario when a user provides input to a bot as “Book a flight from Mumbai to Pune for
24th May 2023”. Here, booking aflight is intent, Mumbai and Pune are entities, and Booking a flight from Mumbai to Pune for 24thMay 2023 is utterance.
Dialogs& Types of Dialogs
Dialogsprovide ways to manage conversations with users. We can pass arguments orparameters to dialogs. A dialog can be started, paused, resumed, or stopped.
Dialogs are very useful in implementing multi-turn conversations. For example, if we want to develop a bot that suggests weekend activities and highly rated restaurants based on the user’s input like their hobbies and favorite food, we can use dialogs. Bot Framework provides various types of dialogs such as waterfall dialog, prompt dialog, adaptive dialog, QnA Maker dialog,etc. to efficiently manage the conversation with users. For example, use a Prompt dialog to take input from theuser and validate input.

Principlesof Bot Design
Keep the below principlesin mind while designing a bot:
1. Design greatconversation flow: Users interact with the bot in a non-linear fashion. Theycan randomly ask different questions based on their requirement. Bots must havea great conversation flow to handle the above situation.
2. Create a great userexperience: A great user experience helps users to efficiently communicate withthe bot. To create a great user experience, we can use images, carousels, NLP,speech capability, etc. in the bot.
3. Use Rich usercontrols: Rich user controls such as adaptive cards, audio cards, video cards,suggested action cards, etc. give a better design to the bot.
DevelopingConference Registration Chatbot
Now, we have a goodunderstanding of the principles of bot design and Microsoft bot framework keyconcepts. Let’s now develop a bot for taking user details for registering themfor Analytics Vidhya Conference using the Core bot template, Prompts, andDialogs in the Microsoft bot framework. Follow the below steps:
1.Open Visual Studio-> Create NewProject-> Search for Empty Bot template and select it.

2. Click Next. Provide ConferenceBot as the Projectname and click Create.

3. Install the NuGet packages: AdaptiveCardsand Microsoft.Bot.Builder.Dialogs.Declarative

4. Create a new file ConferenceBot.cs inside the new folder Bots in the project. Paste the below code snippet in the file:
namespace ConferenceBot.Bots{ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AdaptiveCards; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Schema; using Microsoft.Extensions.Logging; using Newtonsoft.Json; public class ConferenceBot<T> : ActivityHandler where T : Dialog { protected readonly Dialog Dialog; protected readonly BotState ConversationState; protected readonly BotState UserState; protected readonly ILogger Logger; public ConferenceBot( ConversationState conversationState, UserState userState, T dialog, ILogger<ConferenceBot<T>> logger) { ConversationState = conversationState; UserState = userState; Dialog = dialog; Logger = logger; } public override async Task OnTurnAsync( ITurnContext tc, CancellationToken ct = default) { await base.OnTurnAsync(tc, ct); await ConversationState.SaveChangesAsync(tc, false, ct); await UserState.SaveChangesAsync(tc, false, ct); } protected override async Task OnMessageActivityAsync( ITurnContext<IMessageActivity> tc, CancellationToken ct) { Logger.LogInformation("Running dialog with Message Activity."); await Dialog.RunAsync(tc, ConversationState.CreateProperty<DialogState> (nameof(DialogState)), ct); }
Here, the OnTurnAsync method is used to process the action waiting on the queue. TheOnMessageActivityAsync method is called for processing the message activities. The Dialog conversation gets created and the dialog state is maintained to save data in memory.
protected override async Task OnMembersAddedAsync( IList<ChannelAccount> ca, ITurnContext<IConversationUpdateActivity> tc, CancellationToken ct) { var welcomeCard = CreateAdaptiveCardAttachment(); var welcomeResponse = MessageFactory.Attachment (welcomeCard, ssml: "Welcome to Conference Registration!"); foreach (var member in ca) { if (member.Id != tc.Activity.Recipient.Id) { await tc.SendActivityAsync(welcomeResponse, ct); } } } /// <summary> /// Adaptive Card for welcoming user /// </summary> /// <returns></returns> private static Attachment CreateAdaptiveCardAttachment() { AdaptiveCard weclomeCard = new AdaptiveCard(); weclomeCard.Body.Add(new AdaptiveTextBlock() { Text = "Conference Registration", Size = AdaptiveTextSize.Large, Wrap = true }); weclomeCard.Body.Add(new AdaptiveTextBlock() { Text = "30th April 2023, Pune", Size = AdaptiveTextSize.Medium }); weclomeCard.Body.Add(new AdaptiveImage() { Url = new Uri("image URI"), HorizontalAlignment = AdaptiveHorizontalAlignment.Center }); weclomeCard.Body.Add(new AdaptiveTextBlock() { Text = " Hi, data enthusiast.", Size = AdaptiveTextSize.Small, Wrap = true, Weight = AdaptiveTextWeight.Bolder }); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = weclomeCard }; return attachment; } }}
Here, OnMembersAddedAsync() gets called whena new user joins the conversation. CreateAdaptiveCardAttachment()returns adaptive card attachment. OnMessageActivityAsync()gets the requests from the user and handles them using Dialog.
5.Create a new fileConferenceDetailsDialog.csinside the new folder Dialog in the project with the help of the below code snippets:
var waterfallSteps = new WaterfallStep[] { FetchUserNameAsync, FetchUserEmailAsync, TransportStepAsync, OptionalAgeStepAsync, FetchUserAgeAsync, UploadProfileImageAsync, DataProcessConfirmationStepAsync, DataProcessingStepAsync, }; AddDialog(new WaterfallDialog( nameof(WaterfallDialog), waterfallSteps)); AddDialog(new TextPrompt( nameof(TextPrompt), ValidateNameAsync)); AddDialog(new TextPrompt( nameof(TextPrompt))); AddDialog(new ChoicePrompt( nameof(ChoicePrompt))); AddDialog(new NumberPrompt<int>( nameof(NumberPrompt<int>), ValidateAgeAsync)); AddDialog(new ConfirmPrompt( nameof(ConfirmPrompt))); AddDialog(new AttachmentPrompt( nameof(AttachmentPrompt), ValidateProfileImageAsync));
The above code snippet creates waterfall steps for taking data from the user.
private static async Task<DialogTurnResult> FetchUserNameAsync( WaterfallStepContext sc, CancellationToken ct) { return await sc.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text( "Please enter your name (must contain at least 3 characters and at most 200 characters)."), RetryPrompt = MessageFactory.Text("Invalid username"), } , ct); }
The above code snippet creates Text Promptwhich takes the username. The FetchUserEmailAsync, TransportStepAsync, and FetchUserAgeAsync methods stores name, email, and age and process the provided data.
private async Task<DialogTurnResult> FetchUserEmailAsync( WaterfallStepContext sc, CancellationToken ct) { sc.Values["name"] = (string)sc.Result;//logic }
private async Task<DialogTurnResult> TransportStepAsync( WaterfallStepContext sc , CancellationToken ct) { sc.Values["email"] = (string)sc.Result; //logic }
private async Task<DialogTurnResult> FetchUserAgeAsync( WaterfallStepContext sc, CancellationToken ct) { if ((bool)sc.Result) { var promptOptions = new PromptOptions { Prompt = MessageFactory.Text("Provide age:"), RetryPrompt = MessageFactory.Text("Invalid age."), }; return await sc. PromptAsync(nameof(NumberPrompt<int>), promptOptions, ct); } else { return await sc. NextAsync(-1, ct); } }
private static Task<bool> ValidateAgeAsync( PromptValidatorContext<int> pc, CancellationToken ct) { return Task.FromResult(pc.Recognized.Succeeded && pc.Recognized.Value > 0 && pc.Recognized.Value < 80); }
private static Task<bool> ValidateNameAsync( PromptValidatorContext<string> pc, CancellationToken ct) { return Task.FromResult(pc.Recognized.Succeeded && pc.Recognized.Value.Length > 3 && pc.Recognized.Value.Length < 200); }
The above code snippets validate the age and name entered by the user. Theage should be between 0 and 80. The length of thename should be between 3 and 200.
6. Click IISExpress and run the project.
Now,open Bot Framework Emulator to test the bot locally.


7.OpenBot Framework Emulator. Click Connect.
Conclusion
In this article, we haveseen how to develop a chatbot to take details from users to register them for aconference using Microsoft Bot Framework. An application program called a bot simulates human conversation and provides responses to users based on its training data and rules. Developers design bots to intelligently respond to user queries, offer customer services, and assist users with tasks such as ticket booking or bill payments. We have seen how to use prompts to take data from users. We also understand how to store gathered datatemporarily into in-memory. Below are the major takeaways from the above guide:
- We learned the best practices to be followedwhile designing the bot.
- We have also seen how to create a bot using Empty BotTemplate.
- We have also collected data from users using Prompts such asText Prompts, Choice prompts, Attachment Prompts, etc.
- We learned how to greet users using adaptive cardattachments.
- Apart from that, we have also seen how to test the developedbot using Bot Framework Emulator.
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.
Related
AzureblogathonbotbotschatbotchatbotsframeworkGuideMicrosoft