0
我對lambda函數很陌生,如果這個問題很愚蠢,請道歉。下面的代碼工作 第一部分,它啓動EC2實例,但如果我把它鏈接到Alexa的爲什麼我在使用Callback時無法啓動實例?
var aws = require("aws-sdk");
var https=require('https')
exports.handler = (event, context, callback) => {
try{
if (event.session.new) {
//New Session
console.log("NEW SESSION")
}
switch (event.request.type){
case "IntentRequest":
// > Intent Request
console.log(`INTENT REQUEST`)
switch(event.request.intent.name){
case "StartecInsatnce":
console.log(`Test msg`)
var ec2=new aws.EC2({region: 'us-east-1'});
var endpoint= ec2.startInstances({InstanceIds: ['i-0a20b89becb6fcb7e']}, function(err,data) {
if (err) console.log(err,err.stack);
else console.log(data);
context.done(err,data);
});
callback(null, "some success message");
}
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)
}
}
catch(error) { context.fail(`EXCEPTION: ${error}`) }
}
所以我用下面的代碼,這雖然發送響應,但無法啓動EC2實例不起作用。請幫助
var aws = require("aws-sdk");
var https=require('https')
exports.handler = (event, context, callback) => {
try{
if (event.session.new) {
//New Session
console.log("NEW SESSION")
}
switch (event.request.type){
case "IntentRequest":
// > Intent Request
console.log(`INTENT REQUEST`)
switch(event.request.intent.name){
case "StartecInsatnce":
onIntent(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
// callback(null, "some success message");
}//end of inner switch
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)
}
}
catch(error) { context.fail(`EXCEPTION: ${error}`) }
//Helpers
generateResponse = (sessionAttributes, speechletResponse) => {
return{
version: "1.0",
sessionAttributes: "sessionAttributes",
response: "speechletResponse"
}
}
}
function onIntent(intentRequest, session, callback) {
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
var cardTitle = intent.name;
console.log(`Test msg`)
var sessionAttributes={}
var shouldEndSession = false;
speechOutput = "instance started.";
var ec2=new aws.EC2({region: 'us-east-1'});
var endpoint= ec2.startInstances({InstanceIds: ['i-0a20b89becb6fcb7e']}, function(err,data) {
if (err) console.log(err,err.stack);
else console.log(data);
context.done(err,data);
});
console.log("end="+endpoint)
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, shouldEndSession));
}
function buildSpeechletResponse(title, output, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: "SessionSpeechlet - " + title,
content: "SessionSpeechlet - " + output
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
謝謝,我剛從ec2 start-instance中刪除了context.done。你能否建議我是否可以編輯ec2.startInstances所做的回調調用? –