如何为需要向其发送参数的功能设置时间驱动(时钟)触发器? [英] How to set a time-driven (clock) trigger for a function that needs parameters sent to it?

查看:54
本文介绍了如何为需要向其发送参数的功能设置时间驱动(时钟)触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用时间驱动(时钟)触发器运行函数.我的问题是,该函数需要将变量作为参数发送给它.通常,如果我不使用触发器,我会像这样直接发送它.

I'm trying to have a function run with a time-driven (clock) trigger. My issue is, the function needs variables sent to it as parameters. Normally if I'm not using a trigger I'll just send it directly like this.

<script>
    function runFunction(){
    google.script.run.myFunction(x,y,z);
    }
</script>

在服务器端,我将轻松调用它们.

And on the server side, I'll call them easily.

function myFunction(x,y,z){
var a = x;
var b = y;
var c = z;
Logger.log(a+b+c);
}

但是当我使用时间驱动的(时钟)触发器运行该函数时,如何将 x,y,z 插入该函数.

But when I'm using a time-driven (clock) trigger to run the function how can I get x,y,z into the function.

我四处搜寻,发现了一种从触发函数的参数中创建 scriptProperties 的方法.

I searched around and saw one method of creating scriptProperties out of the parameters in the trigger function like this.

已编辑.这是实际的代码.

客户端.

<script>
    function sendCall() {
    
      var testNumber = document.getElementById('numberCall').value;
      var testGroup = document.getElementById('groupsCall').value;
      var testtime = document.getElementById('scheduleCall').value;
      var now = document.getElementsByName('sendTimeCall')[0].checked;
      
      var number;
      if(testNumber == ''){
      number = null;
      }else{
      number = testNumber;
      }
      
      var group;
      if(testGroup == ""){
      group = null;
      }else{
      group = testGroup;
      }
      
        var time;
      if(testtime == ''){
      time = null;
      }else{
      time = testtime;
      }
    
      var file = document.getElementsByName('audio')[0].files[0];
      
      var name = file.name;
    
      var reader = new FileReader(); 
      reader.onload = function (e) {   
      var content = reader.result;
    
     google.script.run.withSuccessHandler(success2).triggerCall(group, number, content, time, now, name);
     return false;
      }
          reader.readAsDataURL(file); 
        }
</script>

服务器端-触发功能.

function triggerCall(group, number, content, time, now, name){

var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({
  'GROUP_CALL': group,
  'AUDIO': content,
  'NUMBER_CALL': number,
  'FILE_NAME': name
});

var status;
if(now){
status = 'Call Sent';
}else{
status = 'Call Scheduled';
}

if(now){
return makeCall(status);
}else{
// Set here the date you want to schedule the one-time trigger
var rawdate = time;
var today_D = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));
var scheduled_D = new Date(rawdate);
var time_af = Math.abs(scheduled_D - today_D) / 36e5;

ScriptApp.newTrigger("makeCall")
.timeBased()
.after(time_af * 60 *60 * 1000)
.create();
}
return status;
}

服务器端-这是实际起作用的功能.

function makeCall(status) {

var scriptProperties = PropertiesService.getScriptProperties();
var blob = scriptProperties.getProperty('AUDIO');
var number = scriptProperties.getProperty('NUMBER_CALL');
var group = scriptProperties.getProperty('GROUP_CALL');
var name = scriptProperties.getProperty('FILE_NAME');

var fullNumber;
if(group){
var ss = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxx');
var sheet = ss.getSheetByName(group)
var length = sheet.getLastRow();
var values = sheet.getRange(1, 1, length).getValues();
fullNumber = values.flat();

}else{

  var num = number;
  var prefix = '+1';
  var removeDashes = num.replace(/-/g,"");
  var format = prefix + removeDashes;
  var comma = format.replace(/ /g, ' +1');
  fullNumber = comma.split(' ')
}
  
   //upload file to drive
  var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxx');  
  var blob = blob.split(",");
  var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'audio/mpeg', name);
  var file = folder.createFile(blob); 
     
  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  
  var id = file.getId();

for (var i = 0; i < fullNumber.length; i++){

    //the url with HTTP request to create a call and parameters
  var callsUrl = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxxxxxx/Calls.json";
   
  var payload = {
    "To": fullNumber[i],
    "From" : "+177777777",
    "Twiml" : "<Response><Play>https://docs.google.com/uc?export=play&amp;id=" + id + "</Play></Response>",
  };
  
  var options = {
    "method" : "post",
    "payload" : payload
  };
  
  options.headers = {    
    "Authorization" : "Basic " + Utilities.base64Encode("xxxxxxxxxxx:xxxxxxxx")
  };
  UrlFetchApp.fetch(callsUrl, options);
  }  
  scriptProperties.deleteProperty('AUDIO');
  scriptProperties.deleteProperty('NUMBER_CALL');
  scriptProperties.deleteProperty('GROUP_CALL');
  scriptProperties.deleteProperty('FILE_NAME');
  return status;
}  

