的問題是,編程助手是事件驅動的系統(各意圖是一個事件),並且結束該服務器上的事件的處理與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。 –