在Alexa技能中,您可以使用插槽进行内部路由,以便根据用户提供的信息采取不同的操作。下面是一个使用Node.js的代码示例:
const Alexa = require('ask-sdk-core');
const LaunchRequestHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
},
handle(handlerInput) {
const speakOutput = '欢迎使用技能,请提供一个数字。';
return handlerInput.responseBuilder
.speak(speakOutput)
.getResponse();
}
};
const NumberIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'NumberIntent';
},
handle(handlerInput) {
const numberSlot = Alexa.getSlotValue(handlerInput.requestEnvelope, 'number');
let speakOutput;
switch (numberSlot) {
case '1':
speakOutput = '您提供的是数字1。';
break;
case '2':
speakOutput = '您提供的是数字2。';
break;
default:
speakOutput = '抱歉,我无法识别您提供的数字。';
break;
}
return handlerInput.responseBuilder
.speak(speakOutput)
.getResponse();
}
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.error(`发生错误:${error.stack}`);
const speakOutput = '抱歉,我遇到了一些问题,请稍后再试。';
return handlerInput.responseBuilder
.speak(speakOutput)
.getResponse();
}
};
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
LaunchRequestHandler,
NumberIntentHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
在上面的示例中,我们定义了两个请求处理程序:LaunchRequestHandler
处理技能启动请求,NumberIntentHandler
处理用户提供数字的意图请求。根据用户提供的数字,我们在NumberIntentHandler
中使用switch
语句进行内部路由。
请注意,您需要根据您的技能设置和意图定义进行适当的更改。上面的示例仅用于演示目的。