Skip to content
This repository has been archived by the owner on Dec 4, 2023. It is now read-only.

Sample 43.complex-dialog #959

Merged
merged 2 commits into from
Feb 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
*/
public class DialogState {
@JsonProperty(value = "dialogStack")
private List<DialogInstance> dialogStack = new ArrayList<DialogInstance>();
private List<DialogInstance> dialogStack;

/**
* Initializes a new instance of the class with an empty stack.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
*/
public class WaterfallDialog extends Dialog {

private final String persistedOptions = "options";
private final String stepIndex = "stepIndex";
private final String persistedValues = "values";
private final String persistedInstanceId = "instanceId";
private static final String PERSISTED_OPTIONS = "options";
private static final String PERSISTED_VALUES = "values";
private static final String PERSISTED_INSTANCEID = "instanceId";
private static final String STEP_INDEX = "stepIndex";

private final List<WaterfallStep> steps;

/**
* Initializes a new instance of the {@link waterfallDialog} class.
* Initializes a new instance of the {@link WaterfallDialog} class.
*
* @param dialogId The dialog ID.
* @param actions Optional actions to be defined by the caller.
Expand Down Expand Up @@ -90,9 +90,9 @@ public CompletableFuture<DialogTurnResult> beginDialog(DialogContext dc, Object
// Initialize waterfall state
Map<String, Object> state = dc.getActiveDialog().getState();
String instanceId = UUID.randomUUID().toString();
state.put(persistedOptions, options);
state.put(persistedValues, new HashMap<String, Object>());
state.put(persistedInstanceId, instanceId);
state.put(PERSISTED_OPTIONS, options);
state.put(PERSISTED_VALUES, new HashMap<String, Object>());
state.put(PERSISTED_INSTANCEID, instanceId);

Map<String, String> properties = new HashMap<String, String>();
properties.put("DialogId", getId());
Expand Down Expand Up @@ -156,8 +156,8 @@ public CompletableFuture<DialogTurnResult> resumeDialog(DialogContext dc, Dialog
// Increment step index and run step
Map<String, Object> state = dc.getActiveDialog().getState();
int index = 0;
if (state.containsKey(stepIndex)) {
index = (int) state.get(stepIndex);
if (state.containsKey(STEP_INDEX)) {
index = (int) state.get(STEP_INDEX);
}

return runStep(dc, index + 1, reason, result);
Expand All @@ -178,9 +178,9 @@ public CompletableFuture<Void> endDialog(TurnContext turnContext, DialogInstance
HashMap<String, Object> state = new HashMap<String, Object>((Map<String, Object>) instance.getState());

// Create step context
int index = (int) state.get(stepIndex);
int index = (int) state.get(STEP_INDEX);
String stepName = waterfallStepName(index);
String instanceId = (String) state.get(persistedInstanceId);
String instanceId = (String) state.get(PERSISTED_INSTANCEID);

HashMap<String, String> properties = new HashMap<String, String>();
properties.put("DialogId", getId());
Expand All @@ -190,7 +190,7 @@ public CompletableFuture<Void> endDialog(TurnContext turnContext, DialogInstance
getTelemetryClient().trackEvent("WaterfallCancel", properties);
} else if (reason == DialogReason.END_CALLED) {
HashMap<String, Object> state = new HashMap<String, Object>((Map<String, Object>) instance.getState());
String instanceId = (String) state.get(persistedInstanceId);
String instanceId = (String) state.get(PERSISTED_INSTANCEID);

HashMap<String, String> properties = new HashMap<String, String>();
properties.put("DialogId", getId());
Expand All @@ -210,7 +210,7 @@ public CompletableFuture<Void> endDialog(TurnContext turnContext, DialogInstance
*/
protected CompletableFuture<DialogTurnResult> onStep(WaterfallStepContext stepContext) {
String stepName = waterfallStepName(stepContext.getIndex());
String instanceId = (String) stepContext.getActiveDialog().getState().get(persistedInstanceId);
String instanceId = (String) stepContext.getActiveDialog().getState().get(PERSISTED_INSTANCEID);

HashMap<String, String> properties = new HashMap<String, String>();
properties.put("DialogId", getId());
Expand Down Expand Up @@ -245,11 +245,11 @@ protected CompletableFuture<DialogTurnResult> runStep(DialogContext dc, int inde
// Update persisted step index
Map<String, Object> state = (Map<String, Object>) dc.getActiveDialog().getState();

state.put(stepIndex, index);
state.put(STEP_INDEX, index);

// Create step context
Object options = state.get(persistedOptions);
Map<String, Object> values = (Map<String, Object>) state.get(persistedValues);
Object options = state.get(PERSISTED_OPTIONS);
Map<String, Object> values = (Map<String, Object>) state.get(PERSISTED_VALUES);
WaterfallStepContext stepContext =
new WaterfallStepContext(this, dc, options, values, index, reason, result);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,23 @@
* Defines the core behavior of prompt dialogs.
*
* When the prompt ends, it should return a Object that represents the value
* that was prompted for. Use {@link DialogSet#add(Dialog)} or
* {@link ComponentDialog#addDialog(Dialog)} to add a prompt to a dialog set or
* component dialog, respectively. Use
* that was prompted for. Use {@link com.microsoft.bot.dialogs.DialogSet#add(Dialog)} or
* {@link com.microsoft.bot.dialogs.ComponentDialog#addDialog(Dialog)} to add a prompt to
* a dialog set or component dialog, respectively. Use
* {@link DialogContext#prompt(String, PromptOptions)} or
* {@link DialogContext#beginDialog(String, Object)} to start the prompt. If you
* start a prompt from a {@link WaterfallStep} in a {@link WaterfallDialog} ,
* then the prompt result will be available in the next step of the waterfall.
* start a prompt from a {@link com.microsoft.bot.dialogs.WaterfallStep} in a
* {@link com.microsoft.bot.dialogs.WaterfallDialog}, then the prompt result will be
* available in the next step of the waterfall.
*
* @param <T> Type the prompt is created for.
*/
public abstract class Prompt<T> extends Dialog {

public static final String ATTEMPTCOUNTKEY = "AttemptCount";

private final String persistedOptions = "options";
private final String persistedState = "state";
private static final String PERSISTED_OPTIONS = "options";
private static final String PERSISTED_STATE = "state";
private final PromptValidator<T> validator;

/**
Expand All @@ -58,8 +59,9 @@ public abstract class Prompt<T> extends Dialog {
* @param validator Optional, a {@link PromptValidator{T}} that contains
* additional, custom validation for this prompt.
*
* The value of {@link dialogId} must be unique within the
* {@link DialogSet} or {@link ComponentDialog} to which the
* The value of dialogId must be unique within the
* {@link com.microsoft.bot.dialogs.DialogSet} or
* {@link com.microsoft.bot.dialogs.ComponentDialog} to which the
* prompt is added.
*/
public Prompt(String dialogId, PromptValidator<T> validator) {
Expand Down Expand Up @@ -114,16 +116,16 @@ public CompletableFuture<DialogTurnResult> beginDialog(DialogContext dc, Object

// Initialize prompt state
Map<String, Object> state = dc.getActiveDialog().getState();
state.put(persistedOptions, opt);
state.put(PERSISTED_OPTIONS, opt);

HashMap<String, Object> pState = new HashMap<String, Object>();
pState.put(ATTEMPTCOUNTKEY, 0);
state.put(persistedState, pState);
state.put(PERSISTED_STATE, pState);

// Send initial prompt
onPrompt(dc.getContext(),
(Map<String, Object>) state.get(persistedState),
(PromptOptions) state.get(persistedOptions),
(Map<String, Object>) state.get(PERSISTED_STATE),
(PromptOptions) state.get(PERSISTED_OPTIONS),
false);
return CompletableFuture.completedFuture(Dialog.END_OF_TURN);
}
Expand Down Expand Up @@ -157,8 +159,8 @@ public CompletableFuture<DialogTurnResult> continueDialog(DialogContext dc) {

// Perform base recognition
DialogInstance instance = dc.getActiveDialog();
Map<String, Object> state = (Map<String, Object>) instance.getState().get(persistedState);
PromptOptions options = (PromptOptions) instance.getState().get(persistedOptions);
Map<String, Object> state = (Map<String, Object>) instance.getState().get(PERSISTED_STATE);
PromptOptions options = (PromptOptions) instance.getState().get(PERSISTED_OPTIONS);
PromptRecognizerResult<T> recognized = onRecognize(dc.getContext(), state, options).join();

state.put(ATTEMPTCOUNTKEY, (int) state.get(ATTEMPTCOUNTKEY) + 1);
Expand Down Expand Up @@ -226,8 +228,8 @@ public CompletableFuture<DialogTurnResult> resumeDialog(DialogContext dc, Dialog
*/
@Override
public CompletableFuture<Void> repromptDialog(TurnContext turnContext, DialogInstance instance) {
Map<String, Object> state = (Map<String, Object>) instance.getState().get(persistedState);
PromptOptions options = (PromptOptions) instance.getState().get(persistedOptions);
Map<String, Object> state = (Map<String, Object>) instance.getState().get(PERSISTED_STATE);
PromptOptions options = (PromptOptions) instance.getState().get(PERSISTED_OPTIONS);
onPrompt(turnContext, state, options, false).join();
return CompletableFuture.completedFuture(null);
}
Expand All @@ -252,7 +254,7 @@ protected CompletableFuture<Boolean> onPreBubbleEvent(DialogContext dc, DialogEv
// Perform base recognition
Map<String, Object> state = dc.getActiveDialog().getState();
PromptRecognizerResult<T> recognized = onRecognize(dc.getContext(),
(Map<String, Object>) state.get(persistedState), (PromptOptions) state.get(persistedOptions)).join();
(Map<String, Object>) state.get(PERSISTED_STATE), (PromptOptions) state.get(PERSISTED_OPTIONS)).join();
return CompletableFuture.completedFuture(recognized.getSucceeded());
}

Expand All @@ -272,8 +274,8 @@ protected CompletableFuture<Boolean> onPreBubbleEvent(DialogContext dc, DialogEv
* @param isRetry true if this is the first time this prompt dialog instance
* is on the stack is prompting the user for input;
* otherwise, false. Determines whether
* {@link PromptOptions#prompt} or
* {@link PromptOptions#retryPrompt} should be used.
* {@link PromptOptions#getPrompt()} or
* {@link PromptOptions#getRetryPrompt()} should be used.
*
* @return A {@link CompletableFuture} representing the asynchronous operation.
*/
Expand Down
21 changes: 21 additions & 0 deletions samples/43.complex-dialog/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Microsoft Corporation. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
90 changes: 90 additions & 0 deletions samples/43.complex-dialog/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Complex Dialog Sample

This sample creates a complex conversation with dialogs.

This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to use the prompts classes included in `botbuilder-dialogs`. This bot will ask for the user's name and age, then store the responses. It demonstrates a multi-turn dialog flow using a text prompt, a number prompt, and state accessors to store and retrieve values.

## Prerequisites

- Java 1.8+
- Install [Maven](https://maven.apache.org/)
- An account on [Azure](https://azure.microsoft.com) if you want to deploy to Azure.

## To try this sample locally
- From the root of this project folder:
- Build the sample using `mvn package`
- Run it by using `java -jar .\target\bot-complexdialog-sample.jar`

- Test the bot using Bot Framework Emulator

[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.

- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)

- Connect to the bot using Bot Framework Emulator

- Launch Bot Framework Emulator
- File -> Open Bot
- Enter a Bot URL of `http://localhost:3978/api/messages`

## Deploy the bot to Azure

As described on [Deploy your bot](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-deploy-az-cli), you will perform the first 4 steps to setup the Azure app, then deploy the code using the azure-webapp Maven plugin.

### 1. Login to Azure
From a command (or PowerShell) prompt in the root of the bot folder, execute:
`az login`

### 2. Set the subscription
`az account set --subscription "<azure-subscription>"`

If you aren't sure which subscription to use for deploying the bot, you can view the list of subscriptions for your account by using `az account list` command.

### 3. Create an App registration
`az ad app create --display-name "<botname>" --password "<appsecret>" --available-to-other-tenants`

Replace `<botname>` and `<appsecret>` with your own values.

`<botname>` is the unique name of your bot.
`<appsecret>` is a minimum 16 character password for your bot.

Record the `appid` from the returned JSON

### 4. Create the Azure resources
Replace the values for `<appid>`, `<appsecret>`, `<botname>`, and `<groupname>` in the following commands:

#### To a new Resource Group
`az deployment sub create --name "multiTurnPromptBotDeploy" --location "westus" --template-file ".\deploymentTemplates\template-with-new-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" botSku=S1 newAppServicePlanName="multiTurnPromptBotPlan" newWebAppName="multiTurnPromptBot" groupLocation="westus" newAppServicePlanLocation="westus"`

#### To an existing Resource Group
`az deployment group create --resource-group "<groupname>" --template-file ".\deploymentTemplates\template-with-preexisting-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" newWebAppName="multiTurnPromptBot" newAppServicePlanName="multiTurnPromptBotPlan" appServicePlanLocation="westus" --name "multiTurnPromptBot"`

### 5. Update app id and password
In src/main/resources/application.properties update
- `MicrosoftAppPassword` with the botsecret value
- `MicrosoftAppId` with the appid from the first step

### 6. Deploy the code
- Execute `mvn clean package`
- Execute `mvn azure-webapp:deploy -Dgroupname="<groupname>" -Dbotname="<botname>"`

If the deployment is successful, you will be able to test it via "Test in Web Chat" from the Azure Portal using the "Bot Channel Registration" for the bot.

After the bot is deployed, you only need to execute #6 if you make changes to the bot.


## Further reading

- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
- [Azure Portal](https://portal.azure.com)
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
- [Maven Plugin for Azure App Service](https://docs.microsoft.com/en-us/java/api/overview/azure/maven/azure-webapp-maven-plugin/readme?view=azure-java-stable)
- [Spring Boot](https://spring.io/projects/spring-boot)
- [Azure for Java cloud developers](https://docs.microsoft.com/en-us/azure/java/?view=azure-java-stable)
Loading