To implement returning a formatted response from JavaScript (Node.js) in a Lambda Function:
First create some handy functions for building proper Lex response formats.
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
You can find more Node response-building functions like that in AWS-Lex-Convo-Bot-Example index.js
Then just call that function and pass it what it needs, like this:
var message = {
'contentType': 'PlainText',
'content': 'Hi! How can I help you?'
}
var responseMsg = close( sessionAttributes, 'Fulfilled', message );
(write your message inside 'content', if using SSML tags, change 'contentType' to 'SSML')
Then pass responseMsg
to the callback
of exports.handler
.
Put it all together and you get:
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
exports.handler = (event, context, callback) => {
console.log( "EVENT= "+JSON.stringify(event) );
const intentName = event.currentIntent.name;
var sessionAttributes = event.sessionAttributes;
var responseMsg = "";
if (intentName == "HelloIntent") { // change 'HelloIntent' to your intent's name
var message = {
'contentType': 'PlainText',
'content': 'Hi! How can I help you?'
}
responseMsg = close( sessionAttributes, 'Fulfilled', message );
}
// else if (intentName == "Intent2") {
// build another response for this intent
// }
else {
console.log( "ERROR unhandled intent named= "+intentName );
responseMsg = close( sessionAttributes, 'Fulfilled', {"contentType":"PlainText", "content":"Sorry, I can't help with that yet."});
}
console.log( "RESPONSE= "+JSON.stringify(responseMsg) );
callback(null, responseMsg);
}