在MS Bot框架中创建多个对话框,以便bot记住正在进行哪个对话的方法如下:
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Choices;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Dialog1 : ComponentDialog
{
public Dialog1(string dialogId) : base(dialogId)
{
AddDialog(new TextPrompt(nameof(TextPrompt)));
AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
{
PromptStepAsync,
ProcessStepAsync,
FinalStepAsync
}));
InitialDialogId = nameof(WaterfallDialog);
}
private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter some text.") }, cancellationToken);
}
private async Task<DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
stepContext.Values["text"] = (string)stepContext.Result;
var choices = new List<Choice> { new Choice("Option 1"), new Choice("Option 2"), new Choice("Option 3") };
return await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions { Prompt = MessageFactory.Text("Please select an option."), Choices = choices }, cancellationToken);
}
private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
stepContext.Values["choice"] = ((FoundChoice)stepContext.Result).Value;
await stepContext.Context.SendActivityAsync($"You entered: {stepContext.Values["text"]}");
await stepContext.Context.SendActivityAsync($"You selected: {stepContext.Values["choice"]}");
return await stepContext.EndDialogAsync();
}
}
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Bot : ActivityHandler
{
private readonly DialogSet _dialogs;
public Bot()
{
_dialogs = new DialogSet();
_dialogs.Add(new Dialog1(nameof(Dialog1)));
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var dialogContext = await _dialogs.CreateContextAsync(turnContext, cancellationToken);
var results = await dialogContext.ContinueDialogAsync(cancellationToken);
if (results.Status == DialogTurnStatus.Empty)
{
await dialogContext.BeginDialogAsync(nameof(Dialog1), cancellationToken: cancellationToken);
}
}
}
以上代码示例中,创建了一个名为"Dialog1"的对话类,该对话类包含了一个简单的对话流程,包括提示用户输入文本、选择选项,并显示用户输入的文本和选择的选项。
在bot的主对话流程中,通过创建对话集合(DialogSet)并添加对话类的实例,然后在收到消息时,使用对话集合创建对话上下文(DialogContext),并根据对话状态决定是否开始新的对话。
这样,当用户与bot进行对话时,bot将根据用户的输入和选择,进入不同的对话流程,并记住当前进行的是哪个对话。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云