เรียกใช้ฟังก์ชันด้วย Google Apps Script API

Apps Script API มีเมธอด scripts.run ที่ เรียกใช้ฟังก์ชัน Google Apps Script ที่ระบุจากระยะไกล คุณสามารถใช้วิธีนี้ในแอปพลิเคชันการโทรเพื่อเรียกใช้ฟังก์ชันในโปรเจ็กต์สคริปต์อย่างใดอย่างหนึ่งจากระยะไกลและรับการตอบกลับ

ข้อกำหนด

ก่อนที่แอปพลิเคชันการโทรจะใช้เมธอด scripts.run ได้ คุณต้องทำดังนี้

  • นำโปรเจ็กต์สคริปต์ไปใช้เป็นไฟล์ดำเนินการของ API คุณสามารถติดตั้ง ถอนการติดตั้ง และติดตั้งโปรเจ็กต์อีกครั้งได้ตามต้องการ

  • ระบุโทเค็น OAuth ที่กำหนดขอบเขตอย่างถูกต้องสำหรับการดำเนินการ โทเค็น OAuth นี้ ต้องครอบคลุมขอบเขตทั้งหมดที่สคริปต์ใช้ ไม่ใช่เฉพาะขอบเขตที่ฟังก์ชันที่เรียกใช้ใช้ ดูรายการทั้งหมดของ ขอบเขตการให้สิทธิ์ ในการอ้างอิงเมธอด

  • ตรวจสอบว่าสคริปต์และแอปพลิเคชันที่เรียกใช้ ไคลเอ็นต์ OAuth2 ใช้โปรเจ็กต์ Google Cloud เดียวกัน โปรเจ็กต์ที่อยู่ในระบบคลาวด์ต้องเป็นโปรเจ็กต์ที่อยู่ในระบบคลาวด์มาตรฐาน โปรเจ็กต์เริ่มต้นที่สร้างขึ้นสำหรับโปรเจ็กต์ Apps Script นั้นไม่เพียงพอ คุณจะใช้โปรเจ็กต์ Cloud มาตรฐานใหม่หรือโปรเจ็กต์ที่มีอยู่ก็ได้

  • เปิดใช้ Google Apps Script API ในโปรเจ็กต์ Cloud

scripts.run วิธี

วิธี scripts.run ต้องใช้ข้อมูลต่อไปนี้

คุณสามารถกำหนดค่าสคริปต์ให้ดำเนินการในโหมดการพัฒนาได้ โหมดนี้จะทำงานกับโปรเจ็กต์สคริปต์เวอร์ชันที่บันทึกไว้ล่าสุด แทนที่จะเป็นเวอร์ชันที่ใช้งานล่าสุด โดยตั้งค่า devModeบูลีนใน เนื้อหาคำขอ เป็น true มีเพียงเจ้าของสคริปต์เท่านั้นที่สามารถเรียกใช้สคริปต์ในโหมดการพัฒนาได้

จัดการประเภทข้อมูลพารามิเตอร์

การใช้เมธอด Apps Script API scripts.run มักเกี่ยวข้องกับการส่งข้อมูลไปยัง Apps Script เป็นพารามิเตอร์ฟังก์ชัน และการรับข้อมูลกลับเป็นค่าที่ฟังก์ชันส่งคืน API สามารถ รับและแสดงค่าที่มีประเภทพื้นฐานเท่านั้น ได้แก่ สตริง อาร์เรย์ ออบเจ็กต์ ตัวเลข และ บูลีน API ไม่สามารถส่งผ่านออบเจ็กต์ Apps Script ที่ซับซ้อนกว่า เช่น Document หรือ Sheet ไปยังหรือจากโปรเจ็กต์สคริปต์ได้

