ChatBot with Microsoft Bot Framework and QnA

The rising wave of artificial intelligence (AI) in the last couple of years has given a massive push to the idea of conversational interfaces, commonly known as chatbots. Many companies (like IBM. Google, Microsoft, Facebook) have joined forces to boost the growth of various aspects of AI, including natural language processing and machine learning. These companies have tirelessly created platforms and tools to help developers and businesspersons to improve the process of integrating such technology into their own products and businesses. 

The Microsoft Bot Framework is providing support to integrate a chatbot with existing platform such as Slack, Facebook, Skype, Alexa, Twilio, LINE, Telegram and many more. Microsoft made its Bot Builder available as an open-source SDK, not just on .NET, but also on Node.js and a REST API. So, in this article we will focus on creating a chatbot using the Microsoft Bot Framework.

Software requirements:

  • .Net Core SDK (2.1 or higher)
  • Visual Studio 2017 or later
  • Bot Framework SDK Template
  • Microsoft Bot Framework Emulator

About Microsoft Bot Framework

The Microsoft Bot Framework is a powerful set of services, tools, and SDKs that provides a rich foundation or “framework” for developers to build and connect intelligent bots. The Bot Framework is built to be intelligent and learn from user interaction. User interaction can be possible via Chatting or Text/SMS to Skype, Mail, Telegram, SMS, etc.

From basic chatbots to intelligent virtual assistants, you can build pretty much anything with the Microsoft Bot Framework.

About Microsoft Bot Framework Emulator

The Bot Framework Emulator is a cross-platform desktop application that allows bot developers to test and debug bots built using the Bot Framework SDK. You can use the Bot Framework Emulator to test bots running locally on your machine or to connect to bots running remotely.

About QnA Maker

QnA Maker is a cloud-based API service that creates a conversational, question-and-answer layer over your data. With QnA Maker, you can build, train and publish a simple question and answer bot based on FAQ URLs, structured documents, product manuals or editorial content in minutes.

About Bot Builder Template

Bot Framework provides us with a basic template that helps developers to build bots more quickly. This template comes with reference to essential libraries so that developers don’t have to tweak into basics to start building a bot every time.

About QnA Maker service

QnA Maker is a cloud-based API service that lets you create a conversational question-and-answer layer over your existing data. Use it to build a knowledge base by extracting questions and answers from your semi-structured content, including FAQs, manuals and documents.

Set up a QnA maker service

Please refer the below link and create a knowledge base and add questions and answers,select%20Create%20a%20QnA%20service.

Create a project 

  • Open Visual Studio 2017 or later.
  • Click on File -> New Project -> Bot Framework -> Core Bot (Bot Framework v4 – .Net Core 2.1)

  • Enter the name of the project (e.g. FirstQnABot), select the location of the project and click “Ok” 
  • Visual Studio will create a chatbot project with default folders and files.

  • By default, Visual Studio creates a demo chatbot project of flight booking. 
  • Build the project
  • Now run the project from the Visual Studio command prompt, as described below

Visual Studio Command Prompt

  • Open the Visual Studio Developer Prompt

Start -> Visual Studio 2017 -> Developer Command Prompt for VS 2017

  • Navigate to the project directory (E.g. D:\Sources\bots\FirstQnABot\FirstQnABot). This directory must contain the project file (e.g. FirstQnABot.csproj).
  • Type the command “dotnet run” and press Enter
  • It runs the chatbot code
  • Copy the listening on URL (e.g. http://localhost:3978). It will be used later (when we test the chatbot).
  • To test the chatbot in a local environment, we will use Microsoft Bot Emulator. Follow the below steps to test the chatbot

Microsoft Bot Emulator

  • Start the Microsoft Bot Emulator

  • Click on the “Open Bot” button
  • Enter Bot URL, from the previous step and add “/api/messages” text at the end

e.g. http://localhost:3978/api/messages

Refer below screen shot

  • Click “Connect” button
  • It will show Welcome message and ask the question like “Where would you like to travel to?”

  • To stop the chatbot conversion anytime, press Ctrl + C in the Visual Studio command prompt 
  • The chatbot will stop listening to any message and Bot Emulator will not provide any response after this.

Now change the code for Echo bot functionality.

  • Comment the code in the Bots\DialogAndWelcomeBot.cs file

// Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(“DialogState”), cancellationToken);

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)


            foreach (var member in membersAdded)


                if (member.Id != turnContext.Activity.Recipient.Id)


                    var welcomeCard = CreateAdaptiveCardAttachment();

                    var response = MessageFactory.Attachment(welcomeCard);

await turnContext.SendActivityAsync(response, cancellationToken);

                    //await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(“DialogState”), cancellationToken);




