Невозможно запустить удаленное приложение Google Apps Script через node.js

У меня проблема с запуском следующего node.js для удаленного выполнения скрипта Google Apps. сам по себе скрипт Google Apps очень прост, он просто:

function addText(){
  SpreadsheetApp.openById('ID').getSheetByName('Sheet1').getRange('A1').setValue('test500');
}

Я пытаюсь протестировать запуск GAS удаленно. Я использую следующий сценарий:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'];
const TOKEN_PATH = 'credentials.json';


fs.readFile('client_secret.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  authorize(JSON.parse(content), callAppsScript);
});

function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  }); 
}

function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  }); 
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  }); 
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return callback(err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      }); 
      callback(oAuth2Client);
    }); 
  }); 
}

function callAppsScript(auth) {
  var scriptId = 'ID';
  const script = google.script({version: 'v1', auth});
  script.scripts.run({
    auth: auth,
    resource: {
      function: "addText",
      devMode:true
    },  
    scriptId: scriptId
  });  
}

Вылезает очень много ошибок, но в начале вот такое:

Error: Requested entity was not found.
  at createError (.../node_modules/axios/lib/core/createError.js:16:15)
  at settle (/home/jasonjurotich/node_modules/axios/lib/core/settle.js:18:12)
  at IncomingMessage.handleStreamEnd (.../node_modules/axios/lib/adapters/http.js:201:11)
  at IncomingMessage.emit (events.js:187:15)
  at endReadableNT (_stream_readable.js:1090:12)
  at process._tickCallback (internal/process/next_tick.js:63:19)

Я должен уточнить, что я использую Google Cloud Platform с Ubuntu 18, со всем обновленным, включая node. Вначале OAuth работает нормально, и GAS подключен к проекту Cloud Platform, в котором включены все необходимые API и client_secret.json правильно установлен и находится в нужном месте. Я следовал этому руководству и просто следовал руководству само по себе все нормально работает. Ошибки появляются только тогда, когда я изменяю последнюю часть, чтобы запустить конкретный скрипт. Сам простой ГАЗ тоже отлично работает, если я запускаю его как обычно.


comment
Возможный дубликат Запрошенный объект не найден. - Ошибка API выполнения скриптов приложений   -  person Martin Zeitler    schedule 26.08.2018


Ответы (1)


здесь это в основном объясняется: https://developers.google.com/apps-script/guides/cloud-platform-projects#accessing_an_apps_script_cloud_platform_project

хотя есть одно ограничение, которое также может быть причиной entity not found:

Проекты сценариев Cloud Platform, хранящиеся на общих дисках, могут быть недоступны.

как насчет замены var scriptId = 'ID'; фактическим scriptId?

или даже const SCRIPT_ID = '9t453c9zmt5fz792t5z7m9t4...';

person Martin Zeitler    schedule 25.08.2018