Share via


Bot Framework: Creating Booking Assistant chatbot

Introduction 

The Bot Framework enables you to build bots that support different types of interactions with users. You can design conversations in your bot to be freeform. Your bot can also have more guided interactions where it provides the user choices or actions. The conversation can use simple text strings or more complex rich cards that contain text, images, and action buttons. And you can add natural language interactions, which let your users interact with your bots in a natural and expressive way.

Bot Builder SDK introduced Form Flow, it will automatically generate the dialogs conversation based on your property and type that is specified on a class.

In this wiki, will help you to customize the forming process, change prompt text, field order and how to add condition field. We are going to edit bus booking bot and add validation and form flow attribute. 

https://2.bp.blogspot.com/-D1ssrkrl_RI/XCO0hs86z-I/AAAAAAAAUKE/9SCePLt2HiQHi9hEzrFQamFY04qp8uukgCLcBGAs/s640/FormFlowDemo.gif

Customize Form Flow Property Text

Prompt Text

​The Form Flow provides default prompt text-based o the property name; for example, Email Property default prompt text is “Please enter email “ but Bot Framework provides feature for customizing text using prompt attribute like below.

[Prompt("When you are starting from")]  
public DateTime? StartDate

https://lh6.googleusercontent.com/kqFYGK4XyPSMrJr7XqgeDexh8FoLcL9b2qrYqYhjqDNIqhXDpXXhUGt1fexbf7UYKooDEOZqvkVbwgGQJh6LZg2Ky4zBrlst6R8uADzs_TcI2y-uxO9tpWosyQIi2fNpWbTI-WXBcxGDzDriTA

Enum List Item with Prompt text

The following code shows the prompt text with the list of data .You can add custom prompt text and add pattern language({&},{||} ) to dynamically populate list of data at runtime.

[Prompt("You can Select {&}  {||}")]  
   public FromCity? FromAddress;  
   [Prompt("You can Select {&}  {||}")]  
   public ToCity? ToAddress;

The output looks like below

https://lh3.googleusercontent.com/0Ij5YJ85yDFzV-2kk12yaPzSKhGysY_JbzXnjRAxkbLo9NeB4BcJNjshmNs44WAiULwyztZrxPbMe92haAPkrr_vuUFi-8GQSqFURdZiQSrJwne6uQDKeJc41bhy0N7M4yku2q5F3aMQV-jEQw

Form Flow User Input Validation

Numeric field

The Numeric attribute is used to specify and restrict the range of allowed values for a numeric field. The following code allows a number between 1 and 5.

[Numeric(1,5)]  
  public int? NumberofSeat;

If user provide value above 5 or below 1 , bot will show the validation message like below

https://lh6.googleusercontent.com/DDQ1UXGz5a9NULTRReqao8ZC2s3sQZtQxFT1ZVxpcuOyMjblrYmRKX-dgYMX_kx_I86_wWLT9IQxc-aHEqL6mYjEu-9jpRnUWrMWFEkjZPTUMUoNCX7q1sL_kq89_D5Pf7qDp8Ajf5RbQ1Ijkw

Optional Field

In the Form Flow attribute, by default, every field is required and must be filled in the form. If you specify the Optional attribute, it will select as “No preference “.

[Optional]  
    public string  Address;

The Optional Field type output look like below

https://lh6.googleusercontent.com/JMAH-aeshjq6fs271WkGf_50bqVP9O4NuD6PX9wycieP_Dg1vEP_oAbvHzoq97qwnMm8kOFtGn-izqhzo58huvlh2lqu0Xfjm1uQebpWJ3U8ekc6-oz-hM5VAzIgHuBMzOcz_gUzXHvwPbdXfw

Pattern field

A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. You can add regular expressions into pattern attribute and validate the user input. The following code will validate user email id .

