Guided Conversations In Chatbot App Using FormFlow Of Microsoft Bot Framework

In my previous articles on Microsoft Bot Framework, we have seen bot creation and its integration with QnA maker service, LUIS, and SharePoint authentication. In these bot apps, we have used Dialogs for managing messages between a bot and a user. In this article, we will discuss FormFlow which will help us to manage guided conversations.

Highlights of the article

  • Create form fields, attributes for fields.
  • Build a form and initiate a conversation, form close or exception handling.

You can pull code from GitHub.

Prerequisite

We can manage guided conversations by chaining the dialogs. In this case, we need to create and manage the dialogs. Developing a bot app with same functionality using FormFlow will take much fewer development efforts (but with less flexibility). We can also use a combination of Dialogs and FormFlow as per need.

Let’s take an example of bot using which, the user will register for New Year’s Eve in local restro-bar. I am going to use the same solution which we created in article Quick start - Development Of Chat Bot Using Microsoft Bot Framework - For Beginners

I have added a new folder named Forms and two class files named as PartyRegistrationForm.cs and PartyRegistrationController.cs.

 

Property added to PartyRegistrationForm class will be considered as a field on a form. Field types supported by FormFlow are Integral (sbyte, byte, short, ushort, int, uint, long, ulong), Floating point (float, double), String, DateTime, Enumeration, List of enumerations. We are going to add each type of field in our form. I have also added attributes for properties of the class to update behavior while form rendering.

Property Type
Name String
Gender Enumeration
ArrivalTime DateTime
TotalAttendees Integral
CuisinesPreferences List of enumerations
ComplementoryDrink Enumerations
  1. [Prompt("May I know your good name?")]    
  2. public string Name; // type: String    

Prompt attribute will prompt user with the mentioned text and user input will be saved as property value. 

  1. [Optional]  
  2. [Template(TemplateUsage.EnumSelectOne, "Please select gender, if you want else you can skip. {||}", ChoiceStyle = ChoiceStyleOptions.Buttons)]  
  3. public GenderOpts? Gender; // type: Enumeration  

We have marked Gender property as non-mandatory using Optional attribute. Template attribute will help us to render gender options as buttons as I have specified ChoiceStyle. We can also provide prompt as parameter. {||} will be used to display available values for this property in prompt.

  1. [Prompt("What will be your arrival time?")]  
  2. public DateTime ArrivalTime; // type: DateTime  
  3.   
  4. [Numeric(1, 6)]  
  5. [Prompt("How many guests are accompanying you?<br>If more than 3, you will get complementory drink ! :)")]  
  6. public Int16 TotalAttendees; // type: Integral  

We have added Numeric attribute to restrict value for this property between 1 and 6. If user provides value other than these values it will prompt user with invalid input.

  1. [Prompt("Which type of cuisines you would like to have? {||}")]  
  2. public List<CuisinesOpts> CuisinesPreferences; // type: List of enumerations  

Prompt attribute will prompt user the mentioned text and {||} is used to display possible values for this property.

  1. [Template(TemplateUsage.EnumSelectOne, "Which complementory drink you would like to have? {||}", ChoiceStyle = ChoiceStyleOptions.Carousel)]    
  2. public ComplementoryDrinkOpts? ComplementoryDrink; // type: Enumeration  

I mentioned ChoiceStyle as Carousel, it will help to render possible values as carousel, which will enhance the user experience.

We have completed specifying the fields for a registration form.