เมื่อเขียนแอปพลิเคชันการโทรในภาษาที่มีการพิมพ์อย่างเข้มงวด เช่น Java แอปพลิเคชันจะส่งพารามิเตอร์เป็นรายการหรืออาร์เรย์ของออบเจ็กต์ทั่วไปที่สอดคล้องกับประเภทพื้นฐานเหล่านี้ ในหลายกรณี คุณสามารถใช้ Conversion ประเภท ได้โดยอัตโนมัติ ตัวอย่างเช่น ฟังก์ชันที่ใช้พารามิเตอร์ตัวเลข สามารถรับออบเจ็กต์ Java Double, Integer หรือ Long เป็นพารามิเตอร์ได้โดยไม่ต้อง มีการจัดการเพิ่มเติม

เมื่อ API แสดงผลการตอบกลับของฟังก์ชัน คุณมักจะต้องแคสต์ค่าที่แสดงผลเป็นประเภทที่ถูกต้องก่อนจึงจะใช้งานได้ ตัวอย่างที่ใช้ Java มีดังนี้

  • ตัวเลขที่ API ส่งคืนไปยังแอปพลิเคชัน Java จะมาในรูปแบบออบเจ็กต์ java.math.BigDecimal และอาจต้องแปลงเป็นประเภท Double หรือ int
  • หากฟังก์ชัน Apps Script แสดงผลอาร์เรย์ของสตริง แอปพลิเคชัน Java จะส่งการตอบกลับไปยังออบเจ็กต์ List<String>

    List<String> mylist = (List<String>)(op.getResponse().get("result"));
    
  • หากต้องการแสดงอาร์เรย์ของ Bytes ให้เข้ารหัสอาร์เรย์เป็นสตริง base64 ภายในฟังก์ชัน Apps Script แล้วแสดงสตริงนั้นแทน

    return Utilities.base64Encode(myByteArray); // returns a string.
    

ตัวอย่างโค้ดด้านล่างแสดงวิธี ตีความการตอบกลับของ API

ขั้นตอนทั่วไป

หากต้องการใช้ Apps Script API เพื่อเรียกใช้ฟังก์ชัน Apps Script ให้ทำตามขั้นตอนต่อไปนี้

ขั้นตอนที่ 1: ตั้งค่าโปรเจ็กต์ Cloud ทั่วไป

ทั้งสคริปต์และแอปพลิเคชันที่เรียกใช้ต้องใช้โปรเจ็กต์ Cloud เดียวกัน ซึ่งอาจเป็นโปรเจ็กต์ที่มีอยู่แล้วหรือโปรเจ็กต์ใหม่ที่สร้างขึ้น เพื่อวัตถุประสงค์นี้ เมื่อมีโปรเจ็กต์ Cloud แล้ว คุณต้องเปลี่ยนโปรเจ็กต์สคริปต์ให้ใช้โปรเจ็กต์ Cloud ดังกล่าว

ขั้นตอนที่ 2: ทำให้สคริปต์ใช้งานได้เป็นไฟล์ดำเนินการของ API

  1. เปิดโปรเจ็กต์ Apps Script ที่มีฟังก์ชันที่คุณต้องการใช้
  2. ที่ด้านขวาบน ให้คลิกติดตั้งใช้งาน > การติดตั้งใช้งานใหม่
  3. ในกล่องโต้ตอบที่เปิดขึ้น ให้คลิกเปิดใช้ประเภทการทำให้ใช้งานได้ > API Executable
  4. ในเมนูแบบเลื่อนลง "ใครมีสิทธิ์เข้าถึง" ให้เลือกผู้ใช้ที่ได้รับอนุญาต ให้เรียกใช้ฟังก์ชันของสคริปต์โดยใช้ Apps Script API
  5. คลิกทำให้ใช้งานได้

ขั้นตอนที่ 3: กำหนดค่าแอปพลิเคชันการโทร

