LordVee
LordVee

Reputation: 104

cannot get aws lambda to send sms via aws sns

I have copied the example in the various guides on the internet, including the fairly recent topic on SO:

How to send SMS using Amazon SNS from a AWS lambda function

I've implemented successfully the code from https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-sending-sms.html on my local nodejs server, however when i do the same on Lambda nothing happens, not even console.log???

This is the code i am using in Lambda:

const AWS = require('aws-sdk');

exports.handler = async (event) => {
  AWS.config.update({region: 'eu-west-2'});
  var params = {
    Message: 'TEXT_MESSAGE', /* required */
    PhoneNumber: '+1346879',
  };

  // Create promise and SNS service object
  var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

// Handle promise's fulfilled/rejected states
  publishTextPromise.then(
    function(data) {
      console.log("MessageID is " + data.MessageId);
    const response = {
        statusCode: 200,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    };
    console.log('Server response function');
    return response;
    }).catch(
      function(error) {
      //console.error(err, err.stack);
          const response = {
        statusCode: 500,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({error: 'Internal server error', message: error})
    };
    return response;
  });
}

Needless to say i tried various flavours of what seems to be an elementary piece of code... Logs say exactly this:

    2020-10-29T00:29:21.820+00:00   START RequestId: 8dbaedac-1f98-4319-9ac5-acba1d8860c5 Version: $LATEST

2020-10-29T00:29:22.242+00:00   Lambda Insights extension initializing.

2020-10-29T00:29:22.242+00:00   EXTENSION Name: cloudwatch_lambda_agent State: Ready Events: [INVOKE,SHUTDOWN]

2020-10-29T00:29:22.838+00:00   END RequestId: 8dbaedac-1f98-4319-9ac5-acba1d8860c5

2020-10-29T00:29:22.838+00:00

Copy
REPORT RequestId: 8dbaedac-1f98-4319-9ac5-acba1d8860c5  Duration: 594.62 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 99 MB  Init Duration: 448.90 ms    
REPORT RequestId: 8dbaedac-1f98-4319-9ac5-acba1d8860c5 Duration: 594.62 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 99 MB Init Duration: 448.90 ms

I have set permissions in the same exact way both on my user and on lambda:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sns:*",
            "Resource": "*"
        }
    ]
}

Any thought?

Upvotes: 0

Views: 914

Answers (2)

Filipe Mendes
Filipe Mendes

Reputation: 185

I think that you have to return a promise to ensure all the tasks will be executed till the end.

If your code performs an asynchronous task, return a promise to make sure that it finishes running. When you resolve or reject the promise, Lambda sends the response or error to the invoker.

const AWS = require('aws-sdk');

exports.handler = async (event) => {
    AWS.config.update({region: 'eu-west-2'});
    var params = {
        Message: 'TEXT_MESSAGE', /* required */
        PhoneNumber: '+1346879',
    };

    // Create promise and SNS service object
    var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

    return new Promise((resolve, reject) => {
        // Handle promise's fulfilled/rejected states
        publishTextPromise.then((data) => {
            console.log("MessageID is " + data.MessageId);
            const response = {
                statusCode: 200,
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(data)
            };
            console.log('Server response function');
            resolve(response);
        }).catch((error) => { reject(Error(error)); });
    });
}

Upvotes: 1

Siva Sumanth
Siva Sumanth

Reputation: 662

  • Check the lambda execution time, try to increase it to 15 mins.
  • This SNS is having two types of messages 1.Promotional 2.Transactional
  • By default it choose promotional. If end users is having DND enabled to his number. Then your message will not delivered.
  • If it is related to transactional use the below object for sending transactional messages.

    {
       Message: 'Message',
       PhoneNumber: '+XXX',
       MessageAttributes: {
        'AWS.SNS.SMS.SMSType': {
           DataType: 'String',
           StringValue: 'Transactional'
        }
     }

Upvotes: 1

Related Questions