Now, it's time to build and call the form. For building a form, I have added static BuildForm method in our PartyRegistrationForm class.
  1. public static IForm<PartyRegistrationForm> BuildForm()  
  2.         {  
  3.             return new FormBuilder<PartyRegistrationForm>()  
  4.                     .Message("Hey, Welcome to the registration for New Year's Eve party !")  
  5.   
  6.                     .Field(nameof(Name))  
  7.                     .Field(nameof(Gender))  
  8.                     .Field(nameof(ArrivalTime))  
  9.                     .Field(nameof(TotalAttendees))  
  10.                     .Field(nameof(CuisinesPreferences)) 
  11.  
  12.                     .Field(new FieldReflector<PartyRegistrationForm>(nameof(ComplementoryDrink))  
  13.                         .SetType(null)  
  14.                         .SetActive(state => state.TotalAttendees > 3)  
  15.                         .SetDefine(async (state, field) =>  
  16.                         {  
  17.                             field  
  18.                             .AddDescription(ComplementoryDrinkOpts.Beer, Convert.ToString(ComplementoryDrinkOpts.Beer), "<<image path>>")  
  19.                             .AddTerms(ComplementoryDrinkOpts.Beer, Convert.ToString(ComplementoryDrinkOpts.Beer))  
  20.   
  21.                             .AddDescription(ComplementoryDrinkOpts.Scotch, Convert.ToString(ComplementoryDrinkOpts.Scotch), "<<image path>>")  
  22.                             .AddTerms(ComplementoryDrinkOpts.Scotch, Convert.ToString(ComplementoryDrinkOpts.Scotch))  
  23.   
  24.                             .AddDescription(ComplementoryDrinkOpts.Mojito, Convert.ToString(ComplementoryDrinkOpts.Mojito), "<<image path>>")  
  25.                             .AddTerms(ComplementoryDrinkOpts.Mojito, Convert.ToString(ComplementoryDrinkOpts.Mojito));  
  26.   
  27.                             return true;  
  28.                         }))  

  29.                     .Confirm(async (state) =>  
  30.                     {  
  31.                         return new PromptAttribute("Hi {Name}, Please review your selection. No. of guests: {TotalAttendees}, Cuisines: {CuisinesPreferences}. Do you want to continue? {||}");  
  32.                     })  
  33.                     .Build();  
  34.         }  
We are creating a form using FormBuilder object by specifying various parameters. Using Message method, we can display a welcome message to the user. By specifying Field method, we can manage a sequence of fields in the form. If we don't specify fields here, fields will be displayed on the form by a sequence of their definition as class properties. Confirm method is used to prompt the user before final submission of registration form.
 
The entry point of the conversation is our Controller, hence we will call our BuildForm method from the Controller file. We can handle form cancellation as an exception. We will catch FormCanceledException. 
  1. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)  
  2.     {  
  3.         if (activity.Type == ActivityTypes.Message)  
  4.         {  
  5.             await Conversation.SendAsync(activity, MakeForm);  
  6.         }  
  7.         else  
  8.         {  
  9.             HandleSystemMessage(activity);  
  10.         }  
  11.         var response = Request.CreateResponse(HttpStatusCode.OK);  
  12.         return response;  
  13.     }  
  14.   
  15.     internal static IDialog<PartyRegistrationForm> MakeForm()  
  16.     {  
  17.         return Chain.From(() => FormDialog.FromForm(PartyRegistrationForm.BuildForm)).Do(async (context, registration) =>  
  18.             {  
  19.                 try  
  20.                 {  
  21.                     var completed = await registration;  
  22.                     await context.PostAsync("You are registerd. Have a happy time with us.");  
  23.                 }  
  24.                 catch (FormCanceledException<PartyRegistrationForm> e)  
  25.                 {  
  26.                     string reply = null == e.InnerException ? $"Hey, you quit the registration. Dont miss out the party!" : "Sorry, Could not register you. Please try again.";  
  27.                     await context.PostAsync(reply);  
  28.                 }  
  29.             });  
  30.     }  
Now, let's test the bot. Hit F5 and open emulator. Put URL http://localhost:<<port>>/api/PartyRegistration and click "Connect". Start the conversation and enter "Hi". It will greet you welcome and prompt you for the first field name.

 
Please specify Name and press Enter. Then, it will ask for gender. As we have marked gender as optional, it is showing No Preference option. Then, specify the arrival time.

 
Now, it will ask for the number of guests and will also provide offers for more than 3 guests. We have specified SetActive property of field ComplementoryDrink when the value of property TotalAttendees is greater than 3. If we specify the value for no. of guests as less than or equal to 3, then it will not prompt for complementary drink selection.
 
    
            
 At the end of the form, it will prompt for confirmation. If the user confirms, it will display a success message.
 
That's all regarding the usage of FormFlow in ChatBot application. In next articles, we will look into implementation with a combination of Dialogs and FormFlows. Until then, keep chatting with your bot!


Similar Articles