To test the Echo feature

  • Build the project
  • From the Visual Studio Command prompt, execute the “dotnet run” command (as described above) to run the code
  • Connect the Bot Emulator (as described above) and type any message.
  • Whatever message you will type, the bot will reply you with “Message from Bot: <your message>”

Alter the code for question-answer feature

QnA Maker

  • As described in the “Set up a QnA maker service” section of this document, create & configure a knowledge base with questions and answers.
  • In the QnA maker site, click on the “My knowledge bases” link. It will open your knowledgebase
  • Now click on the “View Code” button and copy the content

  • It will open a pop-up window with content like shown below. Now copy this knowledge base id, host URL and endpoint key. It will be used, later in the code.

POST /knowledgebases/yourKnowledgeBaseId/generateAnswer


Authorization: EndpointKey endpointId

Content-Type: application/json

  • Add a reference of “Microsoft.Bot.Builder.AI.QnA” nuget package in the project.
  • Add the HttpClientFactory’s client object in the ConfigureServices method of Startup class. This client object will be used to call QnAMaker 


  • Update the constructor of DialogAndWelcomeBot class by adding IHttpClientFactory object as a parameter and pass it to the base constructor.

public DialogAndWelcomeBot(ConversationState conversationState, UserState userState, T dialog, ILogger<DialogBot<T>> logger, IHttpClientFactory httpClientFactory) : base(conversationState, userState, dialog, logger, httpClientFactory)



  • Define a global reference object of IHttpClientFactory interface in DialogBot class.

protected readonly IHttpClientFactory ClientFactory;

  • Add a reference of QnA library, which we added, in the DialogBot class

using Microsoft.Bot.Builder.AI.QnA;

  • Update the constructor of DialogBot class. Add IHttpClientFactory object parameter in the constructor.

public DialogBot(ConversationState conversationState, UserState userState, T dialog, ILogger<DialogBot<T>> logger, IHttpClientFactory httpClientFactory)


            ConversationState = conversationState;

            UserState = userState;

            Dialog = dialog;

            Logger = logger;

            ClientFactory = httpClientFactory;


  • Now update the code in OnMessageActivityAsync method of DialogBot class as mentioned below. You can also copy the below code (make sure to replace your knowledgebase id, endpoint key and host)

//>> Start QnA Service Code

var httpClient = ClientFactory.CreateClient();

var qnaMaker = new QnAMaker(new QnAMakerEndpoint


    KnowledgeBaseId = “876e90lo-c121-4a22-11dd-f9087ww9081q”,

    EndpointKey = “3a45q3wq-9856-1234-c4uo-g980e8877fgb”,

    Host = “”

}, null, httpClient);

Logger.LogInformation(“Calling QnA Maker”);

var options = new QnAMakerOptions { Top = 1 };

var response = await qnaMaker.GetAnswersAsync(turnContext, options);

if (response != null && response.Length > 0)


Await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);




await turnContext.SendActivityAsync(MessageFactory.Text(“No QnA Maker answers were found.”), cancellationToken);


//<< End QnA Service Code

// await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);

  • Now build the code again.
  • Open the Visual Studio Command prompt, and run the code (as mentioned above)
  • Once the code start listening to a URL (e.g. http://localhost:3978), open the Microsoft Bot Emulator and test the code (as describe above).
  • You can enter the question (which you added in the QnAMaker service) and see whether the chatbot is returning the same answer, which you had defined in the QnAMaker service or not.

Final Testing

     Please find below couple of questions and answers I added in the QnA maker service

Question 1:

  • Good Morning
  • Good Afternoon
  • Good Evening
  • GM
  • Hi
  • Hello

Answer 1:

  • Welcome to AFour Virtual Assistant

     Question 2:

  • Salary slip
  • Where can I get my salary slip?
  • Download a salary slip

      Answer 2:

     Question 3: 

  • Please let me know about the company
  • Please tell us about the company
  • About the AFour Technology

      Answer 3:

  To test the chatbot for QnA maker service, enter any of the above question and check you will get the appropriate answer or not

Great! You have successfully created a chatbot using Microsoft Bot Framework and QnA service. Hopefully, I have demonstrated that you can create a chatbot using Microsoft Bot Framework and QnA Maker service. 


In this blog we have looked at the Microsoft Bot Framework, some of its key components, how you can build and test chat bots, and looked at a sample application. We also introduced the QnA Maker service, and how you can use it in the chatbot. I hope these features will help you to create some neat bots. We tested the bot using Microsoft Bot Emulator.

The Microsoft Bot Framework gives us a lot of possibilities and freedom of choice. Together with the powerful cognitive services we have quite an interesting technology in our hands. The QnA Maker service is another example how Microsoft is continuing to offer solutions to help make it easier for you to build smart bots.

I hope you have enjoyed and learned something new in this article.

Author: Tejashkumar Mistry

Leave a Reply