【问题标题】:Google Apps Script trigger - run whenever a new file is added to a folderGoogle Apps 脚本触发器 - 将新文件添加到文件夹时运行
【发布时间】:2021-01-26 13:01:01
【问题描述】:

每当 new 文件添加到特定文件夹时,我都想执行 google Apps 脚本。

目前我正在使用每 x 分钟运行一次的时钟触发器,但我只需要在将文件添加到文件夹时运行脚本。有没有办法做到这一点?

this 问题相同 - 现在已经快 3 岁了。问题下方的评论指出:

如果这是您所希望的,那没有触发因素。怎样 东西进入文件夹,你有什么控制权吗? – Jesse Scherer 2018 年 4 月 8 日 3:02

我想知道这条评论是否仍然有效,如果有效,那么是否有解决方法。

【问题讨论】:

  • Drive REST API supports push notifications 允许您跟踪事件,例如何时将新文件添加到 Google Drive 文件夹。不幸的是,由于多种原因,无法从 Apps 脚本访问此功能。但是它可以用另一种语言/平台创建一个中介服务,并让 Apps 脚本调用它。实施起来并不简单,但可行。
  • 非常感谢@TheAddonDepot 的建议

标签: google-apps-script triggers google-drive-api


【解决方案1】:

问题:

很遗憾,您阅读的评论仍然正确Here 是所有可用触发器的列表,new file added to a folder 的触发器不是其中之一。

解决方法/说明:

我可以为您提供一种解决方法,开发人员在构建附加组件时通常会使用该解决方法。您可以利用 PropertiesService 类。逻辑很简单。

  1. 您将在脚本范围内存储键值对:

在您的情况下,键将是文件夹 id,值将是该文件夹下的文件数。

  1. 您将设置一个时间驱动触发器,例如每分钟执行一次mainFunction

  2. 脚本将计算所选文件夹中的当前文件数。负责的函数是countFiles

  3. checkProperty 函数负责检查此文件夹下的当前文件数是否与旧文件数匹配。如果匹配,则表示没有添加文件,则checkProperty 返回false,否则返回true 并更新当前文件夹ID 的属性,因此当脚本在1 分钟后运行时,它将与新鲜价值。

  4. 如果checkProperty 返回true,则执行所需的代码。

代码sn-p:

mainFunction 设置时间驱动触发器。如果folderID 下的文件数发生了变化,则无论您在if(runCode) 语句的括号内放置的代码都将被执行。

function mainFunction(){
  const folderID = 'folderID'; //provide here the ID of the folder
  const newCounter = countFiles(folderID);
  const runCode = checkProperty(folderID, newCounter);
  
  if(runCode){
   // here execute your main code
   // 
    console.log("I am executed!");
   //
  }
}

这里是需要在同一个项目中的辅助函数(你可以将它们放在同一个脚本或不同的脚本中,但在同一个“脚本编辑器”中)。

function countFiles(folderID) {
  const theFolder = DriveApp.getFolderById(folderID);
  const files = theFolder.getFiles();
  let count = 0;
  while (files.hasNext()) {
   let file = files.next();
   count++;
   };
  return count;
}


function checkProperty(folderID, newC){
  const scriptProperties = PropertiesService.getScriptProperties();
  const oldCounter = scriptProperties.getProperty(folderID);
  const newCounter = newC.toString();
  if(oldCounter){
    if(oldCounter==newCounter){
      return false;
    }
    else{
      scriptProperties.setProperty(folderID, newCounter);  
      return true;
    }
  }
  else{
     scriptProperties.setProperty(folderID, newCounter);  
     return true;
  }
}

【讨论】:

  • 很好的答案 - 如果可以的话,我会给超过 1 票!
  • @Andy 已经感谢您的支持。很高兴这个答案对你有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 2018-09-08
相关资源
最近更新 更多