一次 API 调用以向多个用户发送短信 (Twilio)

One API call to send SMS to multiple users (Twilio)

我有一个包含 ~50 phone 个号码的列表,我需要通过 Twilio 的 API 向其发送相同的 SMS。我该怎么做(通过 Python)?

我可以像这样在 for 循环中完成:

from twilio.rest import Client
client = Client(SID, AT)

for number in number_list:
    client.messages.create(to=number, from_="+18328955063",body="foo bar")

但与其多次点击 Twilio 的 API,我宁愿批量发送 array/list 个 phone 号码,然后只拨打一个 API 电话。那我该怎么做呢?有可能吗?

我正在设置一个后台异步任务来处理外发短信,理想情况下我不希望我的任务在 Twilio 一条一条地处理消息时等待很长时间。我只想发送一个数字列表作为有效载荷并完成它。

此处为 Twilio 开发人员布道师。

您可以使用 Twilio Notify API 实现此目的。 Notify 用于向多个平台发送通知,但其中包括 SMS。

您可以这样做:

首先,创建一个Notify service

然后您需要通过 creating bindings 的 Notify API 为所有用户注册所有用户及其号码。每个绑定都需要来自您系统的某种身份(用户 ID 或类似身份)。

from twilio.rest import Client

account = "YOUR_ACCOUNT_TOKEN"
token = "YOUR_AUTH_TOKEN"
client = Client(account, token)

service = client.notify.services("YOUR_NOTIFY_SERVICE_SID")

for identity, number in user_dict.items():
    service.bindings.create(
        identity=identity,
        binding_type="sms",
        address=number
    )

然后,要向一组用户发送通知,您只需为他们的身份创建通知:

service.notifications.create(identity=list_of_identities,
                             body="Hello world!")

这一次只需要 20 个身份,但您也可以在创建绑定时使用标签做一些工作,或者 segments 发送更多。

如果这有帮助,请告诉我。

你也可以这样做: https://www.twilio.com/docs/notify/api/notification-resource#code-send-a-notification-to-bindings-in-the-request-1

notification = client.notify.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")\
    .notifications.create(
        to_binding=[
            "{\"binding_type\":\"sms\",\"address\":\"+15555555555\"}",
            "{\"binding_type\":\"facebook-messenger\",\"address\":\"123456789123\"}"
        ],
        body="Hello Bob")

无需创建绑定, 顺便说一下,twilio 可以接受 10,000 个数字

The destination address specified as a JSON string. Multiple to_binding parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers.