javascript - 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
推荐阅读
- c# - winforms刷新多个面板
- f# - F# 函数签名的字符串表示
- c++ - 有 C++ 标准库 ifdef 或 ifndef 预处理器指令吗?
- entity-framework - 如何用 linq 排除孙子
- node.js - Angular,webpack:将项目构建到输出路径中
- php - 我的地图中有 x 和 y 坐标。x 的坐标是不同的标记并且有一个斜角。同样在 y 中。我怎样才能在下面的代码中做到这一点?
- firebase - 使用 Firebase Auth 对 IoT 设备进行身份验证
- reactjs - React Native - 选项卡导航器问题
- autocomplete - Monaco Editor 双倍空格产生句号
- excel - OnComm 事件不触发