แอปพลิเคชันที่เรียกใช้ต้องเปิดใช้ Apps Script API และสร้างข้อมูลเข้าสู่ระบบ OAuth ก่อนใช้งาน คุณต้องมีสิทธิ์เข้าถึง โปรเจ็กต์ Cloud เพื่อดำเนินการนี้

  1. กำหนดค่าโปรเจ็กต์ระบบคลาวด์ที่แอปพลิเคชันการโทรและ สคริปต์ของคุณใช้ ดังนี้
    1. เปิดใช้ Apps Script API ในโปรเจ็กต์ Cloud
    2. กำหนดค่าหน้าจอขอความยินยอม OAuth
    3. สร้างข้อมูลเข้าสู่ระบบ OAuth
  2. เปิดโปรเจ็กต์สคริปต์ แล้วคลิกภาพรวม ทางด้านซ้าย
  3. ในส่วนขอบเขต OAuth ของโปรเจ็กต์ ให้บันทึกขอบเขตทั้งหมดที่สคริปต์ ต้องการ
  4. ในโค้ดแอปพลิเคชันการเรียก ให้สร้างโทเค็นเพื่อการเข้าถึง OAuth ของสคริปต์ สำหรับการเรียก API นี่ไม่ใช่โทเค็นที่ API ใช้เอง แต่เป็นโทเค็นที่สคริปต์ต้องการเมื่อดำเนินการ โดยควรสร้างโดยใช้ รหัสไคลเอ็นต์ของโปรเจ็กต์ Cloud และขอบเขตสคริปต์ที่คุณบันทึกไว้

    ไลบรารีของไคลเอ็นต์ Google สามารถช่วยในการสร้างโทเค็นนี้และจัดการ OAuth สำหรับแอปพลิเคชัน โดยปกติแล้วจะช่วยให้คุณสร้างออบเจ็กต์ "ข้อมูลเข้าสู่ระบบ" ระดับที่สูงขึ้นได้โดยใช้ขอบเขตของสคริปต์ ดูตัวอย่างการสร้างออบเจ็กต์ข้อมูลเข้าสู่ระบบจากรายการขอบเขตได้ที่การเริ่มต้นอย่างรวดเร็วของ Apps Script API

ขั้นตอนที่ 4: ส่งคำขอ scripts.run

เมื่อกำหนดค่าแอปพลิเคชันการโทรแล้ว คุณจะโทร scripts.run ได้ดังนี้

  1. สร้างคำขอ API โดยใช้รหัสสคริปต์ ชื่อฟังก์ชัน และพารามิเตอร์ที่จำเป็น
  2. เรียกใช้ scripts.run และรวมโทเค็น OAuth ของสคริปต์ที่คุณสร้างไว้ในส่วนหัว (หากใช้คำขอ POST พื้นฐาน) หรือใช้ออบเจ็กต์ข้อมูลเข้าสู่ระบบที่คุณสร้างด้วยขอบเขตของสคริปต์
  3. ปล่อยให้สคริปต์ทำงานจนเสร็จ สคริปต์อาจใช้เวลาดำเนินการนานถึง 6 นาที ดังนั้นแอปพลิเคชันของคุณควรอนุญาตให้ดำเนินการได้
  4. เมื่อเสร็จสิ้น ฟังก์ชันสคริปต์อาจแสดงผลค่า ซึ่ง API จะส่งกลับไปยังแอปพลิเคชันหากค่าเป็นประเภทที่รองรับ

คุณดูตัวอย่างscripts.runการเรียก API ได้ในส่วนต่อไปนี้

หากต้องการรีเฟรชโทเค็นเพื่อการเข้าถึง ให้เพิ่มข้อมูลโค้ดต่อไปนี้ก่อนscripts.runคำขอ API

if (credential.getExpiresInSeconds() <= 360) {
  credential.refreshToken();
}

ตัวอย่างคำขอ API

ตัวอย่างต่อไปนี้แสดงวิธีส่งคำขอการเรียกใช้ Apps Script API ในภาษาต่างๆ โดยเรียกใช้ฟังก์ชัน Apps Script เพื่อพิมพ์รายการโฟลเดอร์ในไดเรกทอรีรากของผู้ใช้ ต้องระบุรหัสสคริปต์ของโปรเจ็กต์ Apps Script ที่มีฟังก์ชันที่เรียกใช้ในตำแหน่งที่ระบุด้วย ENTER_YOUR_SCRIPT_ID_HERE ตัวอย่างใช้ไลบรารีของไคลเอ็นต์ Google API