[Pattern(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]  
    public string  Email;

The below output shows a user trying provide invalid email id, immediately bot will reply and ask for valid email

https://lh5.googleusercontent.com/74cAUXYBvleTaO9R0GC-5uAJO8OiFqVI5j-kclhP4jlFJEJsDs_nvurunsIjmu3_uYLXkowmjmPXknH8Bo-CoenCh0Le0rWwErI6KOnLdUU8s_KxnNacblvzQBHZLvmzVGUpAAUV7RN1w1AFaA

Terms

You can add the Terms attribute to match the user input. When we ask the user for gender they are presented with buttons for them to choose between Male or Female. However, they don’t have to use the buttons and can instead type their answer if they wish.  By default, if the user types their answer they must enter the choice exactly, e.g. “Male” or “Female”, but in the context of a natural conversation the user might say something like “M” or “girl”. 

/// <summary>  
    /// Gender  
    /// </summary>  
public enum  Gender  
    {  
      [Terms("M","boy")]  
       Male,  
      [Terms("F","girl")]  
       Female  
  
    }

The Form Flow is like below and the user can select or provide term

https://lh6.googleusercontent.com/qO2bvNGB_KWcDtNZ5zpRtKpRQLoWIJChlNiB993R-Hx3l6NJnxuKOqNhApK4BNyYHD8emsudnn0z02aQjUjuIXkgoLC259YakchUMWO9rbwfC3UP3-K5LnGYrsZS44LFwXiTbUQ_eGgnIx2WLQ

Custom message for Enum

The following code shows how to show custom item list for enum . We have attribute for describing customized enum item using Describe

public enum  Food
    {
      [Describe("Yes, I want South indian meal")]
      SMeal = 1,
 
      [Describe("Yes, I want South North Indain meal")]
      NMeal = 2,
 
      [Describe("Yes , I want Fruits")]
      Fruts = 3 ,
      [Describe("Thanks , I dont want any Food")]
      No =4
    }

The output look like below

https://lh6.googleusercontent.com/H5CyPGS8T5gFTvjS6oFrqlQzhMH-OsYI4XTeYt95j91izTq2Hls_rikjTxPa62aE9iPfaAiONJZY4ANzkvwKXXE38hcciAeDui36_6NPmqVYdA2r7w1tTRvJ83cob99MxJdC8_cVx0ptoOCO4A

Template Attribute

The Template attribute enables you to replace the default templates that FormFlow uses to automatically generate prompts. The following code example uses the Template attribute to redefine how the form handles enumeration fields. The attribute indicates that the user may select only one item, sets the prompt text by using pattern language, and specifies that the form should display only one item per line

.

[Template(TemplateUsage.NotUnderstood, "Sorry , \"{0}\" Not avilable .", "Try again, I don't get \"{0}\".")]  
public Food LunchFood;

Pattern language uses curly braces ({}) to identify elements that will be replaced at runtime with actual values.  The output looks like below

https://lh6.googleusercontent.com/WFpjsfQbvIpG_Cd2x2B3-Q_ZIBi4_IWLPVKHAaiehkhD3oIwSQLa-gZbZl0OT0Ky0HwWE4QP3ebnXjO9DQvf0TP-t5gkzAdA9pQ4N_v_UdiQ1CGPKDBOHnXRGe-8uIIs7AXtJXbRb5YvIckUJA

Custom Template Error

The following code redefines the TemplateUsage.NotUnderstood template to specify two different variations of message. When the bot needs to communicate that it does not understand a user's input, it will determine message contents by randomly selecting one of the two text strings. 

[Template(TemplateUsage.NotUnderstood, "Sorry , \"{0}\" Not avilable .", "Try again, I don't get \"{0}\".")]  
public Food LunchFood;

The output look like below

https://lh4.googleusercontent.com/f68lhvvM5No0cZ4qGTXJ_leZH1F9fQdS-DLwe8e9F1QwSAKYEoxzOgEvdXU4_UxtbuMEhtkP1rgzwBf4xep4no2U9pC_R68wfQUeAofIFOgahoyuZudHByA_yxsNfgoh9tXbbKH5wfHG8s__NQ

Welcome, Confirmation and Form Builder

The following code example uses FormBuilder to define the steps of the form, validation, welcome message and dynamically define a field value and confirmation. By default, steps in the form will be executed in the sequence in which they are listed

public static  IForm<BusFormFlow> BuildForm()
    {
      return new  FormBuilder<BusFormFlow>()
          .Message("Welcome to the BotChat Bus Booking !")
          .Field(nameof(ToAddress))
          .Field(nameof(StartDate))
          .Field(nameof(BusTypes))
          .Field(nameof(NumberofSeat))
          .Field(nameof(LunchFood))
          .Message("Passenger Details")
          .AddRemainingFields()
          .Message("You will get confirmation email and SMS .Thanks for using Chat Bot Bus Booking")
          .OnCompletion(async (context, profileForm) =>
          {
            string message = "Your Bus booking Successfully Completed  , Welcome Again !!! :)";
            await context.PostAsync(message);
          })
          .Build();
    }

Run Bot Application

The emulator is a desktop application that lets we test and debug our bot on localhost. Now, you can click on "Run the application" in Visual studio and execute in the browser.

https://lh5.googleusercontent.com/Bsk4cyY28AMvdUQUW2UK3AXayWc_YXpFOtO8bPJa22vMOf_ML5KjPDBxdbpLzRCHu5h35wEmJUaD-eLzZE85iy1ulr3X9bv_YHwSdz4CVxfj5XgDztqz0aTcDjonx16xIiRqQTglSoofIsWx2Q

Test Application on Bot Emulator

You can follow the below steps for test your bot application.

  1. Open Bot Emulator. 
  2. Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979 
  3. You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages. 
  4. You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".

https://lh6.googleusercontent.com/SLGeuJ4OLr7jmQqzpXogR_W9HxujgbBUHLvslGb7fa3k8enI4Cjj7aQDWwpMkGv1DP89xsrUeHfX6D-2hjIjOMkJH0Vw4GtiJP4yF23rPn1_QF6v8IyCTkb-zLc1VZl_e7qMUfrEDFFOm0QjCw

Summary

In this wiki, you have learned about customize the form process, change prompt text, field order and how to add condition field.  If you have any questions/ feedback/ issues, please write in the comment box.