מדריך למתחילים: יצירת שלב של מחשבון באמצעות Google Apps Script

במדריך למתחילים הזה נסביר איך ליצור שלב מותאם אישית ב-Workspace Studio באמצעות Google Apps Script. השלב המותאם אישית מקבל שני מספרים ופעולה אריתמטית כקלט, מבצע את החישוב ומחזיר את התוצאה.

משתמש מגדיר את שלב המחשבון כחלק מסוכן.

איור 1: משתמש מגדיר את שלב המחשבון כחלק מסוכן.

מטרות

  • אפשר ליצור שלב מותאם אישית ל-Workspace Studio באמצעות Google Apps Script.
  • פורסים את השלב המותאם אישית בארגון Google Workspace שלכם.
  • בודקים את השלב המותאם אישית ב-Workspace Studio.

דרישות מוקדמות

  • חשבון Google עם גישה ל-Workspace Studio.

הגדרת הסקריפט

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

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

    פתיחת הפרויקט

  2. לוחצים על סקירה כללית.

  3. בדף הסקירה הכללית, לוחצים על הסמל ליצירת עותק יצירת עותק.

  4. נותנים שם לעותק של פרויקט Apps Script:

    1. לוחצים על Copy of Calculator quickstart (עותק של מדריך למתחילים בנושא מחשבון).

    2. בשדה שם הפרויקט, כותבים Calculator quickstart.

    3. לוחצים על Rename.

אופציונלי: בדיקת קוד ההפעלה המהירה

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

אפשר גם לבדוק כל קובץ שהעתקתם בקטע הקודם:

appsscript.json

קובץ המניפסט. קובץ JSON מיוחד שמציין מידע בסיסי על הפרויקט שנדרש ל-Apps Script כדי להריץ את הסקריפט.

הצגת הקוד appsscript.json

{
  "timeZone": "America/Los_Angeles",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "addOns": {
    "common": {
      "name": "Calculator",
      "logoUrl": "https://www.gstatic.com/images/branding/productlogos/calculator_search/v1/web-24dp/logo_calculator_search_color_1x_web_24dp.png",
      "useLocaleFromApp": true
    },
    "flows": {
      "workflowElements": [
        {
          "id": "actionElement",
          "state": "ACTIVE",
          "name": "Calculate",
          "description": "Asks the user for two values and a math operation, then performs the math operation on the values and outputs the result.",
          "workflowAction": {
            "inputs": [
              {
                "id": "value1",
                "description": "value1",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "INTEGER"
                }
              },
              {
                "id": "value2",
                "description": "value2",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "INTEGER"
                }
              },
              {
                "id": "operation",
                "description": "operation",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "STRING"
                }
              }
            ],
            "outputs": [
              {
                "id": "result",
                "description": "Calculated result",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "INTEGER"
                }
              }
            ],
            "onConfigFunction": "onConfigCalculateFunction",
            "onExecuteFunction": "onExecuteCalculateFunction"
          }
        }
      ]
    }
  }
}
Calculator.gs

הגדרת שלב מותאם אישית ל-Google Workspace Studio. השלב שנקרא Calculate (חישוב) מקבל שני מספרים ופעולה כקלט ומחזיר את תוצאת החישוב.

הצגת הקוד Calculator.gs

/**
 * This script defines a custom step for Google Workspace Studio.
 * The step, named "Calculate", takes two numbers and an operation as input
 * and returns the result of the calculation.
 *
 * The script includes functions to:
 *
 * 1.  Define the configuration UI for the step using Card objects:
 *
 *     - `onConfigCalculateFunction()`: Generates the main configuration card.
 *     - Helper functions like `pushCard()`, `saveButton()` to build card components.
 *
 * 2.  Handle the execution of the step.
 *
 *     - `onExecuteCalculateFunction()`: Retrieves inputs, performs the calculation,
 *       and returns outputs.
 *
 * To learn more, see the following quickstart guide:
 * https://developers.google.com/workspace/add-ons/studio/quickstart
 */