สคริปต์เป้าหมาย

ฟังก์ชันในสคริปต์นี้ใช้ Drive API

คุณต้องเปิดใช้ Drive API ในโปรเจ็กต์ที่โฮสต์สคริปต์

นอกจากนี้ แอปพลิเคชันที่เรียกใช้ต้องส่งข้อมูลเข้าสู่ระบบ OAuth ซึ่งรวมถึงขอบเขตไดรฟ์ต่อไปนี้

  • https://www.googleapis.com/auth/drive

แอปพลิเคชันตัวอย่างที่นี่ใช้ไลบรารีของไคลเอ็นต์ Google เพื่อสร้างออบเจ็กต์ข้อมูลเข้าสู่ระบบสำหรับ OAuth โดยใช้ขอบเขตนี้

/**
 * Return the set of folder names contained in the user's root folder as an
 * object (with folder IDs as keys).
 * @return {Object} A set of folder names keyed by folder ID.
 */
function getFoldersUnderRoot() {
  const root = DriveApp.getRootFolder();
  const folders = root.getFolders();
  const folderSet = {};
  while (folders.hasNext()) {
    const folder = folders.next();
    folderSet[folder.getId()] = folder.getName();
  }
  return folderSet;
}

Java


/**
 * Create a HttpRequestInitializer from the given one, except set
 * the HTTP read timeout to be longer than the default (to allow
 * called scripts time to execute).
 *
 * @param {HttpRequestInitializer} requestInitializer the initializer
 *                                 to copy and adjust; typically a Credential object.
 * @return an initializer with an extended read timeout.
 */
private static HttpRequestInitializer setHttpTimeout(
    final HttpRequestInitializer requestInitializer) {
  return new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest httpRequest) throws IOException {
      requestInitializer.initialize(httpRequest);
      // This allows the API to call (and avoid timing out on)
      // functions that take up to 6 minutes to complete (the maximum
      // allowed script run time), plus a little overhead.
      httpRequest.setReadTimeout(380000);
    }
  };
}

/**
 * Build and return an authorized Script client service.
 *
 * @param {Credential} credential an authorized Credential object
 * @return an authorized Script client service
 */
public static Script getScriptService() throws IOException {
  Credential credential = authorize();
  return new Script.Builder(
      HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(credential))
      .setApplicationName(APPLICATION_NAME)
      .build();
}

/**
 * Interpret an error response returned by the API and return a String
 * summary.
 *
 * @param {Operation} op the Operation returning an error response
 * @return summary of error response, or null if Operation returned no
 * error
 */
public static String getScriptError(Operation op) {
  if (op.getError() == null) {
    return null;
  }

  // Extract the first (and only) set of error details and cast as a Map.
  // The values of this map are the script's 'errorMessage' and
  // 'errorType', and an array of stack trace elements (which also need to
  // be cast as Maps).
  Map<String, Object> detail = op.getError().getDetails().get(0);
  List<Map<String, Object>> stacktrace =
      (List<Map<String, Object>>) detail.get("scriptStackTraceElements");

  java.lang.StringBuilder sb =
      new StringBuilder("\nScript error message: ");
  sb.append(detail.get("errorMessage"));
  sb.append("\nScript error type: ");
  sb.append(detail.get("errorType"));

  if (stacktrace != null) {
    // There may not be a stacktrace if the script didn't start
    // executing.
    sb.append("\nScript error stacktrace:");
    for (Map<String, Object> elem : stacktrace) {
      sb.append("\n  ");
      sb.append(elem.get("function"));
      sb.append(":");
      sb.append(elem.get("lineNumber"));
    }
  }
  sb.append("\n");
  return sb.toString();
}

