我无法让一个函数调用另一个函数 - 使用 Apps 脚本在 Google Sheet 上发送 Discord 消息

问题描述 投票:0回答:1

我正在尝试创建一个与 Discord 配合使用的 Google 表格。 在 Google Sheet 上,您可以使用“Apps Script”添加一些脚本。

项目如下: 这是一个社交媒体帖子规划器,人们可以在这里写下他们的想法。

在 C 列中,有草稿文本。 当草稿准备好由经理审核时,作者可以选中 D 列中的框,它将在频道中发送一条 Discord 消息(通过 Discord Webhook),告知经理有新帖子可供审核.

该脚本有 2 个功能:

  1. onEdit(e);每次单元格是否被编辑都会检查
  2. postToDiscord();发送消息的

如果:

  1. C 列中的单元格为空,并且勾选了该框(例如错误地),将出现一个弹出窗口并显示“空草稿”exemple of onEdit working fine if cell is empty
  2. 单元格不为空,它应该调用一个函数:postToDiscord(),并执行该函数test to see if there is some text

当我手动执行 postToDiscord 函数时,它会执行以下操作: enter image description here

问题是,单独来看,每个功能都可以工作,但是当我将它们混合在一起时,它没有任何作用。

function onEdit(e) {
  var range = e.range,
      col = range.getColumn(),
      row = range.getRow(),
      edited_value = e.value,
      ss = e.range.getSheet();
 
  //check if the box isn't ticked by accident to avoid spam
  if (col == 4 && edited_value == "TRUE" && ss.getRange("C"+row).getValue() == "") {
    Browser.msgBox("Empty draft!");
  }
  //execute the postToDiscord function if the draft cell is not empty
  else if (col == 4 && edited_value == "TRUE" && ss.getRange("C"+row).getValue() !== "") {     
    Browser.msgBox("The text is:" +ss.getRange("C"+row).getValue());
    postToDiscord();
  }
  else{
  }
}

//the function that manage discord messages
function postToDiscord() {
  const url = "https://discord.com/api/webhooks/[url]";
      
  const message = {
    content: "hi there"
    }

  const options = {
    'method': 'post',
    'payload': message
    }
    
  const res = UrlFetchApp.fetch(url, options);
}

你们当中有超级英雄吗?

我愿意在 onEdit(e) 条件良好时让 postToDiscord 发挥作用。

我在其他帖子上尝试过,但没有成功。

我可能误解了他们,因为我实际上以前从未编码过,我只是想学习一些东西来娱乐并为我的公司创造

对于错误提前表示歉意!

祝你玩得开心!

javascript google-sheets google-apps-script discord
1个回答
0
投票

尝试使用可安装的触发器:

function onMyEdit(e) {
  const sh = e.range.getSheet();
  let v = e.range.offset(0, -1).getValue();
  if (sh.getName() == "Your Sheet Name" && e.range.columnStart == 4 && e.value == "TRUE") {
    if (v == "") {
      e.source.toast("Empty draft!");
    } else {
      e.source.toast("The text is:" + v);
      postToDiscord();
    }
  }
}


function createInstallableTrigger() {
  if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "onMyEdit").length == 0) {
    ScriptApp.newTrigger("onMyEdit").forSpreadsheet(SpreadsheetApp.getActive()).onEdit().create();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.