/**
 * Creates an action response to push a new card onto the card stack.
 *
 * This function generates an action object that, when returned, causes the
 * provided card to be pushed onto the card stack, making it the currently
 * displayed card in the configuration UI.
 * @param {Object} card The Card object to push.
 * @return {Object} The action response object.
 */
function pushCard(card) {
  return {

      "action": {
        "navigations": [{
            "push_card": card
          }
        ]
      }  };  
}

/**
 * Creates an action response to update the currently displayed card.
 *
 * This function generates an action object that, when returned, causes the
 * currently displayed card to be replaced with the provided card in the
 * configuration UI.
 * @param {Object} card The Card object to update.
 * @return {Object} The render actions object.
 */
function updateCard(card) {
  return {
    "render_actions": {
      "action": {
        "navigations": [{
            "update_card": card
          }
        ]
      }
    }
  };
}

/**
 * Creates a button configuration object for saving the step.
 *
 * This function generates a button definition that, when clicked, triggers
 * a save action for the current step configuration.
 * @return {Object} The button widget object.
 */
function saveButton() {
  return {
      "text": "Save",
      "onClick": {
        "hostAppAction" : {
          "workflowAction" : {
            "saveWorkflowAction" : {}
          }
        }
      },
    };
}

/**
 * Creates a button configuration object for a refresh action.
 *
 * This function generates a button definition that, when clicked, triggers
 * a function to refresh the current card.
 * @param {string} functionName The name of the Apps Script function to call on click.
 * @return {Object} The button widget object.
 */
function refreshButton(functionName) {
  return {
      "text": "Refresh",
      "onClick": {
        "action" : {
          "function" : functionName
        }
      },
    };
}


/**
 * Generates and displays a configuration card for the sample calculation action.
 *
 * This function creates a card with input fields for two values and a dropdown
 * for selecting an arithmetic operation. The card also includes a "Save"
 * button to save the action configuration for the step.
 *
 * The input fields are configured to let the user select outputs from previous
 * steps as input values using the `hostAppDataSource` property.
 * This function is called when the user adds or edits the "Calculate" step in the UI.
 * @return {Object} The action response object containing the card to display.
 */
function onConfigCalculateFunction() {
  var card = {
    "sections": [
      {
        "header": "Action sample: Calculate",
        "widgets": [
          {
            "textInput": {
              "name": "value1",
              "label": "First value",
              "hostAppDataSource" : {
                "workflowDataSource" : {
                  "includeVariables" : true
                }
              }
            }
          },
          {
            "selectionInput": {
              "name": "operation",
              "label": "Operation",
              "type": "DROPDOWN",
              "items": [
                {
                  "text": "+",
                  "value": "+",
                },
                {
                  "text": "-",
                  "value": "-",
                },
                {
                  "text": "x",
                  "value": "x",
                },
                {
                  "text": "/",
                  "value": "/",
                }
              ]
            }
          },
          {
            "textInput": {
              "name": "value2",
              "label": "Second value",
              "hostAppDataSource" : {
                "workflowDataSource" : {
                  "includeVariables" : true
                }
              }
            }
          }
        ]
      }
    ]
  };
  return pushCard(card);
}

/**
 * Gets an integer value from variable data, handling both string and integer formats.
 *
 * This function attempts to extract an integer value from the provided variable data.
 * It checks if the data contains string values and, if so, parses the first string
 * as an integer. If integer values are present, it returns the first integer.
 * @param {Object} variableData The variable data object from the event.
 * @return {number} The extracted integer value.
 */
function getIntValue(variableData) {
  if (variableData.stringValues) {
    return parseInt(variableData.stringValues[0]);
  }
  return variableData.integerValues[0];
}

/**
* Returns output variables from a step.
*
* This function constructs an object that, when returned, sends the
* provided variable values as output from the current step.
* The variable values are logged to the console for debugging purposes.
*/
function outputVariables(variableDataMap) {
 const workflowAction = AddOnsResponseService.newReturnOutputVariablesAction()
   .setVariableDataMap(variableDataMap);

 const hostAppAction = AddOnsResponseService.newHostAppAction()
   .setWorkflowAction(workflowAction);

 const renderAction = AddOnsResponseService.newRenderActionBuilder()
   .setHostAppAction(hostAppAction)
   .build();

 return renderAction;
}

