使用元件對話,您可以建立獨立的對話框來處理特定案例,將大型對話集分成更容易管理的部分。 每一個片段都有自己的對話集,並避免與對話框集以外的任何名稱衝突。 元件對話框可重複使用,因為它們可以是:
若要使用對話框,請安裝 Microsoft.Bot.Builder.Dialogs NuGet 套件。
Dialogs\UserProfileDialog.cs
在這裡,類別 UserProfileDialog
衍生自 ComponentDialog
類別。
public class UserProfileDialog : ComponentDialog
在建構函式中, AddDialog
方法會將對話框和提示新增至元件對話方塊。 您使用這個方法新增的第一個項目會設定為初始對話框。 您可以藉由明確設定 InitialDialogId
屬性來變更初始對話框。 當您啟動元件對話框時,它會啟動其 初始對話方塊。
public UserProfileDialog(UserState userState)
: base(nameof(UserProfileDialog))
{
_userProfileAccessor = userState.CreateProperty<UserProfile>("UserProfile");
// This array defines how the Waterfall will execute.
var waterfallSteps = new WaterfallStep[]
{
TransportStepAsync,
NameStepAsync,
NameConfirmStepAsync,
AgeStepAsync,
PictureStepAsync,
SummaryStepAsync,
ConfirmStepAsync,
};
// Add named dialogs to the DialogSet. These names are saved in the dialog state.
AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
AddDialog(new TextPrompt(nameof(TextPrompt)));
AddDialog(new NumberPrompt<int>(nameof(NumberPrompt<int>), AgePromptValidatorAsync));
AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
AddDialog(new AttachmentPrompt(nameof(AttachmentPrompt), PicturePromptValidatorAsync));
// The initial child Dialog to run.
InitialDialogId = nameof(WaterfallDialog);
}
下列程式代碼代表瀑布式對話的第一個步驟。
private static async Task<DialogTurnResult> NameStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
stepContext.Values["transport"] = ((FoundChoice)stepContext.Result).Value;
return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter your name.") }, cancellationToken);
}
如需實作瀑布式對話的詳細資訊,請參閱如何 實作循序對話流程。
若要使用對話框,您的專案必須安裝 botbuilder-dialogs npm 套件。
dialogs/userProfileDialog.js
在這裡,類別 UserProfileDialog
會 ComponentDialog
擴充 。
class UserProfileDialog extends ComponentDialog {
在建構函式中, AddDialog
方法會將對話框和提示新增至元件對話方塊。 您使用這個方法新增的第一個項目會設定為初始對話框。 您可以藉由明確設定 InitialDialogId
屬性來變更初始對話框。 當您啟動元件對話框時,它會啟動其 初始對話方塊。
constructor(userState) {
super('userProfileDialog');
this.userProfile = userState.createProperty(USER_PROFILE);
this.addDialog(new TextPrompt(NAME_PROMPT));
this.addDialog(new ChoicePrompt(CHOICE_PROMPT));
this.addDialog(new ConfirmPrompt(CONFIRM_PROMPT));
this.addDialog(new NumberPrompt(NUMBER_PROMPT, this.agePromptValidator));
this.addDialog(new AttachmentPrompt(ATTACHMENT_PROMPT, this.picturePromptValidator));
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.transportStep.bind(this),
this.nameStep.bind(this),
this.nameConfirmStep.bind(this),
this.ageStep.bind(this),
this.pictureStep.bind(this),
this.summaryStep.bind(this),
this.confirmStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
}
下列程式代碼代表瀑布式對話的第一個步驟。
async transportStep(step) {
// 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 user's response is received.
return await step.prompt(CHOICE_PROMPT, {
prompt: 'Please enter your mode of transport.',
choices: ChoiceFactory.toChoices(['Car', 'Bus', 'Bicycle'])
});
}
如需實作瀑布式對話的詳細資訊,請參閱如何 實作循序對話流程。
UserProfileDialog.java
在這裡,類別 UserProfileDialog
衍生自 ComponentDialog
類別。
public class UserProfileDialog extends ComponentDialog {
在建構函式中, addDialog
方法會將對話框和提示新增至元件對話方塊。 您使用這個方法新增的第一個項目會設定為初始對話框。 您可以呼叫 setInitialDialogId
方法來變更初始對話,並提供初始對話的名稱。 當您啟動元件對話框時,它會啟動其 初始對話方塊。
public UserProfileDialog(UserState withUserState) {
super("UserProfileDialog");
userProfileAccessor = withUserState.createProperty("UserProfile");
WaterfallStep[] waterfallSteps = {
UserProfileDialog::transportStep,
UserProfileDialog::nameStep,
this::nameConfirmStep,
this::ageStep,
UserProfileDialog::pictureStep,
this::confirmStep,
this::summaryStep
};
// Add named dialogs to the DialogSet. These names are saved in the dialog state.
addDialog(new WaterfallDialog("WaterfallDialog", Arrays.asList(waterfallSteps)));
addDialog(new TextPrompt("TextPrompt"));
addDialog(new NumberPrompt<Integer>("NumberPrompt", UserProfileDialog::agePromptValidator, Integer.class));
addDialog(new ChoicePrompt("ChoicePrompt"));
addDialog(new ConfirmPrompt("ConfirmPrompt"));
addDialog(new AttachmentPrompt("AttachmentPrompt", UserProfileDialog::picturePromptValidator));
// The initial child Dialog to run.
setInitialDialogId("WaterfallDialog");
}
下列程式代碼代表瀑布式對話的第一個步驟。
private static CompletableFuture<DialogTurnResult> nameStep(WaterfallStepContext stepContext) {
stepContext.getValues().put("transport", ((FoundChoice) stepContext.getResult()).getValue());
PromptOptions promptOptions = new PromptOptions();
promptOptions.setPrompt(MessageFactory.text("Please enter your name."));
return stepContext.prompt("TextPrompt", promptOptions);
}
如需實作瀑布式對話的詳細資訊,請參閱如何 實作循序對話流程。
若要使用對話,請執行和從終端機安裝 pip install botbuilder-ai
pip install botbuilder-dialogs
botbuilder-dialogs 和 botbuilder-ai PyPI 套件。
dialogs/user_profile_dialog.py
在這裡,類別 UserProfileDialog
會 ComponentDialog
擴充 。
class UserProfileDialog(ComponentDialog):
在建構函式中, add_dialog
方法會將對話框和提示新增至元件對話方塊。 您使用這個方法新增的第一個項目會設定為初始對話框。 您可以藉由明確設定 initial_dialog_id
屬性來變更初始對話框。 當您啟動元件對話框時,它會啟動其 初始對話方塊。
class UserProfileDialog(ComponentDialog):
def __init__(self, user_state: UserState):
super(UserProfileDialog, self).__init__(UserProfileDialog.__name__)
self.user_profile_accessor = user_state.create_property("UserProfile")
self.add_dialog(
WaterfallDialog(
WaterfallDialog.__name__,
[
self.transport_step,
self.name_step,
self.name_confirm_step,
self.age_step,
self.picture_step,
self.summary_step,
self.confirm_step,
],
)
)
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(
NumberPrompt(NumberPrompt.__name__, UserProfileDialog.age_prompt_validator)
)
self.add_dialog(ChoicePrompt(ChoicePrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(
AttachmentPrompt(
AttachmentPrompt.__name__, UserProfileDialog.picture_prompt_validator
)
)
self.initial_dialog_id = WaterfallDialog.__name__
下列程式代碼代表瀑布式對話的第一個步驟。
async def transport_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
# 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 step_context.prompt(
ChoicePrompt.__name__,
PromptOptions(
prompt=MessageFactory.text("Please enter your mode of transport."),
choices=[Choice("Car"), Choice("Bus"), Choice("Bicycle")],
),
)
如需實作瀑布式對話的詳細資訊,請參閱如何 實作循序對話流程。
Bots\DialogBot.cs
在範例中,這會使用 RunAsync
從 Bot OnMessageActivityAsync
方法呼叫的方法來完成。
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
Logger.LogInformation("Running dialog with Message Activity.");
// Run the Dialog with the new message Activity.
await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}
dialogs/userProfileDialog.js
在範例中,我們已將方法新增 run
至使用者配置檔對話方塊。
async run(turnContext, accessor) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(turnContext);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dialogContext.beginDialog(this.id);
}
}
bots/dialogBot.js
從 run
Bot 的 onMessage
方法呼叫 方法。
this.onMessage(async (context, next) => {
console.log('Running dialog with Message Activity.');
// Run the Dialog with the new message Activity.
await this.dialog.run(context, this.dialogState);
await next();
});
DialogBot.java
在範例中,這會使用 run
從 Bot onMessageActivity
方法呼叫的方法來完成。
@Override
protected CompletableFuture<Void> onMessageActivity(
TurnContext turnContext
) {
LoggerFactory.getLogger(DialogBot.class).info("Running dialog with Message Activity.");
// Run the Dialog with the new message Activity.
return Dialog.run(dialog, turnContext, conversationState.createProperty("DialogState"));
}
helpers/dialog_helper.py
在範例中,我們已將方法新增 run_dialog
至使用者配置檔對話方塊。
class DialogHelper:
@staticmethod
async def run_dialog(
dialog: Dialog, turn_context: TurnContext, accessor: StatePropertyAccessor
):
dialog_set = DialogSet(accessor)
dialog_set.add(dialog)
dialog_context = await dialog_set.create_context(turn_context)
results = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
await dialog_context.begin_dialog(dialog.id)
run_dialog
從 Bot on_message_activity
方法呼叫的方法。
bots/dialog_bot.py
async def on_message_activity(self, turn_context: TurnContext):
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)