public static void main(String[] args) throws IOException {
  // ID of the script to call. Acquire this from the Apps Script editor,
  // under Publish > Deploy as API executable.
  String scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";
  Script service = getScriptService();

  // Create an execution request object.
  ExecutionRequest request = new ExecutionRequest()
      .setFunction("getFoldersUnderRoot");

  try {
    // Make the API request.
    Operation op =
        service.scripts().run(scriptId, request).execute();

    // Print results of request.
    if (op.getError() != null) {
      // The API executed, but the script returned an error.
      System.out.println(getScriptError(op));
    } else {
      // The result provided by the API needs to be cast into
      // the correct type, based upon what types the Apps
      // Script function returns. Here, the function returns
      // an Apps Script Object with String keys and values,
      // so must be cast into a Java Map (folderSet).
      Map<String, String> folderSet =
          (Map<String, String>) (op.getResponse().get("result"));
      if (folderSet.size() == 0) {
        System.out.println("No folders returned!");
      } else {
        System.out.println("Folders under your root folder:");
        for (String id : folderSet.keySet()) {
          System.out.printf(
              "\t%s (%s)\n", folderSet.get(id), id);
        }
      }
    }
  } catch (GoogleJsonResponseException e) {
    // The API encountered a problem before the script was called.
    e.printStackTrace(System.out);
  }
}

JavaScript

/**
 * Load the API and make an API call.  Display the results on the screen.
 */
function callScriptFunction() {
  const scriptId = '<ENTER_YOUR_SCRIPT_ID_HERE>';

  // Call the Apps Script API run method
  //   'scriptId' is the URL parameter that states what script to run
  //   'resource' describes the run request body (with the function name
  //              to execute)
  try {
    gapi.client.script.scripts.run({
      'scriptId': scriptId,
      'resource': {
        'function': 'getFoldersUnderRoot',
      },
    }).then(function(resp) {
      const result = resp.result;
      if (result.error && result.error.status) {
        // The API encountered a problem before the script
        // started executing.
        appendPre('Error calling API:');
        appendPre(JSON.stringify(result, null, 2));
      } else if (result.error) {
        // The API executed, but the script returned an error.

        // Extract the first (and only) set of error details.
        // The values of this object are the script's 'errorMessage' and
        // 'errorType', and an array of stack trace elements.
        const error = result.error.details[0];
        appendPre('Script error message: ' + error.errorMessage);

        if (error.scriptStackTraceElements) {
          // There may not be a stacktrace if the script didn't start
          // executing.
          appendPre('Script error stacktrace:');
          for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
            const trace = error.scriptStackTraceElements[i];
            appendPre('\t' + trace.function + ':' + trace.lineNumber);
          }
        }
      } else {
        // The structure of the result will depend upon what the Apps
        // Script function returns. Here, the function returns an Apps
        // Script Object with String keys and values, and so the result
        // is treated as a JavaScript object (folderSet).

        const folderSet = result.response.result;
        if (Object.keys(folderSet).length == 0) {
          appendPre('No folders returned!');
        } else {
          appendPre('Folders under your root folder:');
          Object.keys(folderSet).forEach(function(id) {
            appendPre('\t' + folderSet[id] + ' (' + id + ')');
          });
        }
      }
    });
  } catch (err) {
    document.getElementById('content').innerText = err.message;
    return;
  }
}

Node.js


import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Calls an Apps Script function to list the folders in the user's root Drive folder.
 */
async function callAppsScript() {
  // The ID of the Apps Script project to call.
  const scriptId = '1xGOh6wCm7hlIVSVPKm0y_dL-YqetspS5DEVmMzaxd_6AAvI-_u8DSgBT';

  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Apps Script API client.
  const script = google.script({version: 'v1', auth});

  const resp = await script.scripts.run({
    auth,
    requestBody: {
      // The name of the function to call in the Apps Script project.
      function: 'getFoldersUnderRoot',
    },
    scriptId,
  });

  if (resp.data.error?.details?.[0]) {
    // The API executed, but the script returned an error.
    // Extract the error details.
    const error = resp.data.error.details[0];
    console.log(`Script error message: ${error.errorMessage}`);
    console.log('Script error stacktrace:');

    if (error.scriptStackTraceElements) {
      // Log the stack trace.
      for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
        const trace = error.scriptStackTraceElements[i];
        console.log('\t%s: %s', trace.function, trace.lineNumber);
      }
    }
  } else {
    // The script executed successfully.
    // The structure of the response depends on the Apps Script function's return value.
    const folderSet = resp.data.response ?? {};
    if (Object.keys(folderSet).length === 0) {
      console.log('No folders returned!');
    } else {
      console.log('Folders under your root folder:');
      Object.keys(folderSet).forEach((id) => {
        console.log('\t%s (%s)', folderSet[id], id);
      });
    }
  }
}

