-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathAdaptiveCardPrompt.cs
256 lines (224 loc) · 11.8 KB
/
AdaptiveCardPrompt.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
using Newtonsoft.Json.Linq;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
namespace Bot.Builder.Community.Dialogs.Prompts
{
public enum AdaptiveCardPromptErrors
{
/// <summary>
/// No known user errors.
/// </summary>
None,
/// <summary>
/// Error presented if developer specifies AdaptiveCardPromptSettings.promptId,
/// but user submits adaptive card input on a card where the ID does not match.
/// This error will also be present if developer AdaptiveCardPromptSettings.promptId,
/// but forgets to add the promptId to every <submit>.data.promptId in your Adaptive Card.
/// </summary>
UserInputDoesNotMatchCardId,
/// <summary>
/// Error presented if developer specifies AdaptiveCardPromptSettings.requiredIds,
/// but user does not submit input for all required input id's on the adaptive card.
/// </summary>
MissingRequiredIds,
/// <summary>
/// Error presented if user enters plain text instead of using Adaptive Card's input fields.
/// </summary>
UserUsedTextInput,
}
/// <summary>
/// Waits for Adaptive Card Input to be received.
/// </summary>
/// <remarks>
/// This prompt is similar to ActivityPrompt but provides features specific to Adaptive Cards:
/// * Optionally allow specified input fields to be required
/// * Optionally ensures input is only valid if it comes from the appropriate card (not one shown previous to prompt)
/// * Provides ability to handle variety of common user errors related to Adaptive Cards
/// DO NOT USE WITH CHANNELS THAT DON'T SUPPORT ADAPTIVE CARDS.
/// </remarks>
public class AdaptiveCardPrompt : Dialog
{
private const string PersistedOptions = "options";
private const string PersistedState = "state";
public const string AttemptCountKey = "AttemptCount";
// Has to be dynamic because PromptValidator is internal to the SDK
private readonly AdaptiveCardPromptValidator<AdaptiveCardPromptResult> _validator;
private readonly string[] _requiredInputIds;
private readonly string _promptId;
private readonly Attachment _card;
/// <summary>
/// Initializes a new instance of the <see cref="AdaptiveCardPrompt"/> class.
/// </summary>
/// <param name="dialogId">Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`.</param>
/// <param name="validator">(optional) Validator that will be called each time a new activity is received.</param>
/// <param name="settings">(optional) Additional settings for AdaptiveCardPrompt behavior.</param>
public AdaptiveCardPrompt(string dialogId, AdaptiveCardPromptSettings settings, AdaptiveCardPromptValidator<AdaptiveCardPromptResult> validator = null)
: base(dialogId)
{
if (settings == null || settings.Card == null)
{
throw new ArgumentNullException("AdaptiveCardPrompt requires a card in `AdaptiveCardPromptSettings.card`");
}
_validator = validator;
_requiredInputIds = settings.RequiredInputIds ?? null;
ThrowIfNotAdaptiveCard(settings.Card);
_card = settings.Card;
_promptId = settings.PromptId;
}
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options, CancellationToken cancellationToken = default(CancellationToken))
{
// Initialize prompt state
var state = dc.ActiveDialog.State;
state[PersistedOptions] = options;
state[PersistedState] = new Dictionary<string, object>
{
{ AttemptCountKey, 0 },
};
// Send initial prompt
await OnPromptAsync(dc.Context, (IDictionary<string, object>)state[PersistedState], (PromptOptions)state[PersistedOptions], false, cancellationToken).ConfigureAwait(false);
return Dialog.EndOfTurn;
}
// Override ContinueDialogAsync so that we can catch Activity.Value (which is ignored, by default)
public override async Task<DialogTurnResult> ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken)
{
// Perform base recognition
var instance = dc.ActiveDialog;
var state = (IDictionary<string, object>)instance.State[PersistedState];
var options = (PromptOptions)instance.State[PersistedOptions];
var recognized = await OnRecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);
// Increment attempt count
// Convert.ToInt32 For issue https://github.com/Microsoft/botbuilder-dotnet/issues/1859
state[AttemptCountKey] = Convert.ToInt32(state[AttemptCountKey]) + 1;
var isValid = false;
if (_validator != null)
{
var promptContext = new AdaptiveCardPromptValidatorContext<AdaptiveCardPromptResult>(dc.Context, recognized, state, options);
isValid = await _validator(promptContext, cancellationToken).ConfigureAwait(false);
}
else if (recognized.Succeeded)
{
isValid = true;
}
// Return recognized value or re-prompt
if (isValid)
{
return await dc.EndDialogAsync(recognized.Value).ConfigureAwait(false);
}
else
{
// Re-prompt
if (!dc.Context.Responded)
{
await OnPromptAsync(dc.Context, state, options, true, cancellationToken).ConfigureAwait(false);
}
return Dialog.EndOfTurn;
}
}
protected virtual async Task OnPromptAsync(ITurnContext context, IDictionary<string, object> state, PromptOptions options, bool isRetry, CancellationToken cancellationToken)
{
// Since card is passed in via AdaptiveCardPromptSettings, PromptOptions may not be used.
// Ensure we're working with RetryPrompt, as applicable
var prompt = isRetry && options.RetryPrompt != null ? options.RetryPrompt : options.Prompt;
// Clone the correct prompt (or new Activity, if null) so that we don't affect the one saved in state
var clonedPrompt = JObject.FromObject(prompt ?? new Activity()).ToObject<Activity>();
// The actual AdaptiveCard should be tightly-coupled to its AdaptiveCardPromptSettings, which means it would be instantiated in
// a Dialog's constructor and passed in when using AddDialog(AdaptiveCardPrompt) as opposed to passing into Activity.Attachments.
// The actual prompt is typically called by using stepContext.PromptAsync() in a WaterfallDialog step, where PromptOptions is
// required by DialogContext. However, PromptOptions isn't really required (or useful) for AdaptiveCardPrompt.
// This next code block allows a user to simply call by setting Activity.Type to ActivityTypes.Message
// "PromptAsync(nameof(AdaptiveCardPrompt), new PromptOptions())", instead of the uglier
// "PromptAsync(nameof(AdaptiveCardPrompt), new PromptOptions(){ Prompt = MessageFactory.Text(string.Empty) })"
// Note: PromptOptions does not need to be set in Node, since it compiles to JavaScript
// and the card gets sent without setting Activity.Type
if (clonedPrompt.Type == null)
{
clonedPrompt.Type = ActivityTypes.Message;
}
// Add Adaptive Card as last attachment (user input should go last), keeping any others
if (clonedPrompt.Attachments == null)
{
clonedPrompt.Attachments = new List<Attachment>();
}
clonedPrompt.Attachments.Add(_card);
await context.SendActivityAsync(clonedPrompt, cancellationToken).ConfigureAwait(false);
}
protected virtual Task<PromptRecognizerResult<AdaptiveCardPromptResult>> OnRecognizeAsync(ITurnContext context, CancellationToken cancellationToken)
{
// Ignore user input that doesn't come from adaptive card
if (string.IsNullOrWhiteSpace(context.Activity.Text) && context.Activity.Value != null)
{
var data = JObject.FromObject(context.Activity.Value);
// Validate it comes from the correct card - This is only a worry while the prompt/dialog has not ended
if (!string.IsNullOrEmpty(_promptId) && data["promptId"]?.ToString() != _promptId)
{
return Task.FromResult(new PromptRecognizerResult<AdaptiveCardPromptResult>()
{
Succeeded = false,
Value = new AdaptiveCardPromptResult()
{
Data = data,
Error = AdaptiveCardPromptErrors.UserInputDoesNotMatchCardId,
},
});
}
// Check for required input data, if specified in AdaptiveCardPromptSettings
var missingIds = new List<string>();
foreach (var id in _requiredInputIds ?? Enumerable.Empty<string>())
{
if (data[id] == null || string.IsNullOrWhiteSpace(data[id].ToString()))
{
missingIds.Add(id);
}
}
// User did not submit inputs that were required
if (missingIds.Count > 0)
{
return Task.FromResult(new PromptRecognizerResult<AdaptiveCardPromptResult>()
{
Succeeded = false,
Value = new AdaptiveCardPromptResult()
{
Data = data,
Error = AdaptiveCardPromptErrors.MissingRequiredIds,
MissingIds = missingIds,
},
});
}
return Task.FromResult(new PromptRecognizerResult<AdaptiveCardPromptResult>()
{
Succeeded = true,
Value = new AdaptiveCardPromptResult() { Data = data },
});
}
else
{
// User used text input instead of card input
return Task.FromResult(new PromptRecognizerResult<AdaptiveCardPromptResult>()
{
Succeeded = false,
Value = new AdaptiveCardPromptResult() { Error = AdaptiveCardPromptErrors.UserUsedTextInput },
});
}
}
private void ThrowIfNotAdaptiveCard(Attachment cardAttachment)
{
var adaptiveCardType = "application/vnd.microsoft.card.adaptive";
if (cardAttachment == null || cardAttachment.Content == null)
{
throw new NullReferenceException($"No Adaptive Card provided. Include in the constructor or PromptOptions.Prompt.Attachments");
}
else if (string.IsNullOrEmpty(cardAttachment.ContentType) || cardAttachment.ContentType != adaptiveCardType)
{
throw new ArgumentException($"Attachment is not a valid Adaptive Card.\n" +
$"Ensure Card.ContentType is '${adaptiveCardType}'\n" +
"and Card.Content contains the card json");
}
}
}
}