הפעלת פונקציות באמצעות Google Apps Script API

‫Apps Script API מספק שיטה scripts.run שמבצעת מרחוק פונקציה ספציפית של Google Apps Script. אתם יכולים להשתמש בשיטה הזו באפליקציית שיחות כדי להפעיל פונקציה באחד מפרויקטי הסקריפטים שלכם מרחוק ולקבל תשובה.

דרישות

לפני שאפליקציה לביצוע שיחות יכולה להשתמש בשיטה scripts.run, צריך:

  • פורסים את פרויקט הסקריפט כממשק API ניתן להפעלה. אפשר לפרוס פרויקטים, לבטל את הפריסה שלהם ולפרוס אותם מחדש לפי הצורך.

  • צריך לספק אסימון OAuth עם היקף מתאים לביצוע. אסימון ה-OAuth הזה צריך לכלול את כל ההיקפים שבהם נעשה שימוש בסקריפט, ולא רק את ההיקפים שבהם נעשה שימוש בפונקציה שנקראת. הרשימה המלאה של היקפי ההרשאות מופיעה בחומר העזר בנושא שיטות.

  • מוודאים שלסקריפט וללקוח OAuth2 של האפליקציה שמבצעת את הקריאה יש פרויקט משותף ב-Google Cloud. פרויקט בענן צריך להיות פרויקט בענן רגיל. פרויקטים שנוצרים כברירת מחדל עבור פרויקטים ב-Apps Script לא מספיקים. אפשר להשתמש בפרויקט חדש בענן או בפרויקט קיים.

  • מפעילים את Google Apps Script API בפרויקט בענן.

השיטה scripts.run

השיטה scripts.run דורשת את הפרטים הבאים:

אפשר גם להגדיר את הסקריפט כך שיפעל במצב פיתוח. במצב הזה, הסקריפט מופעל עם הגרסה השמורה האחרונה של פרויקט הסקריפט, ולא עם הגרסה האחרונה שפריסתם. כדי לעשות את זה, מגדירים את הערך הבוליאני devMode בגוף הבקשה ל-true. רק הבעלים של הסקריפט יכול להריץ אותו במצב פיתוח.

טיפול בסוגי נתונים של פרמטרים

השימוש בשיטה scripts.run של Apps Script API בדרך כלל כולל שליחת נתונים ל-Apps Script כפרמטרים של פונקציה וקבלת נתונים בחזרה כערכי החזרה של פונקציה. ה-API יכול לקבל ולהחזיר רק ערכים עם סוגים בסיסיים: מחרוזות, מערכים, אובייקטים, מספרים וערכים בוליאניים. אי אפשר להעביר אל פרויקט הסקריפט או ממנו אובייקטים מורכבים יותר של Apps Script, כמו Document או Sheet, באמצעות ה-API.

כשאפליקציית השיחות שלכם כתובה בשפה עם הקלדה חזקה כמו Java, היא מעבירה פרמטרים כרשימה או כמערך של אובייקטים גנריים שתואמים לסוגים הבסיסיים האלה. במקרים רבים, אפשר להחיל המרות מסוג באופן אוטומטי. לדוגמה, אפשר להעביר לפונקציה שמקבלת פרמטר מספרי אובייקט 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. זה יכול להיות פרויקט קיים או פרויקט חדש שנוצר למטרה הזו. אחרי שיוצרים פרויקט בענן, צריך להעביר את פרויקט הסקריפט לשימוש בו.

שלב 2: פריסת הסקריפט כממשק API ניתן להפעלה

  1. פותחים את פרויקט Apps Script עם הפונקציות שרוצים להשתמש בהן.
  2. בפינה השמאלית העליונה, לוחצים על פריסה > פריסה חדשה.
  3. בתיבת הדו-שיח שנפתחת, לוחצים על הפעלה של סוגי פריסה > API Executable.
  4. בתפריט הנפתח 'למי יש גישה', בוחרים את המשתמשים שמורשים להפעיל את הפונקציות של הסקריפט באמצעות Apps Script API.
  5. לוחצים על פריסה.

שלב 3: הגדרת אפליקציית השיחות