/**
 * Executes the calculation action based on the inputs from an event.
 *
 * This function retrieves input values ("value1", "value2") and the "operation"
 * from the event, performs the calculation, and returns the "result" and
 * "log" as output variables.
 * This function is called when the agent reaches this custom step.
 * @param {Object} event The event object passed by the runtime.
 * @return {Object} The output variables object.
 */
function onExecuteCalculateFunction(event) {
 console.log("output: " + JSON.stringify(event));
 var calculatedValue = 0;
 var value1 = event.workflow.actionInvocation.inputs["value1"].integerValues[0];
 var value2 = event.workflow.actionInvocation.inputs["value2"].integerValues[0];
 var operation = event.workflow.actionInvocation.inputs["operation"].stringValues[0];


 if (operation == "+") {
   calculatedValue = value1 + value2;
 } else if (operation == "-") {
   calculatedValue = value1 - value2;
 } else if (operation == "x") {
   calculatedValue = value1 * value2;
 } else if (operation == "/") {
   calculatedValue = value1 / value2;
 }

 const variableDataMap = { "result": AddOnsResponseService.newVariableData().addIntegerValue(calculatedValue) };

 return outputVariables(variableDataMap);
}

פריסה ובדיקה של השלב

כדי לבדוק את השלב, מגדירים פריסת בדיקה לתוסף, מוסיפים את השלב לסוכן ומריצים את הסוכן.

  1. מגדירים פריסת בדיקה לתוסף:

    1. פותחים את פרויקט הסקריפט בכלי לעריכת סקריפטים של Apps Script.
    2. לוחצים על פריסה > בדיקת פריסות.
    3. לוחצים על התקנה.
    4. למטה, לוחצים על סיום.

    אתם יכולים לשתף את פרויקט Apps Script עם חשבון של משתמשים אחרים (נדרשת גישת עריכה) כדי לאפשר להם לבדוק את התוסף. לאחר מכן מבקשים מהמשתמשים לפעול לפי השלבים הקודמים.

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

    מידע נוסף על פריסות לצורך בדיקה זמין במאמר בנושא התקנה של תוסף שלא פורסם.

  2. פותחים את Agents (סוכנים).

  3. יוצרים סוכן שכולל את השלב:

    1. לוחצים על סוכן חדש.
    2. בוחרים איך הסוכן יתחיל. כשבודקים שלב, בוחרים סימן לתחילת פעולה שאפשר להפעיל לבד, כמו שליחת אימייל לעצמכם. אם השלב דורש משתנה קלט, צריך להגדיר את משתנה הקלט כחלק מהפלט של ה-starter.
    3. לוחצים על הוספת שלב. בוחרים את השלב שיצרתם או עדכנתם, שנקרא חישוב.
    4. מגדירים את השלב. בשלב החישוב, בוחרים שני ערכים ופעולה מתמטית. השלב נשמר באופן אוטומטי.
    5. כדי לבדוק את הפלט של השלב, מוסיפים עוד שלב. לדוגמה, כדי להוסיף פלט להודעת אימייל, אפשר להוסיף את השלב שליחת הודעה של Gmail. בקטע הודעה, לוחצים על משתנים ובוחרים את הפלט של השלב. בשלב החישוב, בוחרים באפשרות משתנים > שלב 2: תוצאה מחושבת > תוצאה מחושבת. המשתנה מופיע כצ'יפ בשדה הודעה.
    6. לוחצים על הפעלה. הסוכן מוכן להפעלה.
  4. מפעילים את הסוכן על ידי הפעלת הסימן לתחילת הפעולה של הסוכן. לדוגמה, אם הסוכן מתחיל לפעול כשמתקבל אימייל, שולחים לעצמכם אימייל.

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

השלבים הבאים

יצרתם ובדקתם בהצלחה שלב מותאם אישית ל-Workspace Studio. מעכשיו אפשר: