Designing a Conference Registration Chatbot with Microsoft Bot Framework

Chaitanya Shah 01 Mar, 2024 • 10 min read

Introduction

Chatbots are becoming more popular nowadays with the release of ChatGPT, 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 Microsoft Bot Framework Chatbot Development 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 into mobile 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 show you to develop a chatbot for a real-world scenario. We will develop a chatbot to take details from users to register them for a conference.

Learning objectives

In this guide, we will learn:

  1. Understand the basics of bots and scenarios in which bots can be used.
  2. Steps to follow for developing a bot using Microsoft Bot Framework
  3. Learn about Microsoft Bot Framework’s important concepts and terminologies such as Activities, Turns, Bot Templates, etc.
  4. Bot design principles to design great bot conversation flow
  5. 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?

bot is an application program that simulates human conversation and replies to users based on the data and rules on which the bot is trained. Users communicate with a bot using adaptive 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 using NLP and respond to them using AI-based decision-making.

Design the bot by keeping in mind the phrase, syntax, and other things used in human  conversation. A great bot doesn’t require users to repeat themselves many times, has a good flow while gathering information, and gives a satisfactory response 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 customer services to the users, or help the user to perform tasks like ticket booking, paying bills, etc.

Users can interact with bots through a channel such as Slack, mobile applications, websites, Facebook Messenger, etc. Depending on the user’s response to a question, the bot can ask the additional relevant information from the user or access the services on the user’s behalf. Then from the bot’s response, users can understand what the bot has done and make the required corrections based on the prompts provided by the bot.

Chatbot Use 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 Framework Chatbot Development is a collection of functions, libraries, tools, and services that helps developers easily develop, debug, test, and deploy bots. Using Microsoft Bot Framework, developers can create bots having advanced capabilities such as NLP, getting more trained and increasingly valuable from user inputs, etc. Design the bot by keeping in mind the phrase, syntax, and other things used in human conversation. Users can interact with bots through a channel such as Slack, mobile applications, websites, Facebook Messenger, etc.

Source: O’Reilly

Integrating other Azure Services with Microsoft Bot Framework

We can develop bots in C#, Python, Java, or JavaScript programming language using Bot Framework SDK. Bots developed using Microsoft Bot Framework Chatbot Development can easily use other Azure Services such as Azure SQL, Azure Blob Storage, or Azure Cosmos DB for storage purposes. We can use Azure Cognitive Services such as Custom Question Answering, Azure LUIS, etc. in the bot to add NLP capabilities.

How to build a bot using Microsoft Bot Framework?

Follow the below steps to build a bot using Microsoft Bot Framework:

  • Plan: Before building a bot, it is important to understand user needs to build a successful bot. For example, a bot developed to resolve user queries based on a FAQ document should be able to identify similar words and give a relevant response to the user.
  • Build: We can develop a bot using Microsoft Bot Framework Chatbot Development and deploy it to various channels using Azure Bot Service. For better usability, we can send responses to users in the form of images, audio, video, etc. Bots developed using Microsoft Bot Framework can easily use other Azure Services such as Azure SQL, Azure Blob Storage, or Azure Cosmos DB for storage purposes. We can use Azure Cognitive Services such as Custom Question Answering, Azure LUIS, etc. in the bot to add NLP capabilities.
bot framework | chatbot
  • Test: With the current version of Bot Framework SDK, we can add Unit Tests to the bot. We can test the bot locally 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 a channel such as Slack, mobile applications, websites, Facebook Messenger, etc.
  • Evaluate: We can analyze the data collected after the bot deployment, to implement the bot performance.

Key Development Concepts in Microsoft Bot Framework

Below are some important Development Concepts in Microsoft Bot Framework:

Activities and Turns

All the interactions between users and bots are known as activities. The interaction may happen in the form of images, audio, video, text, etc. In normal human conversation, people speak one at a time to express their opinion. Similarly, in bot conversation, the bot 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.

event driven conversations on chatbot

Managing State and Storage in Bots

