在 AWS Lambda 函数中使用 boto3 通过 AWS SNS 发送短信?

Send an SMS via AWS SNS using boto3 in an AWS Lambda function?

我想使用 boto3 发布方法从 AWS Lambda 函数发送 SMS 消息,以通过 SMS 通知用户问题。我的 lambda 函数是用 Python 编写的,我使用的是 boto3 模块。我的 lambda 函数拥有 SNS 的全部权限。我有这个代码,

sns = boto3.client('sns')
sns.publish(
    PhoneNumber = '+11234567890',
    Message = 'Simple text message'
)

根据boto3 documentation,publish方法接受以下参数,

response = client.publish(
    TopicArn='string',
    TargetArn='string',
    PhoneNumber='string',
    Message='string',
    Subject='string',
    MessageStructure='string',
    MessageAttributes={
        'string': {
            'DataType': 'string',
            'StringValue': 'string',
            'BinaryValue': b'bytes'
        }
    }
)

它需要一个 "Message" 参数和文档中描述的以下三个参数之一:

TopicArn (string) -- The topic you want to publish to.

If you don't specify a value for the TopicArn parameter, you must specify a value for the PhoneNumber or TargetArn parameters.

TargetArn (string) -- Either TopicArn or EndpointArn, but not both.

If you don't specify a value for the TargetArn parameter, you must specify a value for the PhoneNumber or TopicArn parameters.

PhoneNumber (string) -- The phone number to which you want to deliver an SMS message. Use E.164 format.

If you don't specify a value for the PhoneNumber parameter, you must specify a value for the TargetArn or TopicArn parameters.

执行我的代码时返回参数验证错误。它指出,

Unknown parameter in input: "PhoneNumber", must be one of: TopicArn, TargetArn, >Message, Subject, MessageStructure, MessageAttributes".

所以文档上好像说PhoneNumber是一个有效的参数,但是在使用的时候出现了错误,错误的反馈说PhoneNumber不是一个可能的参数。我怀疑我遗漏了一些明显而简单的东西,但需要一些帮助。

我知道还有其他途径可以发送 SMS 消息,例如电子邮件网关和其他供应商提供的解决方案(如 Twilio),但我想采用基于 SNS 的路由并了解我哪里出错了。

实际上你的例子看起来是正确的。这是我试过的

import boto3
sns = boto3.client('sns')
number = '+17702233322'
sns.publish(PhoneNumber = number, Message='example text message' )

工作得很好。我建议首先使用配置了根帐户凭据的 awscli,然后使用代码进行测试。一旦它工作,要么创建一个仅具有您需要的权限的新用户,要么将其应用于实例角色。

您需要创建一个允许 SNS:Publish 资源的策略:*(允许向所有人发送短信)或资源:'+17702233322'(允许向特定号码发送短信)。