Google Apps 独立脚本使用 Google Apps 脚本 API 更新许多绑定脚本

Google Apps Standalone Script to use Google Apps Script API to update many bound scripts

我正在尝试编写一个独立的 Google Apps 脚本,它使用 Google Apps Script API 来更新许多 Google Sheet 的绑定脚本内容。

我有大约 200 个 Google Sheet 的 Sheet ID 是我从模板创建的。我想更新每个 sheet 上绑定脚本的项目内容,使其与一组主脚本相同。

我在使用 urlFetchApp 获取一个 sheet 的绑定脚本的内容作为测试时遇到身份验证错误。错误看起来像:

Request failed for
https://script.googleapis.com/v1/projects/<SCRIPTID>/content returned code 401. 
Truncated server response: { "error": { "code": 401, 
"message": "Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie ... 
(use muteHttpExceptions option to examine full response) (line 34, file "AddScriptsToSheets")

我使用的测试函数如下所示:

function getSheetScriptContent(sheetId) { 
  var sheet = SpreadsheetApp.openById(sheetId);
  // Make a POST request with a JSON payload.
  // Make a GET request and log the returned content.
  var url = PROJECTS_GET_CONTENT_URL.format(sheetId);
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

我认为这个 OAuth2 library 在这种情况下可能会有用,我只是不确定如何使用它。谁能指出我正确的方向?

如果您拥有所有文件,则无需使用 OAuth 库或任何特殊代码来获取访问令牌。您可以从 ScriptApp class.

获取访问令牌
var theAccessTkn = ScriptApp.getOAuthToken();

您可能需要手动编辑 appsscript.json 清单文件并添加范围:

https://www.googleapis.com/auth/script.projects

appsscript.json

{
  "timeZone": "Yours will display here",
  "dependencies": {
  },
  "webapp": {
    "access": "MYSELF",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": [
    "https://www.googleapis.com/auth/drive", 
    "https://www.googleapis.com/auth/script.projects", 
    "https://www.googleapis.com/auth/drive.scripts", 
    "https://www.googleapis.com/auth/script.container.ui", 
    "https://www.googleapis.com/auth/script.external_request"
  ],
  "runtimeVersion": "DEPRECATED_ES5"
}

覆盖 Apps 脚本文件的代码:

function updateContent(scriptId,content,theAccessTkn) {
try{
  var options,payload,response,url;

  if (!content) {
    //Error handling function
    return;
  }
  
  if (!theAccessTkn) {
    theAccessTkn = ScriptApp.getOAuthToken();
  }
  
  //https://developers.google.com/apps-script/api/reference/rest/v1/projects/updateContent
  url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content";

  options = {
    "method" : "PUT",
    "muteHttpExceptions": true,
    "headers": {
      'Authorization': 'Bearer ' +  theAccessTkn
     },
    "contentType": "application/json",//If the content type is set then you can stringify the payload
    "payload": JSON.stringify(content)
  };
  
  response = UrlFetchApp.fetch(url,options);      
  //Logger.log('getResponseCode ' + response.getResponseCode())
  //Logger.log("Response content: " + response.getContentText())

} catch(e) {
  console.log("Error: " + e + "\nStack: " + e.stack)
}
};