Thursday, 11 May 2017

Publishing to SNS from within AWS Lambda Alexa Intent, Node.js

I have a Lambda function written in Node.js that successfully publishes to a SNS. When I put the same function within an Alexa intent in the Alexa Lambda function, it gets executed only if I comment out the Alexa part of the code.

This is the stand-alone Lambda function that works:

var AWS = require("aws-sdk");

exports.handler = function() {
    var sns = new AWS.SNS();
    var params = {
        Message: "Cheese", 
        Subject: "Test SNS From Lambda",
        TopicArn: "arn:aws:sns:us-east-1:xxxxxxx:MyTopic"
    };
    sns.publish(params, function(){});
};

If I then try to put the SNS code within a function in my Alexa lambda function, it doesn't execute. The rest of the Alexa code works fine, but nothing is published to SNS. If I however comment out the Alexa part of it, it does indeed work.

This is the code that doesn't work (aws-sdk is included at the top of the file and omitted from this example):

exports.handler = function(event, context) {

    var sns = new AWS.SNS();
    var params = {
        Message: "Cheese", 
        Subject: "Test SNS From Lambda",
        TopicArn: "arn:aws:sns:us-east-1:xxxxxxx:MyTopic"
    };
    sns.publish(params, function(){}); 

    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.resources = languageStrings;
    alexa.registerHandlers(newSessionHandlers, memberModeHandlers);
    alexa.execute();
};

If I comment out all of the Alexa stuff in the exports.handler function, the SNS publish works, but obviously the rest of the app fails.

Like this, this will work:

exports.handler = function(event, context) {

    var sns = new AWS.SNS();
    var params = {
        Message: "Cheese", 
        Subject: "Test SNS From Lambda",
        TopicArn: "arn:aws:sns:us-east-1:xxxxxxx:MyTopic"
    };
    sns.publish(params, function(){}); 

  /*
  const alexa = Alexa.handler(event, context);
  alexa.APP_ID = APP_ID;
  // To enable string internationalization (i18n) features, set a resources object.
  alexa.resources = languageStrings;
  alexa.registerHandlers(newSessionHandlers, memberModeHandlers);
  alexa.execute();
  */
};

Any thoughts as to what is going on here? Ideally what I want to do is to put the sns publishing code in a separate function that I then call from an intent that is being invoked at one point during the Alexa skill, but so far I cannot make this thing work together with the Alexa code.



via Sjur Sundin

No comments:

Post a Comment