我正在学习Microsoft Bot框架,所以我正在学习教程和一些示例对话框。我在试着写一个计算器机器人。(机器人请求一个整数、一个操作和另一个整数)。
但是,我不能让机器人真正要求用户输入。如果用户在启动对话框后键入任何内容,则响应为$invalid need: expected Call, have Poll
。我看到一些问题,说你不能在同一个函数调用中使用prompt和context.Wait
,但我还没有发现任何如何处理这一问题的东西。
public class CalculatorDialog : IDialog<object>
{
protected readonly String[] operators = { "+", "-", "*", "/" };
private long Left { get; set; }
private long Right {get; set; }
private String Operator { get; set; }
public async Task StartAsync(IDialogContext context)
{
context.Wait(Calculate);
}
private async Task Calculate(IDialogContext context,
IAwaitable<IMessageActivity> result)
{
await result;
PromptDialog.Number(
context,
async (ctx, lhs) => { Left = await lhs; },
"Left hand side"
);
PromptDialog.Choice<string>(
context,
async (ctx, op) => { Operator = await op; },
new PromptOptions<string>("Operator:", options: operators)
);
PromptDialog.Number(
context,
async (ctx, rhs) => { Right = await rhs; },
"Right hand side"
);
long res;
switch (Operator) { /* res = Left Operator Right */}
await context.PostAsync($"The result is: ${res}");
}
}
调用它的代码是
switch (activity.Text)
{
case "math":
context.Call(new CalculatorDialog(), this.ResumeAfterSubDialog);
break;
}
其中ResumeAferSubDialog
继续主循环。
发布于 2018-05-31 11:16:34
在您的代码中,我发现您不断地调用PromptDialog.Number
和PromptDialog.Choice
方法,您可以修改您的代码来执行/调用上一个Resume处理程序中的next PromptDialog,下面的代码片段供您参考。
private async Task Calculate(IDialogContext context, IAwaitable<IMessageActivity> result)
{
await result;
PromptDialog.Number(
context,
LeftReceivedAsync,
"Left hand side"
);
}
private async Task LeftReceivedAsync(IDialogContext context, IAwaitable<long> lhs)
{
Left = await lhs;
PromptDialog.Choice<string>(
context,
OperatorReceivedAsync,
new PromptOptions<string>("Operator:", options: operators)
);
}
private async Task OperatorReceivedAsync(IDialogContext context, IAwaitable<string> op)
{
Operator = await op;
PromptDialog.Number(
context,
RightReceivedAsync,
"Right hand side"
);
}
private async Task RightReceivedAsync(IDialogContext context, IAwaitable<long> rhs)
{
Right = await rhs;
long res;
//switch (Operator) { /* res = Left Operator Right */}
await context.PostAsync($"The result is: ${res}");
}
备注:
根据我的测试,PromptDialog.Choice
不能很好地处理这些特殊字符("+", "-", "*", "/"
),它不会将选定的选项识别为可用选项,但让用户重试。
测试pic1:
如果可能,您可以提供不同的选项列表,例如:
protected readonly String[] operators = { "add (+)", "subtract (-)", "multiply (*)", "divide (/)" };
测试pic2:
https://stackoverflow.com/questions/50611740
复制相似问题