javascript - Twilio - 如何针对每个电话号码发送具有不同正文的批量短信?

标签 javascript node.js express twilio

我平均有 100 - 1500 个要向其发送短信的电话号码。我想在正文中包含与每个电话号码关联的人名。我如何使用 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));

最佳答案

有很多方法可以做到这一点。

一个例子:

文件: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
            });
          }
        )
    );
  }
})();

文件:.env

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

安装依赖项:

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

运行:

node broadcast.js

关于javascript - Twilio - 如何针对每个电话号码发送具有不同正文的批量短信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368249/

相关文章:

javascript - 如何在react中删除数组中的元素?

node.js - 如何在 jade 模板 ahrefs 中嵌入收缩路由 url() 调用?

node.js - 如何从 Flutter 发出纯文本 http(而非 https)请求

mysql - 插入错误 :connect ECONNREFUSED

node.js - 使用 res.setheader 在 cookie nodejs 中使用 max-age

javascript - 从用户浏览器历史记录中隐藏网站

javascript - 了解用户正在 iframe 中浏览哪个页面

javascript - 尝试将用户服务的结果设置到用户组件中

ruby-on-rails - 检测点击了哪个反向链接

angularjs - 使用 $http 将数据从 angularJS 发布到 Express