Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a list of ~50 phone numbers I need to send the same SMS to via Twilio's API. How do I do that (via Python)?

I can do it in a for loop like so:

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

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

But instead of hitting Twilio's API multiple times, I'd rather send an array/list of phone numbers in bulk and just make one API call. So how do I do that? Is it possible at all?

I'm setting up a background async task to take care of outgoing text messages, and ideally wouldn't want my task to wait a long time while Twilio processes the messages one by one. I'd just want to send over a list of numbers as payload and be done with it.

like image 659
Hassan Baig Avatar asked Sep 14 '25 14:09

Hassan Baig


1 Answers

Twilio developer evangelist here.

You can achieve this using the Twilio Notify API. Notify is for sending notifications to multiple platforms, but that includes SMS.

Here's how you'd do it:

First, create a Notify service.

Then you need to register all your users and their numbers with the Notify API by creating bindings for all of them. Each binding requires some sort of identity from your system (a user id, or similar).

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
    )

Then, to send a notification to a group of users you just create a notification to their identities:

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

This only takes 20 identities at a time, though you can also do some work with tags when you create the bindings or segments to send more.

Let me know if this helps at all.

like image 129
philnash Avatar answered Sep 16 '25 03:09

philnash