You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化Google Form脚本:快速获取最新提交响应

优化Google Form提交脚本以解决Discord Webhook延迟问题

核心问题分析

原脚本每次执行时调用FormApp.getActiveForm().getResponses()会拉取所有15万条历史响应,这是导致60-80秒延迟的根本原因——加载巨量数据需要大量时间。

优化方案:利用表单提交触发器的事件对象

Google Form的onSubmit触发器会自动传入一个表单提交事件对象,其中直接包含当前提交的最新响应,完全不需要遍历历史数据。

优化后的代码

function onSubmit(e) {
  // 直接从事件对象获取最新提交的响应,无需拉取所有历史数据
  const itemResponses = e.response.getItemResponses();
  
  // 提取关键数据:用户选择的通知类型、平台标识项的标题和内容
  const notifyOption = itemResponses[2].getResponse()[0];
  const platformItemTitle = itemResponses[1].getItem().getTitle();
  const platformId = itemResponses[1].getResponse();
  
  // 只在用户选择指定通知选项时执行后续逻辑
  if (notifyOption !== 'Notify the community manager of a livestream report in real time?') {
    return;
  }

  // 定义平台URL模板,避免重复的if判断
  const platformTemplates = {
    'Page/Group Identification': `https://www.facebook.com/${platformId}`,
    'Channel Identification': `https://www.youtube.com/channel/${platformId}`,
    'Account Username': `https://www.tiktok.com/@${platformId}`
  };

  // 匹配到对应平台模板则发送Webhook
  const targetUrl = platformTemplates[platformItemTitle];
  if (targetUrl) {
    UrlFetchApp.fetch('https://discord.com/api/webhooks/824374930422497331/X', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      payload: JSON.stringify({content: `<${targetUrl}>`})
    });
  }
}

优化点说明

  • 避免拉取历史数据:通过e.response直接获取当前提交的响应,性能提升显著,响应时间会回到正常水平。
  • 减少冗余代码:用对象模板替代重复的if判断,代码更简洁易维护。
  • 提前退出逻辑:如果用户没选择指定通知选项,直接终止函数,减少不必要的执行。

注意事项

确保脚本是通过表单提交触发器触发的(无论是简单触发还是安装型触发器),事件对象e才会被正确传入。如果之前是手动运行脚本,需要配置对应的触发器(在Google Apps Script编辑器的「编辑」→「当前项目的触发器」中添加)。

内容的提问来源于stack exchange,提问作者user19120926

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:11:05