问题
I'm creating a chat bot for slack using Microsoft's botbuilder and LUIS.
Is there a way to keep using builder.Prompts.text()
to keep asking the user if there are anymore information the user wants to put, like a for
or while
loop? For example I want to keep on asking the user an undefined number of times if there's a key
the user wants to save and only stop when the user types done
and then I will have an equal number of builder.Prompts.text()
to ask the user for the values to put in each of those keys.
function (session, results, next) {
builder.Prompts.text(session, "Another key to put?");
},
function (session, results, next) {
builder.Prompts.text(session, "Value to put?");
}
It doesn't seem like I can create some sort of loop with an array that saves each key with its value, I'm not sure how to approach this.
Thanks.
回答1:
What you're looking for is session.replaceDialog(); there is an example labeled 'basics-loops' on the GitHub repo for the SDK. To loop through prompts, one has to create a small dialog with the desired prompts and have the dialog restart automatically via session.replaceDialog() or session.beginDialog().
I've built a chatbot that receives key-value pairs in the scenario you specified above. The code excerpt below is the final step in my 'Loop' dialog.
function (session, results) {
var value = results.response ? results.response : null,
key = session.dialogData.key;
var pairs = session.userData.kVPairs;
var newPair = {};
newPair[key] = value;
if (key && value) {
session.userData.kVPairs.push(newPair);
console.log(pairs[pairs.length - 1]);
}
session.send('latest key-value pair added, { %s : %s }', key, value);
session.replaceDialog('Loop');
}
session.replaceDialog('Loop') is incorporated at the end of this waterfall step and takes the Id of the new dialog. The method can also take optional arguments to pass to the new dialog.
Note: While not applicable here, the difference between replaceDialog and beginDialog/endDialog is semi-obvious, when you use beginDialog, the new dialog is added to the stack. When you end that child dialog, you will be returned to the original/parent dialog. replaceDialog will end the current dialog and begin the new one.
回答2:
You may use replacedialog to loop the user:
bot.dialog("/getUserKeys", [
function (session, args, next) {
session.dialogData.keys = args && args.keys ? args.keys : [];
builder.Prompts.text(session, "Another key to put?");
},
function (session, results, next) {
if (results.response === "none") {
session.endDialogWithResult({response: { keys: session.DialogData.keys }});
return;
}
session.dialogData.keys[session.dialogData.keys.length] = results.response;
session.replaceDialog("/getUserKeys", { keys: session.DialogData.keys });
}
]);
来源:https://stackoverflow.com/questions/43188558/botframework-prompt-dialogs-until-user-finishes