我正在使用脚本,使用本教程中的Twilio示例,为Google工作表中的日期/时间行发送基于时间的SMS。 https://github.com/jmadden/twilio-sms-for-google-sheets/blob/master/README.md
我已经完成了本教程中的所有设置,并且可以正常工作,请整理一下。脚本不是在使用触发器从单元格在确切时间发送消息的脚本,而是在每次执行触发器时发送SMS,直到经过精确的时间为止。因此,如果触发器设置为5分钟,它将每5分钟发送一次SMS,而不是检查何时发送SMS。有人可以解决这个问题吗?
// Gets predefined properties for this script. See: File -> Project properties -> Script properties
var prop = PropertiesService.getScriptProperties();
// Returns a specific Google Sheet by URL.
var spreadSheet = Spreadsheetapp.openByUrl(prop.getProperty('spreadsheetUrl'));
// Defines how we want the date to be formatted for scheduling.
var dateFormat = prop.getProperty('DateFormat');
// Returns the specific sheet/tab inside a Google Sheed doc.
var sheet = spreadSheet.getSheets()[0];
// The Row where data starts. This skips the headers row.
var startRow = 2;
// Returns the number of rows with values in this sheet.
var numRows = sheet.getLastRow() - 1;
// Returns all the data to be processed in this sheet. i.e. to # and message body.
var data = sheet.getRange(startRow,1,numRows,4).getvalues();
// Whenever this function is called it will send an SMS using Twilio
// if all of the required parameters are passed into the function.
function sendSms(to,body) {
// URL used for sending request to Twilio's Messages API. Be sure to include your account SID
var messages_url = "https://api.twilio.com/2010-04-01/accounts/"+prop.getProperty('accOUNT_SID')+"/Messages.json";
// Parameters needed to send an SMS.
var payload = {
"To": "+"+to,"Body" : body,"From" : prop.getProperty('TWNUM')
};
// Contains the method of communicating with the API (POST) and the parameters needed to build a message.
var options = {
"method" : "post","payload" : payload
};
// Authorize your account to send this message.
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(prop.getProperty('accOUNT_SID')+":"+prop.getProperty('AUTH_TOKEN'))
};
UrlFetchApp.fetch(messages_url,options)
}
// This function loops through your Google Sheet and uses the sendSms() function to send messages.
function sendAll() {
// For loop through your Google Sheet's data.
for (i in data) {
var row = data[i];
// Returns the Google Sheet's timezone info as an object.
var when = Moment.moment.tz(data[i][3],dateFormat,spreadSheet.getSpreadsheetTimeZone());
var now = new Date();
// Compares the current time to the "When" time in the sheet.
// Sends SMS if "When" time is older or equal to the current time.
if (isnaN(when) || !when.isValid() || (when.toDate() >= now)){
// Try sending SMS.
try {
response_data = sendSms(row[0],row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i),3).setvalue(status);
}
}
}
// Runs the full script.
function runApp() {
sendAll();
}