问题是,当我在没有文件输入的情况下运行上述代码时,它起作用了,但是当我以上述方式运行时,该函数不起作用了.我在进行拍摄时遇到了一些麻烦,我认为这与通过properties方法将文件作为数据URL传输有关.VALUE可以容纳多长时间?

The problem is when I run the above code without the file input it works, But when I run it as above the function doesn't work. I did some trouble shooting and I think it has to do with transferring the file as a Data URL via the properties method. Is there a limit to how long of a string the VALUE can be?

简而言之,这是我的问题的两点.

in a nut shell these are the 2 points of my question.

  1. 任何其他有关如何将参数发送到触发函数的想法
  2. 如何使用 PropertiesService .

推荐答案

我想提出以下修改.

  • 我认为您出现问题的原因可能是由于PropertiesService的最大数据大小所致.在当前阶段,似乎属性总存储量"已被确定.是"500kB/物业商店".我以为在这种情况下,当您上传文件时,文件大小可能会超过文件大小.
  • 为了消除您的问题,如何将 content 创建为临时文件并将文件ID放入PropertiesService中?
  • I think that the reason of your issue might be due to the maximum data size for PropertiesService. In the current stage, it seems that "Properties total storage" is "500kB / property store". I thought that in this case, when you upload a file, the file size might be over than it.
  • In order to remove your issue, how about creating content as a temporal file and put the file ID to the PropertiesService?

当以上几点反映到您的脚本中时,它如下所示.

When above points are reflected to your script, it becomes as follows.

在这种模式下, content 被保存为临时文件,并在 makeCall()函数中使用.

In this pattern, content is saved as a temporal file and that is used in the function of makeCall().

function triggerCall(group, number, content, time, now, name){
  var scriptProperties = PropertiesService.getScriptProperties();
  var tempFile = DriveApp.createFile("tempFile.txt", content, MimeType.PLAIN_TEXT);  // Added
  scriptProperties.setProperties({'GROUP_CALL': group,'AUDIO': tempFile.getId(),'NUMBER_CALL': number,'FILE_NAME': name});  // Modified
  var status;
  if(now){
    status = 'Call Sent';
  }else{
    status = 'Call Scheduled';
  }
  if(now){
    return makeCall(status);
  }else{
    var rawdate = time;
    var today_D = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));
    var scheduled_D = new Date(rawdate);
    var time_af = Math.abs(scheduled_D - today_D) / 36e5;
    ScriptApp.newTrigger("makeCall").timeBased().after(time_af * 60 *60 * 1000).create();
  }
  return status;
}

makeCall()

function makeCall(status) {
  var scriptProperties = PropertiesService.getScriptProperties();
  var tempfileId = scriptProperties.getProperty('AUDIO');  // Modified
  var number = scriptProperties.getProperty('NUMBER_CALL');
  var group = scriptProperties.getProperty('GROUP_CALL');
  var name = scriptProperties.getProperty('FILE_NAME');
  var fullNumber;
  if(group){
    var ss = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxx');
    var sheet = ss.getSheetByName(group)
    var length = sheet.getLastRow();
    var values = sheet.getRange(1, 1, length).getValues();
    fullNumber = values.flat();
  }else{
    var num = number;
    var prefix = '+1';
    var removeDashes = num.replace(/-/g,"");
    var format = prefix + removeDashes;
    var comma = format.replace(/ /g, ' +1');
    fullNumber = comma.split(' ')
  }
  var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxx');
  
  var tempFile = DriveApp.getFileById(tempfileId);  // Added
  var text = tempFile.getBlob().getDataAsString();  // Added
  tempFile.setTrashed(true);  // Added
  var blob = text.split(",");  // Modified
  var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'audio/mpeg', name);
  var file = folder.createFile(blob);

  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  var id = file.getId();
  for (var i = 0; i < fullNumber.length; i++){
    var callsUrl = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxxxxxx/Calls.json";
    var payload = {"To": fullNumber[i],"From" : "+177777777","Twiml" : "<Response><Play>https://docs.google.com/uc?export=play&amp;id=" + id + "</Play></Response>"};
    var options = {"method" : "post","payload" : payload};
    options.headers = {"Authorization" : "Basic " + Utilities.base64Encode("xxxxxxxxxxx:xxxxxxxx")};
    UrlFetchApp.fetch(callsUrl, options);
  }  
  scriptProperties.deleteProperty('AUDIO');
  scriptProperties.deleteProperty('NUMBER_CALL');
  scriptProperties.deleteProperty('GROUP_CALL');
  scriptProperties.deleteProperty('FILE_NAME');
  return status;
}

