使用 Node 发送批量短信时的 Twilio API 和指数退避.js



我正在开发一个批量短信应用程序,该应用程序将在紧急情况下向一群人发送一条消息。我已经查看了TwilioDocs并实现了它们的代码,这时我从API得到了一个429错误。所以我添加了指数后退代码来防止这种情况,但当我运行脚本时,它只发送到数组中列出的第二个数字。

const accountSid = '[ACCOUNT SID]';
const authToken = '[AUTH TOKEN]';
const client = require('twilio')(accountSid, authToken);
var numbersToMessage = ["+1800XXXXXXX", "+1888XXXXXXX"]
numbersToMessage.forEach(function(number){
var message = client.messages.create({
body: 'This is test #2 from August 21, 2020.',
from: '[TWILIO SENDER NUMBER]',
statusCallback: '[PIPEDREAM API URL]',
to: number
})
.then(message => console.log(message.status))
return((err) => {
// assumes that the error is "request made too soon"
backoffTime *= 2;
i--;
console.log(err);
return delay(backoffTime);
});
done();
});

指数后退对我来说是全新的,所以我相当确定这就是问题所在,但这是我所了解的。我也尝试过使用npm包指数后退,但没有任何运气。

要明确的是,这不是"指数后退";但它应该适用于大约100个数字。

替换为您的Twilio凭据,将您的数字添加到阵列中,替换PIPEDREAM_API_URL。您的所有100条消息应该在大约30秒内在Twilio排队。

Twilio的响应message.sid表示消息已添加到发送队列中,而不是实际发送了消息。

const accountSid = 'AC...';
const authToken = '4f...';
const client = require('twilio')(accountSid, authToken);
const TWILIO_SENDER_NUMBER = '+1...';
const TEXT_TO_SEND = 'This is test #2 from August 21, 2020.';
const PIPEDREAM_API_URL = '...';
// about 100 numbers
let numbersToMessage = [
"+1...",
"+1...",
"+1...",
// "+1...",
];
function sendAllMessagesWithTwilio(data) {
// stop condition, nothing left in the array of numbers
if (data.length === 0) {
console.log('............... DONE');
return;
}
// take the first number from the array of numbers
let _number = data.shift();
console.log(_number);
client.messages
.create({
to: _number,
from: TWILIO_SENDER_NUMBER,
body: TEXT_TO_SEND,
statusCallback: PIPEDREAM_API_URL
})
.then((message) => {
// after Twilio responds, send the next message
console.log(`${message.sid}`);
// recursive call of function, pass the remaining numbers as argument
// use setTimeout() to slow down, 300 milliseconds between requests
setTimeout(sendAllMessagesWithTwilio.bind(null, data), 300);
})
.catch((err) => {
// if an error is sent back from Twilio
console.error(err);
});
}
// first call of recursive function
// takes the initial array of numbers as argument
console.log('BEGIN ...............')
sendAllMessagesWithTwilio(numbersToMessage);

祝你好运

相关内容

  • 没有找到相关文章

最新更新