2

我正在开发一个批量 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 包指数退避,但没有任何运气。

4

1 回答 1

0

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

祝你好运!
于 2020-08-21T22:09:49.227 回答