botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

beginDialog inside a for loop?

Open suvamsh opened this issue 10 years ago • 4 comments

I've got a list of text questions. I want to loop over them and start a new 'ask' dialog to prompt the user for the question then store their response.

for(var q in questions) { session.beginDialog('/ask'); }

This does not work I get the following error:

Oops. Something went wrong and we need to start over. Error: Dialog[BotBuilder:/ask] not found.

But if I take it out of the for loop it works. What is the correct way to do this?

suvamsh avatar Oct 16 '16 00:10 suvamsh

Take a look at the waterfall code samples here: https://github.com/Microsoft/BotBuilder/tree/master/Node/examples#basic-techniques

danmarshall avatar Oct 17 '16 17:10 danmarshall

In that example I need to write out a function() {prompt} followed by a function(session, results) for every question. I am pulling a list of questions from a database (which changes every time) and I want to ask these questions and store the result? It seems to me that I would need to hard code each of the questions with it's own function. But if I have a different number of question each time this won't work.

suvamsh avatar Oct 17 '16 20:10 suvamsh

Here's an example of using replaceDialog() to create a simple loop over a dynamic set of questions. You could easily expand this to be more complicated:

bot.dialog('/', [
    function (session) {
        session.beginDialog('/q&a');
    },
    function (session, results) {
        session.send("Thanks %(name)s... You're %(age)s and located in %(state)s.", results.response);
    }
]);

bot.dialog('/q&a', [
    function (session, args) {
        // Save previous state (create on first call)
        session.dialogData.index = args ? args.index : 0;
        session.dialogData.form = args ? args.form : {};

        // Prompt user for next field
        builder.Prompts.text(session, questions[session.dialogData.index].prompt);
    },
    function (session, results) {
        // Save users reply
        var field = questions[session.dialogData.index++].field;
        session.dialogData.form[field] = results.response;

        // Check for end of form
        if (session.dialogData.index >= questions.length) {
            // Return completed form
            session.endDialogWithResult({ response: session.dialogData.form });
        } else {
            // Next field
            session.replaceDialog('/q&a', session.dialogData);
        }
    }
]);

var questions = [
    { field: 'name', prompt: "What's your name?" },
    { field: 'age', prompt: "How old are you?" },
    { field: 'state', prompt: "What state are you in?" }
];

Stevenic avatar Oct 19 '16 07:10 Stevenic

Thank you this worked for me.

suvamsh avatar Oct 20 '16 03:10 suvamsh