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

时间:2018-10-01 14:00:39

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

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

我有大约200个通过模板创建的Google表格的表格ID。我想将每张工作表上绑定脚本的项目内容更新为与一组主脚本相同。

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

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可能有用,我只是不确定如何使用它。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

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

var theAccessTkn = ScriptApp.getOAuthToken();

用于覆盖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);
  response = JSON.parse(response);//Must be parsed even though it shows as coming back as an object

  //Logger.log('typeof response: ' + typeof response)

  //Logger.log('response 29 in file GS_Update: ' + JSON.stringify(response).slice(0,45))

  return response;
//} catch(e) {
  //Logger.log(response)
//}
};