DocumentApp.openById()失败,并显示“服务不可用" [英] DocumentApp.openById() fails with “Service unavailable”

查看:84
本文介绍了DocumentApp.openById()失败,并显示“服务不可用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取包含一些folderIdfileNametargetFile的电子表格的内容,然后根据在电子表格中输入的数据进行阅读.

I am trying to read the contents of a spreadsheet which contains some folderId, fileName and targetFile and then based on the data entered in the spreadsheet.

我正在驱动器中找到同一fileName的最新fileId,因为每天都有多个具有相同名称的文件被添加到该文件夹​​中(这是通过功能mostRecentFiIeInFolder完成的),然后我正在尝试将ID为dociIdSource的最新文件的内容复制到ID为docIdTarget的其他文件中(由功能docCopy完成).

I am finding the latest fileId in the drive for the same fileName as multiple files with the same name are getting added into the folder daily (this is done by the function mostRecentFiIeInFolder) and then I am trying to copy the contents of the latest file with ID dociIdSource into a different file with ID docIdTarget (which is done by the function docCopy).

但是当我尝试使用DocumentApp实施此操作时,出现了一个奇怪的错误,提示

But when I tried Implementing this using DocumentApp, I am getting a weird error which says

服务不可用:文档

Service unavailable: Docs

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

我可以知道我要去哪里了吗

May I know where I am going wrong?

// 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文件),则脚本会找到该文件并把它当作不是的东西.

Note that your mostRecentFiIeInFolder function never actually uses the folder, and doesn't ever check that the files are of the correct type - i.e., are actually Google Docs files. Thus if your searched name should have found nothing (i.e. there is no recent file with that name in your target folder), but you had some alternate file elsewhere in your Drive, one that is not a Google Docs file, your script will find it and treat it as something it is not.

解决方案是将搜索范围限制为所需的文件夹,然后再按实际的Google Docs mimetype:

The solution is to restrict your search to your desired folder, and again by actual Google Docs 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文档中详细了解可接受的搜索参数. ,以及> DriveApp文档中的更多信息.

You can read more about the acceptable search parameters in the Drive REST API documentation, and more about the Apps Script native implementation in the DriveApp documentation.

这篇关于DocumentApp.openById()失败,并显示“服务不可用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