我试图建立一个Alexa技能,在它的启动时必须通过Node JS请求模块发出一个发布请求来获取数据。
实际发出请求的代码摘录有效,因为我已经自行测试了它。但是,当我尝试将其包含在AWS Lambda函数中时,它不会被执行。
由于我是JS和AWS的初学者,对我来说调试起来非常困难,而且我甚至无法远程解决这个问题。真正感谢任何帮助。
exports.handler = (event, context) => {
try {
// New session
if (event.session.new) {
// New Session
console.log("NEW SESSION");
}
// Launch Request
switch (event.request.type) {
case "LaunchRequest":
var url = "https://api.random.org/json-rpc/1/invoke";
var myRequest = {
"jsonrpc": "2.0",
"method": "generateStrings",
"params": {
"apiKey": "my-api-key",
"n": "1",
"length": "3",
"characters": "abcdefghijklmnopqrstuvwxyz0123456789"
},
"id": 96
}
var pin;
request.post(
url,
{json: myRequest},
function (error, response, body) {
if (!error && response.statusCode == 200) {
pin = body.result.random.data[0];
console.log(pin);
}
else {
console.log(error);
}
}
);
console.log("LAUNCH REQUEST");
var welcome = "Welcome. ";
var pinStatement = "Your 3 letter or number pin is: " + pin
context.succeed(
generateResponse(
buildSpeechletReponse(welcome + pinStatement, true),
{}
)
);
break;
// Intent Request
case "IntentRequest":
console.log("INTENT REQUEST");
break;
// Session Ended Request
case "SessionEndedRequest":
console.log("SESSION ENDED REQUEST");
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
}
}
catch (error) {
context.fail(`Exception: ${error}`);
}
}
//Here are the helper functions:
buildSpeechletReponse = (outputText, shouldEndSession) => {
return {
outputSpeech : {
type: "PlainText",
text: outputText
},
shouldEndSession: shouldEndSession
};
}
generateResponse = (sessionAttributes, speechletResponse) => {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
答案 0 :(得分:2)
在您的请求收到回复之前,您已致电context.succeed()
。
case "LaunchRequest":
var url = "https://api.random.org/json-rpc/1/invoke";
var myRequest = {
"jsonrpc": "2.0",
"method": "generateStrings",
"params": {
"apiKey": "my-api-key",
"n": "1",
"length": "3",
"characters": "abcdefghijklmnopqrstuvwxyz0123456789"
},
"id": 96
}
var pin;
request.post(
url,
{json: myRequest},
function (error, response, body) {
if (!error && response.statusCode == 200) {
pin = body.result.random.data[0];
console.log(pin);
var response = buildSpeechletReponse("Welcome. Your 3 letter or number pin is: " + pin, true)
context.succeed(generateResponse(response, {}));
}
else {
context.fail(error || body);
}
}
);
console.log("LAUNCH REQUEST");
break;