的问题是,编程助手是事件驱动的系统(各意图是一个事件),并且结束该服务器上的事件的处理与assistant.ask()
或assistant.tell()
。这会将您的回复发回给用户。然后ask()
将等待另一个事件,而tell()
指示对话结束。
这意味着你不能把ask()
放在一个循环中,你不能把结果存储在一个局部变量中,因为每个答案都会作为一个新事件返回给你(比如 - 每次都有一个新的webhook调用)。
这是一种方法。它由三个部分组成:
- 的意图(name.init在我的屏幕截图)用来先调用网络挂接与动作
name.entry
并触发循环。
- 当
name_loop
上下文处于活动状态以获取名称并将其以相同动作发送给webhook时,响应的意图(屏幕截图中的name.loop)name.entry
。
- 处理
name.entry
意图的代码片段。
代码
var loopAction = function(assistant){
const CONTEXT = 'name_loop';
const PARAM = 'name';
const VALUE = 'index';
const NUM_NAMES = 4;
// Get the context, which contains the loop counter index, so we know
// which name we're getting and how many times we've been through the loop.
var index;
var context = assistant.getContext(CONTEXT);
if(!context){
// If no context was set, then we are just starting the loop, so we
// need to initialize it.
index = 0;
} else {
// The context is set, so get the invex value from it
index = context.parameters[VALUE];
// Since we are going through the loop, it means we were prompted for
// the name, so get the name.
var name = assistant.getArgument(PARAM);
// Save this all, somehow.
// We may want to put it back in a context, or save it in a database,
// or something else, but there are things to be aware of:
// - We can't save it in a local variable - they will go out of scope
// after we send the next reply.
// - We can't directly save it in a global variable - other users who
// call the Action will end up writing to the same place.
loopSave(index, name);
// Increment the counter to ask for the next name.
index++;
}
if(index < NUM_NAMES){
// We don't have all the names yet, ask for the next one
// Build the outgoing context and store the new index value
var contextValues = {};
contextValues[VALUE] = index;
// Save the context as part of what we send back to API.AI
assistant.setContext(CONTEXT, 5, contextValues);
// Ask for the name
assistant.ask(`Please give me name ${index}`);
} else {
// We have reached the end of the loop counter.
// Clear the context, making sure we don't continue through the loop
// (Not really needed in this case, since we're about to end the
// conversation, but useful in other cases, and a good practice.)
assistant.setContext(CONTEXT, 0);
// End the conversation
assistant.tell(`I got all ${index}, thanks!`);
}
};
你可以发布不工作的代码和你的api.ai意图的任何屏幕截图吗? – Prisoner
这听起来像你正试图从用户收集一些不同的值?您可能想查看我们的个人厨师视频,该视频展示了如何从同一意图收集后续问题的信息:https://youtu.be/9SUAuy9OJg4 –
@Prisoner posted。 –