模式2:

在此模式中,内容作为解码后的数据保存到文件中,并在 makeCall()函数中使用.

Pattern 2:

In this pattern, content is saved to a file as the decoded data and that is used in the function of makeCall().

function triggerCall(group, number, content, time, now, name){
  var scriptProperties = PropertiesService.getScriptProperties();

  var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxx');  // Added
  var blob = content.split(",");  // Added
  var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'audio/mpeg', name);  // Added
  var file = folder.createFile(blob);  // Added
  scriptProperties.setProperties({'GROUP_CALL': group,'AUDIO': file.getId(),'NUMBER_CALL': number,'FILE_NAME': name});  // Modified
  
  var status;
  if(now){
    status = 'Call Sent';
  }else{
    status = 'Call Scheduled';
  }
  if(now){
    return makeCall(status);
  }else{
    var rawdate = time;
    var today_D = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));
    var scheduled_D = new Date(rawdate);
    var time_af = Math.abs(scheduled_D - today_D) / 36e5;
    ScriptApp.newTrigger("makeCall").timeBased().after(time_af * 60 *60 * 1000).create();
  }
  return status;
}

makeCall()

function makeCall(status) {
  var scriptProperties = PropertiesService.getScriptProperties();
  var fileId = scriptProperties.getProperty('AUDIO');  // Modified
  var number = scriptProperties.getProperty('NUMBER_CALL');
  var group = scriptProperties.getProperty('GROUP_CALL');
  var name = scriptProperties.getProperty('FILE_NAME');
  var fullNumber;
  if(group){
    var ss = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxx');
    var sheet = ss.getSheetByName(group)
    var length = sheet.getLastRow();
    var values = sheet.getRange(1, 1, length).getValues();
    fullNumber = values.flat();
  }else{
    var num = number;
    var prefix = '+1';
    var removeDashes = num.replace(/-/g,"");
    var format = prefix + removeDashes;
    var comma = format.replace(/ /g, ' +1');
    fullNumber = comma.split(' ')
  }

  var file = DriveApp.getFileById(fileId);  // Modified

  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  var id = file.getId();
  for (var i = 0; i < fullNumber.length; i++){
    var callsUrl = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxxxxxx/Calls.json";
    var payload = {"To": fullNumber[i],"From" : "+177777777","Twiml" : "<Response><Play>https://docs.google.com/uc?export=play&amp;id=" + id + "</Play></Response>"};
    var options = {"method" : "post","payload" : payload};
    options.headers = {"Authorization" : "Basic " + Utilities.base64Encode("xxxxxxxxxxx:xxxxxxxx")};
    UrlFetchApp.fetch(callsUrl, options);
  }  
  scriptProperties.deleteProperty('AUDIO');
  scriptProperties.deleteProperty('NUMBER_CALL');
  scriptProperties.deleteProperty('GROUP_CALL');
  scriptProperties.deleteProperty('FILE_NAME');
  return status;
}

注意:

  • 在此修改后的脚本中,上传文件时, content 被保存为临时文件,并且文件ID被放入PropertiesService.运行 makeCall 时,将通过文件ID检索 content ,并将其转换为blob并将其保存为文件.并且临时文件被删除.这样,可以清除PropertiesService的限制.
  • 但是,在当前阶段,Google Apps脚本的最大Blob大小为50 MB(52,428,800字节).因此,当上传的文件大小超过50 MB时,会发生错误.在这种情况下,文件将转换为base64数据.因此,最大大小是base64数据的大小.请注意这一点.
  • Note:

    • In this modified script, when a file is uploaded, content is saved as a temporal file and the file ID is put to the PropertiesService. When makeCall is run, content is retrieved by the file ID and convert to the blob and saved it as a file. And the temporal file is removed. By this, the limitation of PropertiesService can be cleared.
    • But, in the current stage, the maximum blob size of Google Apps Script is 50 MB (52,428,800 bytes). So when the uploaded file size is over 50 MB, an error occurs. In this case, the file is converted to the base64 data. So, the maximum size is the size of base64 data. Please be careful this.
    • 这篇关于如何为需要向其发送参数的功能设置时间驱动(时钟)触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