Thực thi các hàm bằng API Google Apps Script

API Apps Script cung cấp phương thức scripts.run để thực thi từ xa một hàm Google Apps Script được chỉ định. Bạn có thể sử dụng phương thức này trong một ứng dụng gọi để chạy một hàm trong một trong các dự án tập lệnh của mình từ xa và nhận phản hồi.

Yêu cầu

Trước khi ứng dụng gọi có thể sử dụng phương thức scripts.run, bạn phải:

  • Triển khai dự án tập lệnh dưới dạng API có thể thực thi. Bạn có thể triển khai, huỷ triển khai và triển khai lại dự án khi cần.

  • Cung cấp mã thông báo OAuth được phân phạm vi đúng cách để thực thi. Mã thông báo OAuth này phải bao gồm tất cả các phạm vi mà tập lệnh sử dụng, chứ không chỉ những phạm vi mà hàm được gọi sử dụng. Xem danh sách đầy đủ các phạm vi uỷ quyền trong tài liệu tham khảo về phương thức.

  • Đảm bảo rằng tập lệnh và ứng dụng gọi của ứng dụng khách OAuth2 chia sẻ một dự án trên đám mây của Google Cloud chung. Dự án trên đám mây phải là một dự án trên đám mây tiêu chuẩn; các dự án mặc định được tạo cho dự án Apps Script là không đủ. Bạn có thể sử dụng một dự án trên đám mây tiêu chuẩn mới hoặc một dự án hiện có.

  • Bật API Google Apps Script trong dự án trên đám mây.

Phương thức scripts.run

Phương thức scripts.run yêu cầu các thông tin sau:

Bạn có thể tuỳ ý định cấu hình tập lệnh để thực thi ở chế độ phát triển. Chế độ này thực thi với phiên bản đã lưu gần đây nhất của dự án tập lệnh thay vì phiên bản được triển khai gần đây nhất. Để thực hiện việc này, hãy đặt boolean trong nội dung yêu cầu thành true.devMode Chỉ chủ sở hữu của tập lệnh mới có thể thực thi tập lệnh đó ở chế độ phát triển.

Xử lý các kiểu dữ liệu tham số

Việc sử dụng phương thức của API Apps Script scripts.run thường liên quan đến việc gửi dữ liệu đến Apps Script dưới dạng tham số hàm và nhận lại dữ liệu dưới dạng giá trị trả về của hàm. API chỉ có thể nhận và trả về các giá trị có kiểu cơ bản: chuỗi, mảng, đối tượng, số và boolean. API không thể truyền các đối tượng Apps Script phức tạp hơn như Tài liệu hoặc Trang tính vào hoặc từ dự án tập lệnh.

Khi ứng dụng gọi được viết bằng một ngôn ngữ được gõ mạnh như Java, ứng dụng này sẽ truyền các tham số dưới dạng danh sách hoặc mảng các đối tượng chung tương ứng với các kiểu cơ bản này. Trong nhiều trường hợp, bạn có thể tự động áp dụng các chuyển đổi kiểu. Ví dụ: một hàm nhận tham số số có thể được cung cấp đối tượng Double, Integer hoặc Long của Java làm tham số mà không cần xử lý thêm.

Khi API trả về phản hồi của hàm, bạn thường cần truyền giá trị trả về sang kiểu chính xác trước khi có thể sử dụng. Dưới đây là một số ví dụ dựa trên Java:

  • Các số do API trả về cho một ứng dụng Java sẽ đến dưới dạng đối tượng java.math.BigDecimal và có thể cần được chuyển đổi thành kiểu Double hoặc int.
  • Nếu hàm Apps Script trả về một mảng chuỗi, thì ứng dụng Java sẽ truyền phản hồi vào một List<String> đối tượng:

    List<String> mylist = (List<String>)(op.getResponse().get("result"));
    
  • Nếu bạn muốn trả về một mảng Bytes, hãy mã hoá mảng đó dưới dạng chuỗi base64 trong hàm Apps Script và trả về chuỗi đó:

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

Các mẫu mã ví dụ bên dưới minh hoạ các cách diễn giải phản hồi của API.

Quy trình chung

Để sử dụng API Apps Script nhằm thực thi các hàm Apps Script, hãy làm theo các bước sau:

Bước 1: Thiết lập dự án trên đám mây chung

Cả tập lệnh và ứng dụng gọi đều cần chia sẻ cùng một dự án trên đám mây. Dự án trên đám mây này có thể là một dự án hiện có hoặc một dự án mới được tạo cho mục đích này. Sau khi có dự án trên đám mây, bạn phải chuyển dự án tập lệnh để sử dụng dự án đó.

Bước 2: Triển khai tập lệnh dưới dạng API có thể thực thi

  1. Mở dự án Apps Script bằng các hàm mà bạn muốn sử dụng.
  2. Ở trên cùng bên phải, hãy nhấp vào Triển khai > Triển khai mới.
  3. Trong hộp thoại mở ra, hãy nhấp vào Bật các loại triển khai > API có thể thực thi.
  4. Trong trình đơn thả xuống "Ai có quyền truy cập", hãy chọn những người dùng được phép gọi các hàm của tập lệnh bằng API Apps Script.
  5. Nhấp vào Triển khai.

