I am trying to build a google sheets spreadsheet to send SMS reminders. At this stage, I'm still just building the basics of sending SMS from google sheets. I have replaced some fields with their names, eg the API SID and token, and my phone number. My code is below:
//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();
}
It seems that if I run the code manually, it works fine, sends an SMS, updates the 'status' field and all is well. However, if I set a trigger for the script, be it a fixed time trigger or an every minute trigger, the script fails. The Summary of Failures that google apps script sends me is:
Request failed for https://api.twilio.com/2010-04-01/Accounts/MY_ACCOUNT_NUMBER/Messages.json returned code 400. Truncated server response: {"code": 21211, "message": "The 'To' number is not a valid phone number.", "more_info": "https://www.twilio.com/docs/errors/21211", "status": 400} (use muteHttpExceptions option to examine full response) (line 19, file "Code")
I can't quite figure out why. I think it has something to do with var spreadsheet and var sheet, but I really don't know.
Most of the code has been copied from this twilio blog post.