לפני השימוש ב-API, באפליקציה שמבצעת את הקריאה צריך להפעיל את Apps Script API ולהגדיר פרטי כניסה ל-OAuth. כדי לעשות את זה, צריך גישה לפרויקט בענן.

  1. מגדירים את פרויקט בענן שבו משתמשים האפליקציה והסקריפט של השיחות:
    1. מפעילים את Apps Script API בפרויקט בענן.
    2. הגדרת מסך ההסכמה ל-OAuth.
    3. יצירת פרטי כניסה של OAuth.
  2. פותחים את פרויקט התסריט ובצד ימין לוחצים על סקירה כללית .
  3. בקטע Project OAuth scopes (היקפי OAuth של הפרויקט), רושמים את כל ההיקפים שהסקריפט דורש.
  4. בקוד האפליקציה ששולחת את הקריאה, יוצרים אסימון גישה מסוג OAuth של סקריפט לקריאה ל-API. זה לא אסימון שממשק ה-API עצמו משתמש בו, אלא אסימון שהסקריפט דורש בזמן ההפעלה. הוא צריך להיבנות באמצעות מזהה הלקוח של פרויקט בענן וההיקפים של הסקריפט שרשמתם.

    ספריות הלקוח של Google יכולות לעזור ליצור את האסימון הזה ולטפל ב-OAuth עבור האפליקציה. בדרך כלל הן מאפשרות ליצור אובייקט 'פרטי כניסה' ברמה גבוהה יותר באמצעות היקפי ההרשאות של הסקריפט. במאמר הפעלות מהירות של Apps Script API יש דוגמאות ליצירת אובייקט של פרטי כניסה מרשימה של היקפי הרשאות.

שלב 4: שולחים את בקשת scripts.run

אחרי שמגדירים את אפליקציית השיחות, אפשר לבצע שיחות scripts.run:

  1. יוצרים בקשת API באמצעות מזהה הסקריפט, שם הפונקציה וכל הפרמטרים הנדרשים.
  2. מבצעים את הקריאה scripts.run וכוללים את אסימון ה-OAuth של הסקריפט שיצרתם בכותרת (אם משתמשים בבקשת POST בסיסית) או משתמשים באובייקט פרטי הכניסה שיצרתם באמצעות היקפי ההרשאות של הסקריפט.
  3. מאפשרים לסקריפט לסיים את ההרצה. הסקריפטים יכולים לפעול עד שש דקות, ולכן האפליקציה צריכה לאפשר זאת.
  4. בסיום, פונקציית הסקריפט עשויה להחזיר ערך, שה-API מעביר בחזרה לאפליקציה אם הערך הוא מסוג נתמך.

דוגמאות לקריאות ל-API של scripts.run מפורטות בקטע הבא.

כדי לרענן את טוקן הגישה, מוסיפים את קטע הקוד הבא לפני בקשת ה-API של scripts.run:

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 שכוללים את היקף ההרשאות הבא ב-Drive:

  • 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()

מגבלות

ל-Apps Script API יש את המגבלות הבאות:

  1. פרויקט בענן. הסקריפט שמופעל והאפליקציה שמפעילה אותו צריכים להיות באותו פרויקט בענן. הפרויקט בענן צריך להיות פרויקט Cloud רגיל. פרויקטים שמוגדרים כברירת מחדל עבור פרויקטים ב-Apps Script לא מספיקים.

  2. פרמטרים בסיסיים וסוגי החזרה. ה-API לא יכול להעביר או להחזיר אובייקטים ספציפיים ל-Apps Script (כמו Documents,‏ Blobs,‏ Calendars,‏ Drive Files וכו') לאפליקציה. אפשר להעביר ולהחזיר רק סוגים בסיסיים כמו מחרוזות, מערכים, אובייקטים, מספרים וערכים בוליאניים.

  3. היקפי הרשאות OAuth. ממשק ה-API יכול להריץ רק סקריפטים שיש להם לפחות היקף אחד נדרש. המשמעות היא שאי אפשר להשתמש ב-API כדי לקרוא לסקריפט שלא נדרשת בו הרשאה לשירות אחד או יותר.

  4. ללא טריגרים. אי אפשר ליצור גורמים מפעילים של Apps Script באמצעות ה-API.