代码之家  ›  专栏  ›  技术社区  ›  DavChana

如何获取谷歌应用程序脚本的文本内容?

  •  -1
  • DavChana  · 技术社区  · 6 年前

    目标是从Google Drive获取脚本类型的所有文件,并在一个循环中逐个获取其文本内容。

    我的代码是:

    function searchFiles() {
      //https://developers.google.com/apps-script/reference/base/mime-type
      var type = MimeType.GOOGLE_APPS_SCRIPT;
      var files = DriveApp.getFilesByType(type);
      while (files.hasNext()) {
        var file = files.next();
        process(file);
      }
    }
    function process(file){
      //https://developers.google.com/apps-script/reference/base/mime-type
      var txt = file.getBlob(PLAIN_TEXT);
      Logger.log(txt);
    }
    

    从file.getblob()得到的错误是: Converting from application/vnd.google-apps.script to application/pdf is not supported.

    我也试过祭祀 file.getUrl() 但是,如果我以匿名方式打开文件,那么这也只会给出文件的整个HTML,如果我是在登录&错误页HTML的同一窗口中打开的。

    是否可以在谷歌应用程序脚本中获取脚本文件的文本内容?

    1 回复  |  直到 6 年前
        1
  •  3
  •   TheMaster    6 年前

    Flow:

    • 按mime获取所有脚本文件
    • 获取每个文件的ID
    • 通过驱动器REST API或应用程序脚本API来获取

    脚本:

    function getScriptSourceCode(fileid) {
      var params = {
        headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
        followRedirects: true,
        muteHttpExceptions: true,
      };
      var url =
        'https://script.google.com/feeds/download/export?id=' +
        fileid +
        '&format=json';
      var response = UrlFetchApp.fetch(url, params);
      var json = JSON.parse(response);
      for (var file in json['files']) {
        Logger.log(json['files'][file]['source']); //Source code
      }
    }
    

    参考文献: