AIML技术咨询:如何仅在按钮点击时通过Think/Set设置变量
解决AIML按钮点击赋值变量的问题
你当前的写法会在加载quiz模板时就执行所有<think><set>标签,导致question1被最后一次赋值覆盖——根本原因是按钮模板里的代码在生成按钮时就会运行,而不是点击后才触发。
正确的做法是把变量赋值逻辑移到按钮点击后的回调处理里,具体步骤如下:
- 修改按钮的
postback内容,把对应选项的编号包含进去,比如让postback变成question2 1、question2 2这类格式,用来区分用户点击的是哪个选项。 - 创建专门的category来处理这些带编号的postback,在这些category里完成变量赋值,再返回后续的问题内容。
修改后的AIML代码示例
初始的quiz触发category
<category> <pattern>quiz</pattern> <template> Which of these topics are most interesting to you? <button> <text>topic1</text> <postback>question2 1</postback> </button> <button> <text>topic2</text> <postback>question2 2</postback> </button> <button> <text>topic3</text> <postback>question2 3</postback> </button> <button> <text>topic4</text> <postback>question2 4</postback> </button> <button> <text>topic5</text> <postback>question2 5</postback> </button> </template> </category>
处理postback的category
<!-- 处理topic1的选择 --> <category> <pattern>question2 1</pattern> <template> <think><set name="question1">1</set></think> <!-- 这里写question2的内容 --> 接下来是问题2的内容... </template> </category> <!-- 处理topic2的选择 --> <category> <pattern>question2 2</pattern> <template> <think><set name="question1">2</set></think> 接下来是问题2的内容... </template> </category> <!-- 同理复制处理topic3、4、5的category --> <category> <pattern>question2 3</pattern> <template> <think><set name="question1">3</set></think> 接下来是问题2的内容... </template> </category> <category> <pattern>question2 4</pattern> <template> <think><set name="question1">4</set></think> 接下来是问题2的内容... </template> </category> <category> <pattern>question2 5</pattern> <template> <think><set name="question1">5</set></think> 接下来是问题2的内容... </template> </category>
这样用户点击某个按钮后,对应的postback内容会被AIML匹配到对应的category,此时才会执行<set>标签赋值变量,就不会出现覆盖的问题了。
内容的提问来源于stack exchange,提问作者cd78
相关产品推荐
相关产品推荐

