如何遍历 mySQL 数据并将其传递给 Twilio Notify Passthrough API?

问题描述

我试图通过 Twilio Notify 的 passthrough API 使用单个 API 调用发送不到 10,000 条短信。

我已成功连接到包含数据的 MysqL 数据库,但我现在需要将其传递给 Passthrough API 才能成功发送消息。

这是我到目前为止所得到的。我用只读权限的虚拟数据库交换了我的实际数据库,因此凭据是正确的。如果您愿意,请随时查询数据库

<div></div>d

Twilio 提供了一个关于如何在 Python 中执行此操作的示例,但未在 Node.js 中执行此操作。这是他们提供的示例:

var MysqL = require('MysqL');
require('dotenv').load()

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const notifyServiceSid = process.env.NOTIFY_SERVICE_SID;

const client = require('twilio')(accountSid,authToken);

var con = MysqL.createConnection({
  host: "asa.haus",user: "uhrjvef2i9dnc",password: "StackOverflow",database: "dbf2jpy2zqwjn4"
});

var recipientList = []

con.connect(function(err) {
  if (err) throw err;
   con.query("SELECT CellPhone FROM test_notify",function (err,result,fields) {
    if (err) throw err;
    // console.log(result);
    Object.keys(result).forEach(function(key) {
        var row = result[key];
        console.log(row.CellPhone)
        recipientList.push(row.CellPhone)
    })
  });
});

console.log(recipientList)

client.notify.services(notifyServiceSid)
  .notifications.create({
    toBinding: [
      JSON.stringify({
        binding_type: 'sms',address: recipientList,}),],body: 'Hello'
  })
  .then(notification => console.log(notification.sid))
  .catch(error => console.log(error));

感谢您的任何帮助。对不起,如果我的问题有点不清楚。显然我有点业余。

解决方法

这里是 Twilio 开发者布道者。

我认为,根据您的代码,您的 recipientList 是一组电话号码。使用 passthrough API 时,您实际上必须将每个电话号码转换为包含 binding_typeaddress 的 JSON 字符串化对象。所以你可以像这样创建你的绑定:

const bindings = recipientList.map(number => {
  return JSON.stringify({ binding_type: 'sms',address: number });
});

然后您可以发送如下消息:

client.notify.services(notifyServiceSid)
  .notifications.create({
    toBinding: bindings,body: "hello"
  })
  .then(notification => console.log(notification.sid))
  .catch(error => console.log(error));

您可以阅读有关 bulk SMS messaging in Node.js in my blog post here 的更多信息。