简体   繁体   中英

Twilio - How to send bulk sms with a different body text per phone number?

I have an average of 100 - 1500 phone numbers that I want to send SMS to. I want to include the person's name that is associated with each phone number in the body text. How would I be able to do this using Twilio?

client.notify.services(notifyServiceSid)
.notifications.create({
toBinding: JSON.stringify({
  binding_type: 'sms', address: process.env.NUMBER_ONE,
  binding_type: 'sms', address: process.env.NUMBER_TWO
}),
body: 'This should work!' //I want to dynamically change this per number.
})
.then(notification => console.log(notification.sid))
.catch(error => console.log(error));

There are many ways doing it.

An example:

file: broadcast.js

require('dotenv').config();

const twilio = require('twilio')(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);
const template = "Hello {name}, test message";

(async () { 
  const records = [
    {number: "+1234567890", name: "Someone Someonesky"},
    {number: "+1234567891", name: "NotSomeone Someonesky"},
    ...
  ];

  const chunkSize = 99; // let's not overflow concurrency limit: 100
  for (let i = 0, j = records.length; i < j; i += chunkSize) {
    await Promise.all(
      records
        .slice(i, i + chunkSize)
        .map(
          record => {
            const {number, name} = record;

            // copying template to variable
            const body = template.toString();

            // replacing placeholder {name} in template 
            // with name value from object 
            body = body.replace(/\{name\}/g, name);

            return twillio.messages.create({
              to: number,
              from: process.env.TWILIO_NUMBER,
              body
            });
          }
        )
    );
  }
})();

file: .env

TWILIO_ACCOUNT_SID=some-sid
TWILIO_AUTH_TOKEN=some-token 
TWILIO_NUMBER=+3333333

Install dependencies:

npm i --save twilio
npm i --save dotenv

Run:

node broadcast.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM