javascript - 发送 twilio SMS 消息的 Google 表格脚本在手动运行时有效,但在时间触发时失败
问题描述
我正在尝试构建一个谷歌表格电子表格来发送短信提醒。在这个阶段,我仍然只是构建从谷歌表格发送短信的基础知识。我已经用他们的名字替换了一些字段,例如 API SID 和令牌,以及我的电话号码。我的代码如下:
//At the moment this seems to work when manually run, but not when triggered by time or whatever.
function sendSms(to, body) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/API_SID_GOES_HERE/Messages.json"; //This contains my Twilio API LIVE SID
var payload = {
"To": to,
"Body" : body,
"From" : "61123456789" //This is the twilio phone number
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("API_LIVE_TOKEN_GOES_HERE") //This contains my Twilio API LIVE Token
};
UrlFetchApp.fetch(messages_url, options);
}
function sendAll() {
var spreadsheet = SpreadsheetApp.openById("SPREADSHEET_ID_NUMBER") //This part is the ID number of the spreadsheet
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[2]); //This little feller sets an active sheet which it manipulates. Sheet count starts from [0]
var startRow = 2; //starts counting from row #2
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 2) //getRange(Integer row, Integer column, Integer numRows, Integer numColumns)
var data = dataRange.getValues(); //Gets just the values of the cells, not the formulas
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 4).setValue(status); //The number after (i), is the column where the setValue(Status) will land.
}
}
function myFunction() {
sendAll();
}
似乎如果我手动运行代码,它可以正常工作,发送短信,更新“状态”字段,一切都很好。但是,如果我为脚本设置触发器,无论是固定时间触发器还是每分钟触发器,脚本都会失败。谷歌应用程序脚本发送给我的失败摘要是:
https://api.twilio.com/2010-04-01/Accounts/MY_ACCOUNT_NUMBER/Messages.json的请求失败, 返回代码 400。截断的服务器响应:{"code": 21211, "message": "The 'To' number 不是有效的电话号码。", "more_info": " https://www.twilio.com/docs/errors/21211 ", "status": 400} (使用 muteHttpExceptions 选项检查完整响应)(第 19 行, 文件“代码”)
我不太明白为什么。我认为它与 var 电子表格和 var sheet 有关,但我真的不知道。
大部分代码都是从这篇twilio 博客文章中复制而来的。
解决方案
推荐阅读
- java - 当位置设置 OUTSIDE_CHART 和 XAxis 也不显示 OUTSIDE 时,YAxis 不显示
- angular - 具有非静态默认值的默认参数是否合法?
- c - 阻塞模式下的 ALSA 'snd_pcm_writei' 行为
- python - 为什么我会收到“TypeError:必须是 str,而不是 float”错误。我试图转换它
- javascript - 是否可以链接价值设定者?
- javascript - Vue.js 使用 v-for 单击时切换类
- javascript - 处理 SelectDialogBox 的 CONFIRM 事件的行为
- php - 注入问题 - 缺少父构造函数调用
- testflight - 如何解决 Apple TestFlight 中的“出现问题”错误
- python - 熊猫区分两个数据框