-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathGreetingDialog.cs
223 lines (201 loc) · 9.62 KB
/
GreetingDialog.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
namespace Microsoft.BotBuilderSamples
{
/// <summary>
/// Demonstrates the following concepts:
/// - Use a subclass of ComponentDialog to implement a multi-turn conversation
/// - Use a Waterflow dialog to model multi-turn conversation flow
/// - Use custom prompts to validate user input
/// - Store conversation and user state.
/// </summary>
public class GreetingDialog : ComponentDialog
{
// User state for greeting dialog
private const string GreetingStateProperty = "greetingState";
private const string NameValue = "greetingName";
private const string CityValue = "greetingCity";
// Prompts names
private const string NamePrompt = "namePrompt";
private const string CityPrompt = "cityPrompt";
// Minimum length requirements for city and name
private const int NameLengthMinValue = 3;
private const int CityLengthMinValue = 5;
// Dialog IDs
private const string ProfileDialog = "profileDialog";
/// <summary>
/// Initializes a new instance of the <see cref="GreetingDialog"/> class.
/// </summary>
/// <param name="botServices">Connected services used in processing.</param>
/// <param name="botState">The <see cref="UserState"/> for storing properties at user-scope.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> that enables logging and tracing.</param>
public GreetingDialog(IStatePropertyAccessor<GreetingState> userProfileStateAccessor, ILoggerFactory loggerFactory)
: base(nameof(GreetingDialog))
{
UserProfileAccessor = userProfileStateAccessor ?? throw new ArgumentNullException(nameof(userProfileStateAccessor));
// Add control flow dialogs
var waterfallSteps = new WaterfallStep[]
{
InitializeStateStepAsync,
PromptForNameStepAsync,
PromptForCityStepAsync,
DisplayGreetingStateStepAsync,
};
AddDialog(new WaterfallDialog(ProfileDialog, waterfallSteps));
AddDialog(new TextPrompt(NamePrompt, ValidateName));
AddDialog(new TextPrompt(CityPrompt, ValidateCity));
}
public IStatePropertyAccessor<GreetingState> UserProfileAccessor { get; }
private async Task<DialogTurnResult> InitializeStateStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var greetingState = await UserProfileAccessor.GetAsync(stepContext.Context, () => null);
if (greetingState == null)
{
var greetingStateOpt = stepContext.Options as GreetingState;
if (greetingStateOpt != null)
{
await UserProfileAccessor.SetAsync(stepContext.Context, greetingStateOpt);
}
else
{
await UserProfileAccessor.SetAsync(stepContext.Context, new GreetingState());
}
}
return await stepContext.NextAsync();
}
private async Task<DialogTurnResult> PromptForNameStepAsync(
WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
var greetingState = await UserProfileAccessor.GetAsync(stepContext.Context);
// if we have everything we need, greet user and return.
if (greetingState != null && !string.IsNullOrWhiteSpace(greetingState.Name) && !string.IsNullOrWhiteSpace(greetingState.City))
{
return await GreetUser(stepContext);
}
if (string.IsNullOrWhiteSpace(greetingState.Name))
{
// prompt for name, if missing
var opts = new PromptOptions
{
Prompt = new Activity
{
Type = ActivityTypes.Message,
Text = "What is your name?",
},
};
return await stepContext.PromptAsync(NamePrompt, opts);
}
else
{
return await stepContext.NextAsync();
}
}
private async Task<DialogTurnResult> PromptForCityStepAsync(
WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
// Save name, if prompted.
var greetingState = await UserProfileAccessor.GetAsync(stepContext.Context);
var lowerCaseName = stepContext.Result as string;
if (string.IsNullOrWhiteSpace(greetingState.Name) && lowerCaseName != null)
{
// Capitalize and set name.
greetingState.Name = char.ToUpper(lowerCaseName[0]) + lowerCaseName.Substring(1);
await UserProfileAccessor.SetAsync(stepContext.Context, greetingState);
}
if (string.IsNullOrWhiteSpace(greetingState.City))
{
var opts = new PromptOptions
{
Prompt = new Activity
{
Type = ActivityTypes.Message,
Text = $"Hello {greetingState.Name}, what city do you live in?",
},
};
return await stepContext.PromptAsync(CityPrompt, opts);
}
else
{
return await stepContext.NextAsync();
}
}
private async Task<DialogTurnResult> DisplayGreetingStateStepAsync(
WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
// Save city, if prompted.
var greetingState = await UserProfileAccessor.GetAsync(stepContext.Context);
var lowerCaseCity = stepContext.Result as string;
if (string.IsNullOrWhiteSpace(greetingState.City) &&
!string.IsNullOrWhiteSpace(lowerCaseCity))
{
// capitalize and set city
greetingState.City = char.ToUpper(lowerCaseCity[0]) + lowerCaseCity.Substring(1);
await UserProfileAccessor.SetAsync(stepContext.Context, greetingState);
}
return await GreetUser(stepContext);
}
/// <summary>
/// Validator function to verify if the user name meets required constraints.
/// </summary>
/// <param name="promptContext">Context for this prompt.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
private async Task<bool> ValidateName(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
{
// Validate that the user entered a minimum length for their name.
var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;
if (value.Length >= NameLengthMinValue)
{
promptContext.Recognized.Value = value;
return true;
}
else
{
await promptContext.Context.SendActivityAsync($"Names needs to be at least `{NameLengthMinValue}` characters long.");
return false;
}
}
/// <summary>
/// Validator function to verify if city meets required constraints.
/// </summary>
/// <param name="promptContext">Context for this prompt.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
private async Task<bool> ValidateCity(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
{
// Validate that the user entered a minimum lenght for their name
var value = promptContext.Recognized.Value?.Trim() ?? string.Empty;
if (value.Length >= CityLengthMinValue)
{
promptContext.Recognized.Value = value;
return true;
}
else
{
await promptContext.Context.SendActivityAsync($"City names needs to be at least `{CityLengthMinValue}` characters long.");
return false;
}
}
// Helper function to greet user with information in GreetingState.
private async Task<DialogTurnResult> GreetUser(WaterfallStepContext stepContext)
{
var context = stepContext.Context;
var greetingState = await UserProfileAccessor.GetAsync(context);
// Display their profile information and end dialog.
await context.SendActivityAsync($"Hi {greetingState.Name}, from {greetingState.City}, nice to meet you!");
return await stepContext.EndDialogAsync();
}
}
}