DocumentApp.openById() 失败并显示“服务不可用”

DocumentApp.openById() fails with “Service unavailable”

我正在尝试读取电子表格的内容,其中包含一些 folderIdfileNametargetFile,然后基于电子表格中输入的数据。

我在驱动器中找到了同一个 fileName 的最新 fileId,因为每天都有多个同名文件被添加到文件夹中(这是由函数 [=17 完成的) =]) 然后我试图将 ID 为 dociIdSource 的最新文件的内容复制到 ID 为 docIdTarget 的不同文件中(由函数 docCopy 完成)。

但是当我尝试使用 DocumentApp 实现它时,我收到了一个奇怪的错误

Service unavailable: Docs

代码 var baseDoc = DocumentApp.openById(docID);

我可以知道我哪里错了吗?

// Test function to call applyDocCopytoList.
function test(){
  applyDocCopytoList();
}

// Read the values from the spreadsheet.
function applyDocCopytoList(){
  var originalSpreadsheet = SpreadsheetApp.openById('sheet Id goes here').getSheetByName("sheet name goes here");
  var getRange = originalSpreadsheet.getDataRange();
  var data = originalSpreadsheet.getDataRange().getValues();
  for (var i = 1; i < data.length; i++) {
    var folderId = data[i][1];
    var fileName = data[i][2];
    var targetFile = data[i][3];

    Logger.log('****************Record No: ' + i);
    Logger.log('folderId: ' + data[i][1]);
    Logger.log('fileName: ' + data[i][2]);
    Logger.log('targetFile: ' + data[i][3]);

    var latestFileId = mostRecentFiIeInFolder(folderId, fileName);
    if(latestFileId!= undefined){
      docCopy(latestFileId, targetFile);
    }
  }
}


// Log the id of the latest file with a particular name in the folder.
function mostRecentFiIeInFolder(folderId, fileName) {
  var folder = DriveApp.getFolderById(folderId);
  Logger.log(folder);
  var files = DriveApp.getFilesByName(fileName);
  Logger.log(fileName);
  var result = [];
  // Checks whether the given file is in the folder or not
  if(!files.hasNext()){
    Logger.log('No such file in the folder with the given name');
  }
  else{
    while (files.hasNext()) {
      var file = files.next();
      result.push([file.getDateCreated(), file.getId()]);
    }
    Logger.log('************All the file ids with the same file name and their dates created************');  
    Logger.log(result);
    result.sort(function (x, y){
      var xp = x[0];// get first element in inner array
      var yp = y[0];
      return xp == yp ? 0 : xp > yp ? -1 : 1;// choose the sort order, here its in descending order of created date
    });    
    var id = result[0][1];
    Logger.log(id);
    return id;
  }
}

// Copy the contents of the latest file in the target file.
function docCopy(dociIdSource, docIdTarget){
  Logger.log('The file with id: ' + dociIdSource + ' will be copied to the target id: ' + docIdTarget);

  var docID = docIdTarget;
  var baseDoc = DocumentApp.openById(docID); //Service unavailable: Docs error is thrown for this line of code
  var body = baseDoc.getBody();

  var otherBody = DocumentApp.openById(dociIdSource).getBody();
  var totalElements = otherBody.getNumChildren();
  for( var j = 0; j < totalElements; ++j ) {
    var element = otherBody.getChild(j).copy();
    var type = element.getType();
    if( type == DocumentApp.ElementType.PARAGRAPH )
      body.appendParagraph(element);
    else if( type == DocumentApp.ElementType.TABLE )
      body.appendTable(element);
    else if( type == DocumentApp.ElementType.LIST_ITEM )
      body.appendListItem(element);
    else if( type == DocumentApp.ElementType.INLINE_IMAGE )
      body.appendImage(element);
    else if( type == DocumentApp.ElementType.TEXT ) 
      body.setText(element); 
    else
      throw new Error("According to the doc this type couldn't appear in the body: " + type);
  }
}

请注意,您的 mostRecentFiIeInFolder 函数实际上从未使用该文件夹,也从未检查过文件的类型是否正确 - 即实际上是 Google Docs 文件。因此,如果您搜索的名称应该没有找到任何内容(即在您的目标文件夹中没有最近使用该名称的文件),但您在驱动器的其他地方有一些替代文件,一个不是 Google Docs 文件的文件,您的脚本会找到它并将其视为不是它的东西。

解决方案是将您的搜索限制在您想要的文件夹中,并再次通过实际 Google 文档 mimetype:

function testIt() {
  var folderIds = [
    "", // Search all of Drive
    "123428349djf8234", // Search that specific folder
  ];
  // Log (in Stackdriver) the file id of the most recently created Google Docs file with the name "some name" in the various folders:
  folderIds.forEach(function (folderId) {
    console.log(getMostRecentFileIdWithName("some name", folderId, MimeType.GOOGLE_DOCS));
  });
}

function getMostRecentFileIdWithName(fileName, folderId = "", mimeType = "") {
  // If a folder was given, restrict the search to that folder. Otherwise, search with
  // DriveApp. (Throws an error if the folderId is invalid.)
  var parent = folderId ? DriveApp.getFolderById(folderId) : DriveApp;

  // I assume your fileName variable does not contain any unescaped single-quotes.
  var params = "name='" + fileName + "'";
  // If a mimetype was given, search by that type only, otherwise search any type.
  if (mimeType)
    params += " and mimeType='" + mimeType + "'";
  var matches = parent.searchFiles(params),
      results = [];

  // Collect and report results.
  while (matches.hasNext())
    results.push(matches.next());
  if (!results.length)
    throw new Error("Bad search query \"" + params + "\" for folder id = '" + folderId + "'.");

  // Sort descending by the creation date (a native Date object).
  // (a - b sorts ascending by first column).
  results.sort(function (a, b) { return b.getDateCreated() - a.getDateCreated(); });
  return results[0].getId();
}

您可以在 Drive REST API documentation, and more about the Apps Script native implementation in the DriveApp documentation 中阅读有关可接受的搜索参数的更多信息。