【问题标题】:Google Sheet Script not triggered when sheet is edited by service account?服务帐户编辑工作表时未触发 Google 工作表脚本?
【发布时间】:2021-04-10 00:41:55
【问题描述】:

所以我编写了一个 gs 函数,当有人在工作表中插入新行时发送电子邮件。当用户手动插入数据时它可以正常工作,但是该工作表也由通过 API 插入新行的服务帐户使用,并且在这种情况下不会触发编辑事件。

这是我正在使用的触发器

我作为工作表的所有者创建了脚本和触发器,但这并没有解决任何问题,所以我没有想法。

【问题讨论】:

    标签: google-apps-script google-sheets google-sheets-api


    【解决方案1】:

    使用代码触发用户事件的唯一方法是使用 Sheets API,通过特殊设置将值设置为 USER_ENTERED 并且它仅适用于“On Change”事件。因此,您需要为“On Change”创建第二个触发器,但您可以使用相同的函数名称。尽管您可能需要修改函数以处理不同的事件对象。或者你可以使用不同的函数。

    因此,您的服务帐户将需要运行使用 Sheets API 在您的 Google Sheet 中设置值的代码。

    您可以使用 REST API 或表格高级服务。

    要使用 Advance Sheets Service,代码如下所示:

    function writeToSheet() {
      id = "Put the Sheet ID here";
    
      var rowValues = [
        ["one","two"],
      ];
    
      var request = {
        'valueInputOption': 'USER_ENTERED',
        'data': [
          {
            "range": "Sheet1!A2:B2",
            "majorDimension": "ROWS",
            "values": rowValues,
          },
        ],
      };
    
      var response = Sheets.Spreadsheets.Values.batchUpdate(request, id);
      Logger.log('response ' + JSON.stringify(response))
    }
    

    REST API 的基本代码如下:

    function writeToSheet() {
      var id,options,range,response,sh,ss,url,values;
    
      id = 'Put the spreadsheet ID here';
      range = "Sheet1!A1:A1";
      values = {values: [['3','two','nine']]}; // Modified
    
      url = "https://sheets.googleapis.com/v4/spreadsheets/" +
        id + "/values/" + range + ":append?valueInputOption=USER_ENTERED";
    
      options = {
        "method":"post",
        "muteHttpExceptions": true,
        "headers": {
          "Authorization": "Bearer " + ScriptApp.getOAuthToken()
        },
        "contentType": "application/json", // Added
        "payload": JSON.stringify(values) // Added
      }
    
      response = UrlFetchApp.fetch(url,options)
      response = JSON.parse(response);
    
      //Logger.log('response ' + JSON.stringify(response))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多