如何使用AppScript API更新电子表格绑定的脚本?

时间:2019-01-21 09:40:26

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

我打算用另一个脚本(源)中的内容更新绑定的脚本(目标)。我正在尝试以下代码。它不会产生任何错误,但也不会修改目标脚本。

function getScriptSourceCode() {
var srcProjectId = "id of source project"; // Source project ID
var destProjectId = "id of destination project"
var baseUrl = "https://script.googleapis.com/v1/projects";
var accessToken = ScriptApp.getOAuthToken()
var srcName = JSON.parse(UrlFetchApp.fetch(baseUrl + "/" + srcProjectId,       {
 method: "get",
 headers: {"Authorization": "Bearer " + accessToken}
 }).getContentText()).title;

 var content = UrlFetchApp.fetch(baseUrl + "/" + srcProjectId + "/content", {
 method: "get",
 headers: {"Authorization": "Bearer " + accessToken}
  }).getContentText();

var url = "https://script.googleapis.com/v1/projects/" + destProjectId   
 + "/content";

var  options = {
followRedirects: true,
"method" : "PUT",
"muteHttpExceptions": true,
"headers": {
  'Authorization': 'Bearer ' + accessToken
 },
 "contentType": "application/json",
 "payload": JSON.stringify(content)
}      
  var response = UrlFetchApp.fetch(url, options);
  }
}

我想念什么吗?

1 个答案:

答案 0 :(得分:0)

对不起,我输入了错误的脚本。我对脚本进行了一些修改,现在可以按需运行了。但是,似乎我必须运行两次脚本才能获得所需的结果。下面是工作脚本。

function UpdateScript() 
{
  var destProjectId = "Destination project ID"
  var srcProjectId = "Source Project ID"; // Source project ID
  var baseUrl = "https://script.googleapis.com/v1/projects";
  var accessToken = ScriptApp.getOAuthToken()

  var content = UrlFetchApp.fetch(baseUrl + "/" + srcProjectId + "/content", {
  method: "get",
  headers: {"Authorization": "Bearer " + accessToken}
  }).getContentText();

  // Upload a project to bound-script project.
 var response = JSON.parse(UrlFetchApp.fetch(baseUrl + "/" + destProjectId + "/content", {
  method: "put",
  contentType: 'application/json',
  headers: {"Authorization": "Bearer " + accessToken},
  payload: content
 }).getContentText());

}