Microsoft Bot Framework SDK provides state management functionality and a storage layer to manage the data storage and states efficiently. Maintaining state helps in having better conversation flow as we can save the provided by users in the previous turns which is very beneficial in a multi-turn conversation. Depending on the type of data, budget, and requirement, we can use different data storage services such as Memory Storage, SharePoint Online, Azure SQL, Cosmos DB, Azure Blob storage, etc. for storing data.

chatbot

Bot Templates

Microsoft Bot Framework provides several templates for developing bots in C# and Python. An empty bot template provides a basic code structure for the bot and greets the user. The echo bot template provides the functionality of echoing the text entered by the user. The core bot template provides LUIS, Custom Question Answering capabilities, component dialog, and child dialog to effectively manage user conversations.

Intents, Entities, and Utterances

Intent is a task that the user wants to perform. Entities are important information or keywords in a text. Utterances are the inputs given by the user. For example, 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 a flight is intent, Mumbai and Pune are entities, and Booking a flight from Mumbai to Pune for 24th May 2023 is utterance.

Dialogs & Types of Dialogs

Dialogs provide ways to manage conversations with users. We can pass arguments or parameters 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 the user and validate input.

chatbot

Principles of Bot Design

Keep the below principles in mind while designing a bot:

  • Design great conversation flow: Users interact with the bot in a non-linear fashion. They can randomly ask different questions based on their requirement. Bots must have a great conversation flow to handle the above situation.
  • Create a great user experience: A great user experience helps users to efficiently communicate with the bot. To create a great user experience, we can use images, carousels, NLP, speech capability, etc. in the bot.
  • Use Rich user controls: Rich user controls such as adaptive cards, audio cards, video cards, suggested action cards, etc. give a better design to the bot.

Developing Conference Registration Chatbot

Now, we have a good understanding of the principles of bot design and Microsoft Bot Framework Chatbot Development key concepts. Let’s now develop a bot for taking user details for registering them for Analytics Vidhya Conference using the Core bot template, Prompts, and Dialogs in the Microsoft bot framework. Follow the below steps:

1. Open Visual Studio-> Create New Project-> Search for Empty Bot template and select it.

"

2. Click Next. Provide ConferenceBot as the Project name and click Create.

"

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

Microsoft Bot Framework | chatbot

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. The OnMessageActivityAsync 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 when a 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 file ConferenceDetailsDialog.cs inside 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 Prompt which 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. The age should be between 0 and 80. The length of the name should be between 3 and 200.

6. Click IISExpress and run the project.

Now, open Bot Framework Emulator to test the bot locally.

Bot framework emulator | chatbot
Chatbot

7. Open Bot Framework Emulator. Click Connect.

Conclusion

In this article, we have seen how to develop a chatbot to take details from users to register them for a conference using Microsoft Bot Framework Chatbot Development. 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 data temporarily into in-memory. Below are the major takeaways from the above guide:

  • We learned the best practices to be followed while designing the bot.
  • We have also seen how to create a bot using Empty Bot Template.
  • We have also collected data from users using Prompts such as Text Prompts, Choice prompts, Attachment Prompts, etc.
  • We learned how to greet users using adaptive card attachments.
  • Apart from that, we have also seen how to test the developed bot using Bot Framework Emulator.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Frequently Asked Questions

Q1. What is Microsoft Bot Framework?

A. Microsoft Bot Framework is a platform that enables developers to build, deploy, and manage intelligent chatbots and conversational agents. It provides tools, SDKs, and services for creating bots to interact with users across various channels like websites, messaging apps, and voice assistants.

Q2. Is Microsoft Bot free?

A. Yes, the Microsoft Bot Framework offers a free tier that allows developers to build and deploy bots without incurring additional costs. However, certain premium features and services may have associated costs, depending on the usage and requirements of your bot.

Q3. How do I learn Microsoft Bot Framework?

A. To learn Microsoft Bot Framework, you can start by visiting the official documentation and exploring the various tutorials and guides Microsoft provides. Additionally, online courses, community forums, and code samples are available to help you get started and gain proficiency in building bots using the framework.

Q4. What is the benefit of Microsoft Bot Framework?

A. The Microsoft Bot Framework offers several benefits, including cross-platform compatibility, a rich bot development ecosystem, Natural Language Processing (NLP) integration, and scalability and reliability.

Chaitanya Shah 01 Mar 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers