如果您想在文本或附件提示中使用 Facebook Messenger 的位置快速回复来捕获用户的位置,您需要提供自定义验证器 - 我建议使用文本提示。
构造函数
创建您的瀑布并将您的提示添加到您的构造函数中的对话框堆栈中。确保在文本提示中添加自定义验证器;否则,机器人将反复提示用户他们的位置,因为它需要快速回复未提供的文本值。
public MultiTurnPromptsBot(MultiTurnPromptsBotAccessors accessors)
{
...
// This array defines how the Waterfall will execute.
var waterfallSteps = new WaterfallStep[]
{
PromptForLocation,
CaptureLocation,
};
...
// Add named dialogs to the DialogSet. These names are saved in the dialog state.
_dialogs.Add(new WaterfallDialog("details", waterfallSteps));
_dialogs.Add(new TextPrompt("location", LocationPromptValidatorAsync));
}
位置验证器
在自定义验证器中,您可以检查传入活动的位置对象,该对象位于活动的实体属性中。如果activity没有位置,可以返回false,提示会再次询问用户位置;否则,将继续进行下一步。
public Task<bool> LocationPromptValidatorAsync(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
{
var activity = promptContext.Context.Activity;
var location = activity.Entities?.FirstOrDefault(e => e.Type == "Place");
if (location != null) {
return Task.FromResult(true);
}
return Task.FromResult(false);
}
位置提示
正如您在上面的代码 sn-p 中所做的那样,您可以将 Facebook Messenger 快速回复添加到回复的频道数据中。
private static async Task<DialogTurnResult> PromptForLocation(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
Activity reply = stepContext.Context.Activity.CreateReply();
reply.Text = "What is your location?";
reply.ChannelData = JObject.FromObject( new {
quick_replies = new object[]
{
new
{
content_type = "location",
},
},
});
return await stepContext.PromptAsync("location", new PromptOptions { Prompt = reply }, cancellationToken);
}
捕捉位置
您可以在此处捕获用户位置,以随心所欲地使用。
private async Task<DialogTurnResult> CaptureLocation(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var activity = stepContext.Context.Activity;
var location = activity.Entities?.FirstOrDefault(e => e.Type == "Place");
if (location != null) {
var latitude = location.Properties["geo"]?["latitude"].ToString();
var longitude = location.Properties["geo"]?["longitude"].ToString();
await stepContext.Context.SendActivityAsync($"Latitude: {latitude} Longitude: {longitude}");
}
// WaterfallStep always finishes with the end of the Waterfall or with another dialog, here it is the end.
return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}
希望这会有所帮助!