【问题标题】:cannot get aws lambda to send sms via aws sns无法让 aws lambda 通过 aws sns 发送短信
【发布时间】:2020-10-29 00:40:36
【问题描述】:

我已经复制了互联网上各种指南中的示例,包括最近关于 SO 的主题:

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

我已经在我的本地 nodejs 服务器上成功实现了来自 https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-sending-sms.html 的代码,但是当我在 Lambda 上执行相同操作时,没有任何反应,甚至 console.log 都没有???

这是我在 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;
  });
}

不用说,我尝试了各种似乎是基本代码的风格...... 日志就是这样说的:

    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

我在我的用户和 lambda 上都以完全相同的方式设置了权限:

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

有什么想法吗?

【问题讨论】:

  • 消息会进入 SNS 吗?您可以在 SNS 上为失败的消息设置日志记录,以检查它们是否最终出现。
  • 我已经设置了日志记录,但似乎不是这样......没有错误没有什么,有趣的是api网关返回代码200......

标签: amazon-web-services aws-lambda amazon-sns


【解决方案1】:
  • 检查 lambda 执行时间,尝试将其增加到 15 分钟。
  • 此 SNS 有两种类型的消息 1.Promotional 2.Transactional
  • 默认选择促销。如果最终用户对他的号码启用了免打扰。那么您的消息将不会送达。
  • 如果它与事务相关,请使用以下对象发送事务消息。

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

【讨论】:

  • tks Siva 为您解答,我将函数增加到 15 分钟,将 msg 设置为事务性,但结果仍然相同:函数只是在瞬间执行并完成,完全忽略了 sns 部分代码。有趣的是,api 网关返回 200 响应为空????
【解决方案2】:

我认为你必须返回一个承诺,以确保所有任务都会执行到最后。

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)); });
    });
}

【讨论】:

  • 我认为回调是针对同步处理程序docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
  • 当然!查看建议的文档,我注意到,当您使用异步函数时,您必须返回一个承诺。请注意,处理函数没有返回代码。
  • 对了。我把它包装在一个承诺中,消息就直接进来了!谢谢你,伙计编辑:你一直在你的回复中写,昨天我完全误解了你写的东西,解决方案一直在那里抱歉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多