本快速入門導覽課程說明如何使用 Google Apps Script,為 Workspace Studio 建立自訂步驟。自訂步驟會將兩個數字和一個算術運算做為輸入內容,執行計算並輸出結果。
目標
- 使用 Google Apps Script 為 Workspace Studio 建立自訂步驟。
- 將自訂步驟部署至自己的 Google Workspace 機構。
- 在 Workspace Studio 測試自訂步驟。
必要條件
- 可存取 Workspace Studio 的 Google 帳戶。
設定指令碼
如要設定指令碼,請建立新的 Apps Script 專案,並新增快速入門導覽課程程式碼:
按一下下列按鈕,建立新的 Apps Script 專案:
為 Apps Script 專案命名:
按一下「未命名專案」。
在「Project title」(專案名稱) 中輸入
Calculator quickstart。按一下 [重新命名]。
按一下
Code.gs檔案旁的「更多」圖示 >「重新命名」。將檔案命名為Calculator。將
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 flow 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); }
按一下「專案設定」,然後勾選「在編輯器中顯示『appsscript.json』資訊清單檔案」核取方塊。
按一下「Editor」(編輯器) ,開啟
appsscript.json資訊清單檔案,並將內容替換為下列程式碼:查看
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" } } ] } } }
按一下「Save」(儲存) 圖示 。
部署及測試步驟
如要測試步驟,請為外掛程式設定測試部署作業,將步驟新增至流程,然後執行流程。
為外掛程式設定測試部署作業:
- 在 Apps Script 編輯器中開啟指令碼專案。
- 依序點選「部署」>「測試部署作業」。
- 按一下 [安裝]。
- 按一下底部的「完成」。
您可以與其他使用者的帳戶共用 Apps Script 專案 (需要編輯權限),讓他們測試外掛程式。然後提示使用者按照上述步驟操作。
安裝完成後,即可立即在 Flows 中使用外掛程式。您可能需要重新整理 Flows,外掛程式才會顯示。您也必須先授權外掛程式,才能使用。
如要進一步瞭解測試部署作業,請參閱「安裝未發布的外掛程式」。
開啟 Flow。
建立包含步驟的流程:
- 按一下「 新流程」。
- 選取流程的啟動方式。如果步驟需要輸入變數,請將輸入變數設為啟動器的輸出內容。
- 按一下「新增步驟」圖示 ,選取您建立或更新的步驟,名為「Calculate」。
- 設定步驟。在計算步驟中,選擇兩個值和一項數學運算。系統會自動儲存步驟。
- 如要測試步驟的輸出內容,請新增另一個步驟。舉例來說,如要將輸出內容新增至 Google Chat 即時通訊訊息,請新增 Chat 的「在 Chat 中通知我」步驟。在「Message」中,按一下 「Variables」,然後選取步驟的輸出內容。在計算步驟中,依序選取「 變數」>「步驟 2:計算」>「計算結果」。變數會以方塊形式顯示在「Message」(訊息) 欄位中。
- 按一下「啟用」。流程已可執行。
觸發啟動條件,執行流程。舉例來說,如果工作流程是依排程啟動,就會在指定日期和時間執行。
確認流程是否如預期執行。如要查看記錄,請前往流程建構工具的「Activity」(活動) 分頁。如要瞭解如何在「活動」分頁中建立自訂記錄,請參閱「活動記錄」。
後續步驟
您已成功建立及測試 Workspace Studio 的自訂步驟。您現在可以進行下列操作:
繼續提示 Gemini 自訂步驟,協助您實作更複雜的邏輯。
建構設定資訊卡,自訂步驟設定。
記錄活動和錯誤,以便記錄及排解步驟執行問題。
查看事件物件,瞭解流程在執行步驟時傳送及接收的 JSON 酬載。
請試試程式碼實驗室「建構自訂 Workspace Studio 啟動器和動作步驟」,瞭解如何使用 Apps Script 建構自訂啟動器和自訂步驟。