Create your own prompts to gather user input
SDK v4
SDK v3
A conversation between a bot and a user often involves asking (prompting) the user for information, parsing the user's response, and then acting on that information. Your bot should track the context of a conversation, so that it can manage its behavior and remember answers to previous questions. A bot's state is information it tracks to respond appropriately to incoming messages.
Tip
The dialogs library provides built in prompts that provide more functionality that users can use. Examples of those prompts can be found in the Implement sequential conversation flow article.
Prerequisites
- The code in this article is based on the Prompt Users for Input sample. You'll need a copy of either the C# Sample or JavaScript Sample.
- Knowledge of managing state and how to save user and conversation data.
About the sample code
The sample bot asks the user a series of questions, validates some of their answers, and saves their input. The following diagram shows the relationship between the bot, user profile, and conversation flow classes.
- A
UserProfile
class for the user information that the bot will collect. - A
ConversationFlow
class to control our conversation state while gathering user information. - An inner
ConversationFlow.Question
enumeration for tracking where we are in the conversation.
The user state will track the user's name, age, and chosen date, and conversation state will track what we've just asked the user. Since we don't plan to deploy this bot, we'll configure both user and conversation state to use memory storage.
We use the bot's message turn handler plus user and conversation state properties to manage the flow of the conversation and the collection of input. In our bot, we'll record the state property information received during each iteration of the message turn handler.
Create conversation and user objects
The user and conversation state objects are created at startup and dependency injected into the bot constructor.
Startup.cs
// Create the User state.
services.AddSingleton<UserState>();
// Create the Conversation state.
services.AddSingleton<ConversationState>();
// Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
services.AddTransient<IBot, CustomPromptBot>();
Bots/CustomPromptBot.cs
private readonly BotState _userState;
private readonly BotState _conversationState;
public CustomPromptBot(ConversationState conversationState, UserState userState)
{
_conversationState = conversationState;
_userState = userState;
}
Create property accessors
We begin by creating property accessors that give us a handle to the BotState
inside the OnMessageActivityAsync
method. Then, we call the GetAsync
method to get the properly scoped key:
Bots/CustomPromptBot.cs
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var conversationStateAccessors = _conversationState.CreateProperty<ConversationFlow>(nameof(ConversationFlow));
var flow = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationFlow());
var userStateAccessors = _userState.CreateProperty<UserProfile>(nameof(UserProfile));
var profile = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());
And finally, we save the data using the SaveChangesAsync
method.
// Save changes.
await _conversationState.SaveChangesAsync(turnContext);
await _userState.SaveChangesAsync(turnContext);
}
The bot's message turn handler
To handle message activities, we use the helper method FillOutUserProfileAsync() before saving the state using SaveChangesAsync(). Here is the complete code.
Bots/CustomPromptBot.cs
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var conversationStateAccessors = _conversationState.CreateProperty<ConversationFlow>(nameof(ConversationFlow));
var flow = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationFlow());
var userStateAccessors = _userState.CreateProperty<UserProfile>(nameof(UserProfile));
var profile = await userStateAccessors.GetAsync(turnContext, () => new UserProfile());
await FillOutUserProfileAsync(flow, profile, turnContext);
// Save changes.
await _conversationState.SaveChangesAsync(turnContext);
await _userState.SaveChangesAsync(turnContext);
}
Filling out the user profile
We'll start by collecting information. Each one will provide a similar interface.
- The return value indicates whether the input is a valid answer for this question.
- If validation passes, it produces a parsed and normalized value to save.
- If validation fails, it produces a message with which the bot can ask for the information again.
In the next section, we'll define the helper methods to parse and validate user input.
Bots/CustomPromptBot.cs
private static async Task FillOutUserProfileAsync(ConversationFlow flow, UserProfile profile, ITurnContext turnContext)
{
string input = turnContext.Activity.Text?.Trim();
string message;
switch (flow.LastQuestionAsked)
{
case ConversationFlow.Question.None:
await turnContext.SendActivityAsync("Let's get started. What is your name?");
flow.LastQuestionAsked = ConversationFlow.Question.Name;
break;
case ConversationFlow.Question.Name:
if (ValidateName(input, out string name, out message))
{
profile.Name = name;
await turnContext.SendActivityAsync($"Hi {profile.Name}.");
await turnContext.SendActivityAsync("How old are you?");
flow.LastQuestionAsked = ConversationFlow.Question.Age;
break;
}
else
{
await turnContext.SendActivityAsync(message ?? "I'm sorry, I didn't understand that.");
break;
}
case ConversationFlow.Question.Age:
if (ValidateAge(input, out int age, out message))
{
profile.Age = age;
await turnContext.SendActivityAsync($"I have your age as {profile.Age}.");
await turnContext.SendActivityAsync("When is your flight?");
flow.LastQuestionAsked = ConversationFlow.Question.Date;
break;
}
else
{
await turnContext.SendActivityAsync(message ?? "I'm sorry, I didn't understand that.");
break;
}
case ConversationFlow.Question.Date:
if (ValidateDate(input, out string date, out message))
{
profile.Date = date;
await turnContext.SendActivityAsync($"Your cab ride to the airport is scheduled for {profile.Date}.");
await turnContext.SendActivityAsync($"Thanks for completing the booking {profile.Name}.");
await turnContext.SendActivityAsync($"Type anything to run the bot again.");
flow.LastQuestionAsked = ConversationFlow.Question.None;
profile = new UserProfile();
break;
}
else
{
await turnContext.SendActivityAsync(message ?? "I'm sorry, I didn't understand that.");
break;
}
}
}
Parse and validate input
We'll use the following criteria to validate input.
- The name must be a non-empty string. We'll normalize by trimming white-space.
- The age must be between 18 and 120. We'll normalize by returning an integer.
- The date must be any date or time at least an hour in the future. We'll normalize by returning just the date portion of the parsed input.
Note
For the age and date input, we use the Microsoft/Recognizers-Text libraries to perform the initial parsing. While we provide sample code, we do not explain how the text recognizers libraries work, and this is just one way to parse the input. For more information about these libraries, see the repository's README.
Add the following validation methods to your bot.
Bots/CustomPromptBot.cs
private static bool ValidateName(string input, out string name, out string message)
{
name = null;
message = null;
if (string.IsNullOrWhiteSpace(input))
{
message = "Please enter a name that contains at least one character.";
}
else
{
name = input.Trim();
}
return message is null;
}
private static bool ValidateAge(string input, out int age, out string message)
{
age = 0;
message = null;
// Try to recognize the input as a number. This works for responses such as "twelve" as well as "12".
try
{
// Attempt to convert the Recognizer result to an integer. This works for "a dozen", "twelve", "12", and so on.
// The recognizer returns a list of potential recognition results, if any.
var results = NumberRecognizer.RecognizeNumber(input, Culture.English);
foreach (var result in results)
{
// The result resolution is a dictionary, where the "value" entry contains the processed string.
if (result.Resolution.TryGetValue("value", out object value))
{
age = Convert.ToInt32(value);
if (age >= 18 && age <= 120)
{
return true;
}
}
}
message = "Please enter an age between 18 and 120.";
}
catch
{
message = "I'm sorry, I could not interpret that as an age. Please enter an age between 18 and 120.";
}
return message is null;
}
private static bool ValidateDate(string input, out string date, out string message)
{
date = null;
message = null;
// Try to recognize the input as a date-time. This works for responses such as "11/14/2018", "9pm", "tomorrow", "Sunday at 5pm", and so on.
// The recognizer returns a list of potential recognition results, if any.
try
{
var results = DateTimeRecognizer.RecognizeDateTime(input, Culture.English);
// Check whether any of the recognized date-times are appropriate,
// and if so, return the first appropriate date-time. We're checking for a value at least an hour in the future.
var earliest = DateTime.Now.AddHours(1.0);
foreach (var result in results)
{
// The result resolution is a dictionary, where the "values" entry contains the processed input.
var resolutions = result.Resolution["values"] as List<Dictionary<string, string>>;
foreach (var resolution in resolutions)
{
// The processed input contains a "value" entry if it is a date-time value, or "start" and
// "end" entries if it is a date-time range.
if (resolution.TryGetValue("value", out string dateString)
|| resolution.TryGetValue("start", out dateString))
{
if (DateTime.TryParse(dateString, out DateTime candidate)
&& earliest < candidate)
{
date = candidate.ToShortDateString();
return true;
}
}
}
}
message = "I'm sorry, please enter a date at least an hour out.";
}
catch
{
message = "I'm sorry, I could not interpret that as an appropriate date. Please enter a date at least an hour out.";
}
return false;
}
Test the bot locally
Download and install the Bot Framework Emulator to test the bot locally.
- Run the sample locally on your machine. If you need instructions, refer to the README file for C# sample or JS sample sample.
- Test it using the emulator as shown below.
Additional resources
The Dialogs library provides classes that automate many aspects of managing conversations.
Next step
Feedback
Loading feedback...