Bước 3: Định cấu hình ứng dụng gọi

Ứng dụng gọi phải bật API Apps Script và thiết lập thông tin xác thực OAuth trước khi sử dụng. Bạn phải có quyền truy cập vào dự án trên đám mây để thực hiện việc này.

  1. Định cấu hình dự án trên đám mây mà ứng dụng gọi và tập lệnh đang sử dụng:
    1. Bật API Apps Script trong dự án trên đám mây.
    2. Định cấu hình màn hình xin phép bằng OAuth.
    3. Tạo thông tin xác thực OAuth.
  2. Mở dự án tập lệnh rồi ở bên trái, hãy nhấp vào Tổng quan .
  3. Trong phần Phạm vi OAuth của dự án, hãy ghi lại tất cả các phạm vi mà tập lệnh yêu cầu.
  4. Trong mã xử lý ứng dụng gọi, hãy tạo mã truy cập OAuth tập lệnh cho lệnh gọi API. Đây không phải là mã thông báo mà chính API sử dụng, mà là mã thông báo mà tập lệnh yêu cầu khi thực thi. Bạn nên tạo mã thông báo này bằng mã ứng dụng khách của dự án trên đám mây và các phạm vi tập lệnh mà bạn đã ghi lại.

    Thư viện ứng dụng Google có thể hỗ trợ tạo mã thông báo này và xử lý OAuth cho ứng dụng, thường cho phép bạn tạo đối tượng "thông tin xác thực" cấp cao hơn bằng các phạm vi tập lệnh. Hãy xem phần Bắt đầu nhanh về API Apps Script để biết ví dụ về cách tạo đối tượng thông tin xác thực từ danh sách phạm vi.

Bước 4: Tạo yêu cầu scripts.run

Sau khi định cấu hình ứng dụng gọi, bạn có thể thực hiện các lệnh gọi scripts.run:

  1. Tạo yêu cầu API bằng mã triển khai, tên hàm và mọi tham số bắt buộc.
  2. Thực hiện scripts.run lệnh gọi và đưa mã thông báo OAuth tập lệnh mà bạn đã tạo vào tiêu đề (nếu sử dụng yêu cầu POST cơ bản) hoặc sử dụng đối tượng thông tin xác thực mà bạn đã tạo bằng các phạm vi tập lệnh.
  3. Cho phép tập lệnh hoàn tất việc thực thi. Tập lệnh có thể mất tối đa 6 phút để thực thi, vì vậy, ứng dụng của bạn phải cho phép điều này.
  4. Sau khi hoàn tất, hàm tập lệnh có thể trả về một giá trị mà API sẽ gửi lại cho ứng dụng nếu giá trị đó là một kiểu được hỗ trợ.

Bạn có thể tìm thấy các ví dụ về scripts.run lệnh gọi API trong phần sau.

Để làm mới mã truy cập, hãy thêm đoạn mã sau trước yêu cầu API scripts.run:

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

Ví dụ về yêu cầu API

Các ví dụ sau đây cho thấy cách tạo yêu cầu thực thi API Apps Script bằng nhiều ngôn ngữ, gọi một hàm Apps Script để in danh sách thư mục trong thư mục gốc của người dùng. Bạn phải chỉ định mã triển khai của dự án Apps Script chứa hàm được thực thi ở nơi được chỉ định bằng ENTER_YOUR_DEPLOYMENT_ID_HERE. Các ví dụ này dựa vào thư viện ứng dụng API của Google.

Tập lệnh đích

Hàm trong tập lệnh này sử dụng API Drive.

Bạn phải bật API Drive trong dự án lưu trữ tập lệnh.

Ngoài ra, các ứng dụng gọi phải gửi thông tin xác thực OAuth bao gồm phạm vi Drive sau:

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

Các ứng dụng ví dụ ở đây sử dụng thư viện ứng dụng Google để tạo các đối tượng thông tin xác thực cho OAuth bằng phạm vi này.

/**
 * 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()

Các điểm hạn chế

API Apps Script có những hạn chế sau:

  1. Một dự án trên đám mây chung. Tập lệnh đang được gọi và ứng dụng gọi phải chia sẻ một dự án trên đám mây. Dự án Cloud phải là một dự án trên đám mây tiêu chuẩn; các dự án mặc định được tạo cho dự án Apps Script là không đủ.

  2. Tham số cơ bản và kiểu trả về. API không thể truyền hoặc trả về các đối tượng dành riêng cho Apps Script (chẳng hạn như Tài liệu, Blob, Lịch, Tệp Drive, v.v.) cho ứng dụng. Chỉ các kiểu cơ bản như chuỗi, mảng, đối tượng, số và boolean mới có thể được truyền và trả về.

  3. Phạm vi OAuth. API chỉ có thể thực thi các tập lệnh có ít nhất một phạm vi bắt buộc. Điều này có nghĩa là bạn không thể sử dụng API để gọi một tập lệnh không yêu cầu uỷ quyền cho một hoặc nhiều dịch vụ.

  4. Không có trình kích hoạt. API không thể tạo trình kích hoạt Apps Script .