问题是 Assistant 的编程是一个事件驱动的系统(每个 Intent 都是一个事件),并且您在服务器上使用assistant.ask()
或结束事件的处理assistant.tell()
。这会将您的回复发送回用户。ask()
然后将等待另一个事件,whiletell()
表示对话结束。
这意味着您不能将ask()
结果放入循环中,也不能将结果存储在局部变量中,因为每个答案都会作为新事件返回给您(即 - 每次都对您的 webhook 进行新调用)。
这是一种方法。它由三部分组成:
- 用于首先使用操作调用 webhook
name.entry
并触发循环的意图(我的屏幕截图中的 name.init)。
- 当上下文处于活动状态时响应的意图(我的屏幕截图中的 name.loop)
name_loop
以获取名称并使用相同的操作将其发送到 webhook 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!` );
}
};