How do I incorporate await sleep(milliseconds) between two set of messages in MS Bot Framework?

Viewed 79

I am developing a Bot using NodeJs which should ask the user a set of questions and then after a break, ask the same another of questions again. I am using await sleep(milliseconds) in between. While testing using the Emulator, I noticed that the questions from the first set are sent one by one, saving the user's response. The second set is sent all at once without allowing the user to respond to each question of the second set individually.

 await turnContext.sendActivity(askFirstSetOfQuestions(question));
 await sleep(60000);
 await turnContext.sendActivity(askSecondSetOfQuestions(question));

 await next();

image - screen capture from emulator image - screen capture from emulator

Quite lost here.. any help would be appreciated.

1 Answers

There are two things to consider here. First, if you truly need a delay, it is better to await a promise than use sleep. You can do this via await new Promise (resolve => setTimeout(resolve, DELAY_LENGTH);. I use this frequently in conjunction with typing indicator to give the bot a more natural feeling conversation flow when it sends two or more discrete messages without waiting for user input.

However, as Eric mentioned, it seems like you might want a waterfall dialog instead for your use case. This sample from botbuilder-samples is a good example. Each step would be a prompt, and it will wait for user input before proceeding. I won't try to write an entire bot here, but a single question-answer step would look something like:

async firstQuestion(stepContext) {
    return await stepContext.prompt(TEXT_PROMPT, 'Question 1');
}

async secondQuestion(stepContext) {
    stepContext.values.firstAnswer = stepContext.result;
    return await stepContext.prompt(TEXT_PROMPT, 'Question 2');
}

and so forth. Not sure what you are doing with the responses, but in the example above I'm saving it to stepContext.values so that the answers are all available in later steps as part of the context object.

If you can detail more of what your use case/expected behavior and share what askFirstSetOfQuestions is, we could provide further assistance.

Related