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

请求指导修复Google Sheets脚本语法错误:unexpected token var(第65行)

修复Google Apps Script Webhook脚本的语法错误

主要问题及修复步骤

  • 对象定义语法错误:webhooks对象未闭合(缺少};),后续直接写var params导致语法解析失败,触发"unexpected token var"错误。
  • 对象访问方式错误:if(webhooks(channel))使用函数调用语法访问对象属性,正确写法应为webhooks[channel]。
  • 变量定义顺序错误:webhooks定义在使用之后,导致提前调用时变量未初始化。
  • 未定义变量冗余代码:代码中出现未定义的options变量调用,属于无效代码需删除。
  • 请求头类型不匹配:payload是JSON序列化字符串,请求头应改为application/json而非application/x-www-form-urlencoded。

修复后的完整代码

function sendMessage(message, channel) {
  // 提前定义webhooks对象,确保逻辑可访问
  var webhooks = {
    test: "Obtain a webhook for the channel you'd like and put it here."
  };

  // 检查指定频道的webhook是否存在
  if (webhooks[channel]) {
    var url = webhooks[channel];
  } else {
    Logger.log("Error Sending Message to Channel " + channel);
    return "NoStoredWebhookException";
  }
  
  var payload = JSON.stringify({content: message});

  // 修正请求参数的Content-Type
  var params = {
    headers: {"Content-Type": "application/json"},
    method: "POST",
    payload: payload,
    muteHttpExceptions: true
  };

  // 发送请求并记录响应内容
  var res = UrlFetchApp.fetch(url, params);
  Logger.log(res.getContentText());
}

额外提示

  • 需将webhooks对象中test对应的字符串替换为实际的Discord Webhook地址。
  • 如需新增频道配置,直接在webhooks对象中追加键值对即可,格式为频道标识: "对应webhook地址"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:50:29