如何调用 http GET 并在 AWS Lambda 中使用响应?
How to call a http GET and use the response in AWS Lambda?
我查看了其他一些答案,但确实无法正常工作。
我想从 Alexa 调用一个 lambda - 这很好并且给我一个响应。我想将此响应基于对 http GET Web 服务的调用。到目前为止,我得到了下面的代码(已更新以显示完整的 lambda 代码):
/**
Copyright 2016 Brian Donohue.
*/
'use strict';
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
try {
console.log("event.session.application.applicationId=" + event.session.application.applicationId);
/**
* Uncomment this if statement and populate with your skill's application ID to
* prevent someone else from configuring a skill that sends requests to this function.
*/
// if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.05aecccb3-1461-48fb-a008-822ddrt6b516") {
// context.fail("Invalid Application ID");
// }
if (event.session.new) {
onSessionStarted({requestId: event.request.requestId}, event.session);
}
if (event.request.type === "LaunchRequest") {
onLaunch(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "IntentRequest") {
onIntent(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "SessionEndedRequest") {
onSessionEnded(event.request, event.session);
context.succeed();
}
} catch (e) {
context.fail("Exception: " + e);
}
};
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
+ ", sessionId=" + session.sessionId);
// add any session init logic here
}
/**
* Called when the user invokes the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log("onLaunch requestId=" + launchRequest.requestId
+ ", sessionId=" + session.sessionId);
var cardTitle = "Hello, World!"
var speechOutput = "You can tell Hello, World! to say Hello, World!"
callback(session.attributes,
buildSpeechletResponse(cardTitle, speechOutput, "", true));
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log("onIntent requestId=" + intentRequest.requestId
+ ", sessionId=" + session.sessionId);
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
// dispatch custom intents to handlers here
if (intentName == 'TestIntent') {
handleTestRequest(intent, session, callback);
}
else {
throw "Invalid intent";
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
+ ", sessionId=" + session.sessionId);
// Add any cleanup logic here
}
function handleTestRequest(intent, session, callback) {
//---Custom Code---
var speechOutput;
var myCallback = function(data) {
console.log('got data: '+data);
speechOutput = data;
};
var usingItNow = function(callback) {
const http = require('http');
var url = "http://services.groupkt.com/country/get/iso2code/IN";
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var result = JSON.parse(body);
//callback({"email":"test","name" : result.name});
callback('test');
});
}).on("error", (error) => {
//callback(err);
console.log('error');
});
};
usingItNow(myCallback);
//-----------------
callback(session.attributes,
buildSpeechletResponseWithoutCard("Testing Output " + speechOutput, "", "true"));
}
// ------- Helper functions to build responses -------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: title,
content: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
我已经根据下面的回复更新了这段代码,但我的测试回调甚至不起作用,更不用说真实的了。我想我遗漏了什么...
谢谢。
编辑:这是我的示例话语和意图(全部来自我遵循的示例)
{
"intents": [
{
"intent": "TestIntent"
},
{
"intent": "AMAZON.PauseIntent"
},
{
"intent": "AMAZON.ResumeIntent"
}
]
}
TestIntent hello world
TestIntent say hello world
TestIntent to say hello world
TestIntent test
您不需要 'return' 来自 http.get 的任何内容。您的回复应该 return 作为回电,如下所示,
var url = `URL HERE`;
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk
});
res.on("end", () => {
var result = JSON.parse(body);
callBack(result)
});
}).on("error", (error) => {
callBack(err);
});
我只更新了 lambda 函数逻辑以从 REST 调用中获取详细信息。请注意,它不包括对 Alexa 的构建响应,而只包括 REST 服务。请在下面找到相同的代码,
const http = require('http');
exports.handler = (event, context, callback) => {
usingItNow(function (result, error) {
if (error) {
console.log('error')
} else {
console.log("Final result is"+JSON.stringify(result))
callback(null,buildSpeechletResponseWithoutCard(result.name,"sample re-prompt",true))
}
});
};
var usingItNow = function (callback) {
var url = "http://services.groupkt.com/country/get/iso2code/IN";
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var result = JSON.parse(body);
callback({ "email": "test", "name":result.RestResponse.result.name });
//callback('test');
});
}).on("error", (error) => {
//callback(err);
console.log('error');
});
};
function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
我得到的结果,
我查看了其他一些答案,但确实无法正常工作。
我想从 Alexa 调用一个 lambda - 这很好并且给我一个响应。我想将此响应基于对 http GET Web 服务的调用。到目前为止,我得到了下面的代码(已更新以显示完整的 lambda 代码):
/**
Copyright 2016 Brian Donohue.
*/
'use strict';
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
try {
console.log("event.session.application.applicationId=" + event.session.application.applicationId);
/**
* Uncomment this if statement and populate with your skill's application ID to
* prevent someone else from configuring a skill that sends requests to this function.
*/
// if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.05aecccb3-1461-48fb-a008-822ddrt6b516") {
// context.fail("Invalid Application ID");
// }
if (event.session.new) {
onSessionStarted({requestId: event.request.requestId}, event.session);
}
if (event.request.type === "LaunchRequest") {
onLaunch(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "IntentRequest") {
onIntent(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "SessionEndedRequest") {
onSessionEnded(event.request, event.session);
context.succeed();
}
} catch (e) {
context.fail("Exception: " + e);
}
};
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
+ ", sessionId=" + session.sessionId);
// add any session init logic here
}
/**
* Called when the user invokes the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log("onLaunch requestId=" + launchRequest.requestId
+ ", sessionId=" + session.sessionId);
var cardTitle = "Hello, World!"
var speechOutput = "You can tell Hello, World! to say Hello, World!"
callback(session.attributes,
buildSpeechletResponse(cardTitle, speechOutput, "", true));
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log("onIntent requestId=" + intentRequest.requestId
+ ", sessionId=" + session.sessionId);
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
// dispatch custom intents to handlers here
if (intentName == 'TestIntent') {
handleTestRequest(intent, session, callback);
}
else {
throw "Invalid intent";
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
+ ", sessionId=" + session.sessionId);
// Add any cleanup logic here
}
function handleTestRequest(intent, session, callback) {
//---Custom Code---
var speechOutput;
var myCallback = function(data) {
console.log('got data: '+data);
speechOutput = data;
};
var usingItNow = function(callback) {
const http = require('http');
var url = "http://services.groupkt.com/country/get/iso2code/IN";
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var result = JSON.parse(body);
//callback({"email":"test","name" : result.name});
callback('test');
});
}).on("error", (error) => {
//callback(err);
console.log('error');
});
};
usingItNow(myCallback);
//-----------------
callback(session.attributes,
buildSpeechletResponseWithoutCard("Testing Output " + speechOutput, "", "true"));
}
// ------- Helper functions to build responses -------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: title,
content: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
我已经根据下面的回复更新了这段代码,但我的测试回调甚至不起作用,更不用说真实的了。我想我遗漏了什么...
谢谢。
编辑:这是我的示例话语和意图(全部来自我遵循的示例)
{
"intents": [
{
"intent": "TestIntent"
},
{
"intent": "AMAZON.PauseIntent"
},
{
"intent": "AMAZON.ResumeIntent"
}
]
}
TestIntent hello world
TestIntent say hello world
TestIntent to say hello world
TestIntent test
您不需要 'return' 来自 http.get 的任何内容。您的回复应该 return 作为回电,如下所示,
var url = `URL HERE`;
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk
});
res.on("end", () => {
var result = JSON.parse(body);
callBack(result)
});
}).on("error", (error) => {
callBack(err);
});
我只更新了 lambda 函数逻辑以从 REST 调用中获取详细信息。请注意,它不包括对 Alexa 的构建响应,而只包括 REST 服务。请在下面找到相同的代码,
const http = require('http');
exports.handler = (event, context, callback) => {
usingItNow(function (result, error) {
if (error) {
console.log('error')
} else {
console.log("Final result is"+JSON.stringify(result))
callback(null,buildSpeechletResponseWithoutCard(result.name,"sample re-prompt",true))
}
});
};
var usingItNow = function (callback) {
var url = "http://services.groupkt.com/country/get/iso2code/IN";
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var result = JSON.parse(body);
callback({ "email": "test", "name":result.RestResponse.result.name });
//callback('test');
});
}).on("error", (error) => {
//callback(err);
console.log('error');
});
};
function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
我得到的结果,