Google Forms/Sheets - 如何使用有界脚本强制复制的表单文件为其 onFormSubmit 事件添加触发器?

Google Forms/Sheets - How to force a copied form file with a bounded script to add a trigger for its onFormSubmit event?

基本上,我希望从一种表单提交的内容创建另一种表单的副本。

我已经成功复制了表单,并且我已经验证它确实复制了绑定的脚本。

  var templateFile = DriveApp.getFileById("1FEVxX2-_pdeg8vN4jaUGhYbTgqVImQqdcPp5jSXkDGM");
  var targetFolder = DriveApp.getFolderById("1XQfmJH0_CYJP9luXKQTn2JAyLsW5xeV0");
  
  var copiedFile = templateFile.makeCopy("Debriefing Teste " + classID, targetFolder);

但是,不会复制触发器。如何以编程方式为刚刚以编程方式创建的表单文件设置触发器?

编辑:我尝试在同一个脚本中添加触发器,遵循 Jescanellas 的提示。

// This is on the same function:

  var formID = copiedFile.getId();
  
  var newForm = FormApp.openById(formID);
  
  newForm.classID = classID;

ScriptApp.newTrigger("onDebriefingSubmit")
.forForm(formID)
.onFormSubmit()
.create(); `

// Then, on the same script, a dummy code just to test it out:

function onDebriefingSubmit(e){
  var ss = SpreadsheetApp.openById('165k3ieREOPZh9JV7UstidW0z8RScB3GtSjxG_Eb7ttk');
  var sheet = ss.getSheetByName('Respostas');
  
  sheet.getRange(1,1).setValue("teste");
} `

您可以使用 FormTriggerBuilder,但请注意,这将在您的项目中创建一个新触发器,该触发器将引用下一个表单,这是一个不同的项目。更简洁:

  • 表单 A 将为表单 B 生成触发器,但它会在表单 A 的项目中(仍然,它会起作用,因为所有表单都来自同一用户)。

这应该在您的表单 A 的脚本中,在您的其余代码之后,我猜它在 onSubmit 函数中:

var form = copiedFile.getId();
ScriptApp.newTrigger('myFunction')
    .forForm(form)
    .onFormSubmit()
    .create();

我已经解决了我的问题。

这些是重要的部分:

  • 显然,一个脚本无法为另一个最近创建的脚本中的函数设置触发器。它可以为包含的库中的脚本设置触发器,但这对我们没有帮助。
  • 但是,您可以在同一脚本内为另一个文档(例如另一个表单)设置触发器。感谢@Jescanellas 的提示。每当发送该表单时,它都会触发母脚本中的函数。您必须设置某种形式的垃圾收集来删除触发器,因为限制相当低。
  • 这是个大问题:installed triggers are disabled when created from another trigger function in V8。这意味着您必须将脚本的运行时更改为 Rhino。