首页 > 解决方案 > 将变量传递给 Microsoft BotBuilder C# .NET Core 中的对话框

问题描述

我正在尝试使用此示例构建我的机器人。

现在的流程:

  1. 用户写了一些东西foo
  2. 机器人进入对话框...

我一直坚持在对话框中获取用户的第一foo消息

标签: c#.net-corebotframework

解决方案


您可以通过以下方式获取用户输入turnContext

string userInput = turnContext.Context.Activity.Text

例子:

 public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
 {
     string userInput = turnContext.Activity.Text;
 }

至于将变量传递给UserProfileDialog,您可以通过以下方式进行:

await innerDc.BeginDialogAsync(nameof(DialogFlowDialog), userInput );

BeginDialogAsync接受一个可选参数( Object ) 以传递给正在启动的对话框。

在您的UserProfileDialog中,您可以从stepContext获取该参数

例子:

 private static async Task<DialogTurnResult> TransportStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            string userInput = string.Empty;

            // Options contains the information the waterfall dialog was called with
            if (stepContext.Options != null)
            {
                userInput = stepContext.Options.ToString();
            }
        }

如果您想获取用户发送的第一条消息,您始终可以从上下文中获取它,如果您使用05.multi-turn-prompt您可以在UserProfileDialog中以这种方式获取它

   private static async Task<DialogTurnResult> TransportStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // this contains the text message the user sent
            string userInput = stepContext.Context.Activity.Text;
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            // Running a prompt here means the next WaterfallStep will be run when the users response is received.
            return await stepContext.PromptAsync(nameof(ChoicePrompt),
                new PromptOptions
                {
                    Prompt = MessageFactory.Text("Please enter your mode of transport."),
                    Choices = ChoiceFactory.ToChoices(new List<string> { "Car", "Bus", "Bicycle" }),
                }, cancellationToken);
        }

或者像这样在你的DialogBot

  public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {

            // this contains the text message the user sent
            string userInput = turnContext.Activity.Text;

            await base.OnTurnAsync(turnContext, cancellationToken);

            // Save any state changes that might have occured during the turn.
            await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
            await UserState.SaveChangesAsync(turnContext, false, cancellationToken);
        }

推荐阅读