使用谷歌应用程序脚本在谷歌文档中发送批量更新的批量请求时出错

问题描述 投票:0回答:1

我正在尝试创建 Google 文档文件的副本并使用以下方法替换其中的文本

batchRequest, batchUpdate, replaceAllText

作为一个库,我使用来自

github
的库 tanaike batchRequests

我可以创建副本,但是当我尝试替换文本时出现错误

404

这是我的代码:

/**
 * переменная LIST получает данные с листа с названием 1 которые содержаться в 1 и 2 колонке
 * номер и фио
 */

const LIST = SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName('1')
  .getDataRange()
  .getValues()
  .filter(f => f[0] != "")
  .map(f => [f[0], f[1]]);

function Creator() {
  var requests = LIST.map(([b1, a2], i) => {
    return {
      method: "POST",
      endpoint: `https://www.googleapis.com/drive/v3/files/1IzwefpoJOksTyBo0CaGcsaG9L_jrZW6Vuw4lGqC07_Y/copy`,
      requestBody: {
        parents: ["1qI-T2m1sL_I69wc7EAOJr3ZK3233X5qX"], name: `Договор № ${b1} с ${a2}`} // заполните здесь название которое вам нужно что бы получилось
    }
  });
  var res = BatchRequest.EDo({
    batchPath: "batch/drive/v3",
    requests: requests,
  });
  console.log(res);
  batchUpdate(res);
}

function batchUpdate(res) {
  var IDS = res.map((item) => {
    return item.id;
  });
  var requests = support_lib.concatArrays(LIST,IDS).map(([num, name, id]) => {
    return {
      method: "POST",
      endpoint: `https://docs.googleapis.com/v1/documents/${id}:batchUpdate`,
      requestBody: {
        replaceAllText:
        {
          replaceText: num, containsText: { text: "<номер>", matchCase: true },
          replaceText: name, containsText: { text: "<фио>", matchCase: true }
        }
      }
    }
  });
  var response = BatchRequest.EDo({
    batchPath: "batch/drive/v3",
    requests: requests,
  });
  console.log(JSON.stringify(response, null, 2));
}

回复:

17:08:00    Информация  [ { kind: 'drive#file',
    id: '1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs',
    name: 'Договор № 1 с Кожевников Антон Юрьевич',
    mimeType: 'application/vnd.google-apps.document' },
  { kind: 'drive#file',
    id: '1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0',
    name: 'Договор № 2 с Кожевникова Любвоь Алексеевна',
    mimeType: 'application/vnd.google-apps.document' } ]
17:08:00    Информация  [
  {
    "error": {
      "code": 404,
      "message": "URL path: /v1/documents/1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
      "errors": [
        {
          "message": "URL path: /v1/documents/1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
          "domain": "global",
          "reason": "notFound"
        }
      ],
      "status": "NOT_FOUND"
    }
  },
  {
    "error": {
      "code": 404,
      "message": "URL path: /v1/documents/1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
      "errors": [
        {
          "message": "URL path: /v1/documents/1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
          "domain": "global",
          "reason": "notFound"
        }
      ],
      "status": "NOT_FOUND"
    }
  }
]
google-apps-script google-drive-api google-docs-api batch-request
1个回答
0
投票

修改要点:

  • 当我看到您的显示脚本时,我认为您当前问题的原因是您尝试在批量请求中使用方法:documents.batchUpdate。目前阶段无法与批量请求一起使用。
  • 为了对多个文档ID使用方法:documents.batchUpdate,需要循环使用它。
  • 此外,您的 Docs API 请求正文不正确。

虽然我不确定

support_lib.concatArrays(LIST,IDS)
,但是当假设
support_lib.concatArrays(LIST,IDS)
返回有效值时,下面的修改如何?

在此修改中,修改了功能

batchUpdate(res)

修改后的脚本:

此脚本使用 Google Docs API。因此,请在高级 Google 服务中启用 Google Docs API

function batchUpdate(res) {
  var IDS = res.map((item) => {
    return item.id;
  });
  support_lib.concatArrays(LIST, IDS).forEach(([num, name, id]) => {
    const requests = [
      { replaceAllText: { replaceText: num, containsText: { text: "<номер>", matchCase: false } } },
      { replaceAllText: { replaceText: name, containsText: { text: "<фио>", matchCase: false } } }
    ];
    const res = Docs.Documents.batchUpdate({ requests }, id);
    console.log(res);
    
    // Utilities.sleep(5000); // If there are a lot of IDs, this might be required to be used by adjusting the wait time.
  });
}
  • 当假设
    IDS
    support_lib.concatArrays(LIST, IDS)
    的值为有效值来运行此脚本时,复制的模板文档将由
    requests
    更新。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.