使用 Twilio 发送数千条短信

Send thousands of SMS with Twilio

我想用 Twilio 发送大约 50,000 条短信,我只是想知道如果我循环遍历这种大小的 phone 数字数组,我的请求是否会崩溃。事实上,Twilio 只允许每个请求发送 1 条消息,所以我必须制作 50,000 条消息。

是否可以这样做,还是我必须找到其他方法? 50,000似乎太多了,但我不知道我能做多少请求。

phoneNumbers.forEach(function(phNb)
{
    client.messages.create({
        body: msgCt,
        to: phNb,
        from: ourPhone
    })
    .then((msg) => {
        console.log(msg.sid);
    });
})

提前致谢

由于非阻塞的 forEach 正文调用,您可以异步发送请求,我想这对客户端来说是最快的。但问题是:Twilio 是否允许来自单一来源的此类负载?它需要进行测试......如果没有,你应该建立某种请求队列,例如基于承诺,类似于

function sendSync(index = 0) {
  if(index === phoneNumbers.length) {
    return;
  }
  client.messages.create({
      body: msgCt,
      to: phoneNumbers[index],
      from: ourPhone
  })
  .then(function(msg) {
      console.log(msg.sid);
      sendSync(index + 1);
  })
  .catch(function(err) {
      console.log(err);
  });
}

sendSync();

或者如果你喜欢async/await –

async function sendSync() {
  for (let phNb of phoneNumbers) {
    try {
      let msg = await client.messages.create({
        body: msgCt,
        to: phNb,
        from: ourPhone
      });
      console.log(msg);
    } catch(err) {
      console.log(err);
    } 
  })
}

sendSync();

这里有两个因素。

  • 你需要考虑Twilio Api usage Limits.
  • 执行 50.000 个并行 http 请求(实际上是您的代码执行的)不是一个好主意:您将遇到内存问题。

Twilio 短信根据源和目标限制更改。

你有两个解决方案:

顺序执行 50k 个 http 请求

    phoneNumbers.forEach(async function(phNb){
      try {
        let m = await client.messages.create({
          body: msgCt,
          to: phNb,
          from: ourPhone
        })
        console.log(a)
      } catch(e) {
        console.log(e)
      } 
    })

以并发级别

并发执行50k个http请求

使用很棒的蓝鸟糖功能,这很容易做到。不管怎样,twilio 包使用原生的 promise。为此,您可以使用带有 mapLimit 方法的异步模块

这里是 Twilio 开发人员布道者。

API 限制

首先,简要说明一下我们的限制。对于单个数字,Twilio 有每秒发送一条消息的限制。您可以通过添加更多号码来增加它,因此 10 个号码每秒可以发送 10 条消息。 A short code can send 100 messages per second..

We also recommend that you don't send more than 200 messages on any one long code per day.

无论哪种方式,我都建议使用 messaging service 发送这样的消息。

最后,您还被限制为 100 个并发 API 请求。很高兴在这里看到其他答案谈论按顺序而不是异步发出请求,因为这会耗尽服务器上的内存,并开始发现请求被 Twilio 拒绝。

直通 API

我们现在有一个 API 允许您通过单个 API 调用发送多条消息。它被称为 passthrough API, as it lets you pass many numbers through to the Notify service。您需要将您的号码转换为 "bindings" 并通过通知服务发送它们,该服务还使用消息服务进行号码池化。

The code looks a bit like this:

const Twilio = require('twilio');    
const client = new Twilio(accountSid, authToken);
const service = client.notify.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

service.notifications
  .create({
    toBinding: [
      JSON.stringify({
        binding_type: 'sms',
        address: '+15555555555',
      }),
      JSON.stringify({
        binding_type: 'facebook-messenger',
        address: '123456789123',
      }),
    ],
    body: 'Hello Bob',
  })
  .then(notification => {
    console.log(notification);
  })
  .catch(error => {
    console.log(error);
  })

在您的情况下,唯一的缺点是每条消息都需要相同,并且请求的大小需要小于 1 兆字节。我们发现这通常意味着大约 10,000 个号码,因此您可能需要将列表分成 5 API 个电话。

如果有帮助请告诉我。