Python

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def main():
  """Runs the sample."""
  # pylint: disable=maybe-no-member
  script_id = "1VFBDoJFy6yb9z7-luOwRv3fCmeNOzILPnR4QVmR0bGJ7gQ3QMPpCW-yt"

  creds, _ = google.auth.default()
  service = build("script", "v1", credentials=creds)

  # Create an execution request object.
  request = {"function": "getFoldersUnderRoot"}

  try:
    # Make the API request.
    response = service.scripts().run(scriptId=script_id, body=request).execute()
    if "error" in response:
      # The API executed, but the script returned an error.
      # Extract the first (and only) set of error details. The values of
      # this object are the script's 'errorMessage' and 'errorType', and
      # a list of stack trace elements.
      error = response["error"]["details"][0]
      print(f"Script error message: {0}.{format(error['errorMessage'])}")

      if "scriptStackTraceElements" in error:
        # There may not be a stacktrace if the script didn't start
        # executing.
        print("Script error stacktrace:")
        for trace in error["scriptStackTraceElements"]:
          print(f"\t{0}: {1}.{format(trace['function'], trace['lineNumber'])}")
    else:
      # The structure of the result depends upon what the Apps Script
      # function returns. Here, the function returns an Apps Script
      # Object with String keys and values, and so the result is
      # treated as a Python dictionary (folder_set).
      folder_set = response["response"].get("result", {})
      if not folder_set:
        print("No folders returned!")
      else:
        print("Folders under your root folder:")
        for folder_id, folder in folder_set.items():
          print(f"\t{0} ({1}).{format(folder, folder_id)}")

  except HttpError as error:
    # The API encountered a problem before the script started executing.
    print(f"An error occurred: {error}")
    print(error.content)


if __name__ == "__main__":
  main()

ข้อจำกัด

API ของ Apps Script มีข้อจำกัดต่อไปนี้

  1. โปรเจ็กต์ Cloud ทั่วไป สคริปต์ที่เรียกใช้และแอปพลิเคชันที่เรียกใช้ต้องแชร์โปรเจ็กต์ Cloud โปรเจ็กต์ Cloud ต้องเป็นโปรเจ็กต์ Cloud มาตรฐาน โปรเจ็กต์เริ่มต้นที่สร้างขึ้นสำหรับโปรเจ็กต์ Apps Script นั้น ไม่เพียงพอ

  2. พารามิเตอร์และประเภทการคืนค่าพื้นฐาน API ไม่สามารถส่งหรือแสดงออบเจ็กต์เฉพาะของ Apps Script (เช่น เอกสาร Blob ปฏิทิน ไฟล์ในไดรฟ์ ฯลฯ) ไปยัง แอปพลิเคชัน ส่งและแสดงได้เฉพาะประเภทพื้นฐาน เช่น สตริง อาร์เรย์ ออบเจ็กต์ ตัวเลข และ บูลีน

  3. ขอบเขต OAuth API จะเรียกใช้ได้เฉพาะสคริปต์ที่มีขอบเขตที่จำเป็นอย่างน้อย 1 รายการ ซึ่งหมายความว่าคุณไม่สามารถใช้ API เพื่อเรียกสคริปต์ ที่ไม่ต้องมีการให้สิทธิ์บริการอย่างน้อย 1 รายการ

  4. ไม่มีทริกเกอร์ API ไม่สามารถสร้างทริกเกอร์ของ Apps Script ได้