我在Node.js上使用Bot Framework。我想从文件中提取一定数量的问题,然后提示用户提供所有问题的答案。有没有办法循环一个对话框来完成这个,还是有其他解决方案可以工作?
答案 0 :(得分:1)
通过使用下面的逻辑,您应该能够遍历文件中的每个提示。
bot.dialog('prompting', [
(session, args) => {
if ('currentPrompt' in args) {
let promptsData = promptRetriever();
session.conversationData.currentPrompt = args.currentPrompt;
// switch statement so the correct type of prompt is sent to the user
switch (args.promptType) {
case 'text':
builder.Prompts.text(session, promptsData[args.currentPrompt].text);
break;
case 'confirm':
builder.Prompts.confirm(session, promptsData[args.currentPrompt].text);
break;
case 'number':
builder.Prompts.number(session, promptsData[args.currentPrompt].text);
break;
}
} else {
let firstPrompt = promptRetriever()['prompt1'];
session.conversationData.currentPrompt = 'prompt1';
builder.Prompts.confirm(session, firstPrompt.text);
}
},
(session, results) => {
// Store the response for the value of the prompt on session.userData
session.userData[session.conversationData.currentPrompt] = results.response;
delete session.conversationData.currentPrompt;
// Retrieve all the keys (prompts) from prompts.json
let prompts = promptRetriever();
// If the lengths are the same then every prompt has been asked,
// so respond with the user's answers.
if (Object.keys(session.userData).length === Object.keys(prompts).length) {
session.send('You answered all the prompts!')
.send(`prompt1 result: ${session.userData.prompt1}`)
.send(`prompt2 result: ${session.userData.prompt2}`)
.send(`prompt3 result: ${session.userData.prompt3}`)
session.endDialog('Ending dialog.');
} else {
let promptsKeys = Object.keys(prompts);
for (let key in promptsKeys) {
if (!(promptsKeys[key] in session.userData)) {
session.replaceDialog('prompting', {
currentPrompt: promptsKeys[key],
promptType: prompts[promptsKeys[key]].type }
);
break;
}
}
}
}
]).triggerAction({
matches: /prompts/ig
});
// Helper function for accessing out prompts in json format
function promptRetriever() {
return require('./prompts.json');
}
然后用于此示例的prompts.json的结构是:
{
"prompt1": {
"text": "Please say yes or no",
"type": "confirm"
},
"prompt2": {
"text": "Please say something",
"type": "text"
},
"prompt3": {
"text": "What is your age",
"type": "number"
}
}