首页 > 解决方案 > 发送 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 博客文章中复制而来的。

标签: javascriptgoogle-apps-scriptgoogle-sheetstwilio

解决方案


我想通了,这是非常明显的事情。

在设置触发器时,我完全忽略了定义我希望它触发的功能的需要。默认情况下,它只是在运行函数 sendSMS,此时还没有任何数据要发送。

所以我的手动运行正在运行名为 myFunction 的函数,但触发的运行正在运行 sendSMS。

在此处输入图像描述

一旦我意识到这一点并对其进行了更改,它就可以正常工作。

感谢所有为他们提供帮助的人,特别是 Darpan 和我一起追逐红鲱鱼。


推荐阅读