如何在Alexa Skill开发中按对话阶段覆盖默认Intent实现差异化帮助响应
问题解答
结论
完全可以根据当前对话阶段覆盖亚马逊所有内置Intent,你提到的分阶段返回不同Help回复的需求可通过会话状态标记+逻辑判断实现,你目前提供的代码已经完成了自定义HelpIntent的基础覆盖,只需补充会话状态管理逻辑即可。
实现方案
你需要借助Alexa技能的会话属性(Session Attributes)标记当前所处的对话阶段,再在HelpIntent的处理逻辑中根据标记返回对应的回复内容,具体实现步骤如下:
- 第一步:在不同的对话节点设置阶段标记
比如在技能启动的LaunchRequestHandler中设置初始阶段标识,用户完成特定操作进入下一流程时更新标识:// LaunchRequestHandler示例 const LaunchRequestHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); // 设置初始阶段标记 sessionAttributes.stage = 'initial'; handlerInput.attributesManager.setSessionAttributes(sessionAttributes); const speakOutput = '欢迎使用技能,你可以说查询今日天气开始使用'; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } }; // 某个业务Intent示例,触发后更新对话阶段 const QueryWeatherIntentHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'QueryWeatherIntent'; }, handle(handlerInput) { const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); // 更新为查询流程阶段标记 sessionAttributes.stage = 'weather_query'; handlerInput.attributesManager.setSessionAttributes(sessionAttributes); // 业务逻辑省略 const speakOutput = '今日天气晴,气温25度,你还可以查询未来7天天气预报'; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } }; - 第二步:修改HelpIntentHandler,根据阶段标记返回不同回复
const HelpIntentHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.HelpIntent'; }, handle(handlerInput) { const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); const currentStage = sessionAttributes.stage || 'default'; let speakOutput = ''; switch(currentStage) { case 'initial': speakOutput = '你现在处于技能初始阶段,可以对我说查询天气、查询快递来使用对应功能'; break; case 'weather_query': speakOutput = '你现在处于天气查询流程,可以对我说查询明天天气、查询北京天气,也可以说返回回到主菜单'; break; default: speakOutput = '你可以说查询天气使用天气功能,说退出关闭技能'; } return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } };
注意事项
- 所有亚马逊内置Intent都可以用上述逻辑实现分阶段自定义处理
- 如果你修改代码后还是触发默认的Intent回复,请检查是否已经把自定义Handler注册到了SkillBuilder的handler链中,注册顺序没有特殊要求
- 会话属性仅在当前会话有效,会话关闭后自动清空,如果需要跨会话存储用户状态可以使用持久化属性存储
内容的提问来源于stack exchange,提问作者z3po
相关产品推荐
相关产品推荐

