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

Twilio API & Exponential Backoff when sending bulk SMS with Node.js

我正在开发一个群发 SMS 应用程序,它可以在紧急情况下向一组人发送一条消息。我查看了 Twilio Docs 并实施了他们的代码,此时我从 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 包 exponential-backoff,但没有任何运气。

需要说明的是,这不是“指数退避”,但它应该适用于大约 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);

祝你好运!