Hướng dẫn bắt đầu nhanh này hướng dẫn bạn cách tạo một bước tuỳ chỉnh cho Workspace Studio bằng Google Apps Script. Bước tuỳ chỉnh này lấy hai số và một phép toán số học làm dữ liệu đầu vào, thực hiện phép tính và xuất ra kết quả.
Mục tiêu
- Tạo bước tuỳ chỉnh cho Workspace Studio bằng Google Apps Script.
- Triển khai bước tuỳ chỉnh cho tổ chức Google Workspace của riêng bạn.
- Kiểm thử bước tuỳ chỉnh trong Workspace Studio.
Điều kiện tiên quyết
- Tài khoản Google có quyền truy cập vào Workspace Studio.
Thiết lập tập lệnh
Để thiết lập tập lệnh, hãy tạo một dự án Apps Script mới và thêm mã bắt đầu nhanh:
Nhấp vào nút sau để tạo một dự án Apps Script mới:
Đặt tên cho dự án Apps Script:
Nhấp vào Dự án không có tiêu đề.
Trong phần Tiêu đề dự án, hãy nhập
Calculator quickstart.Nhấp vào Đổi tên.
Bên cạnh tệp
Code.gs, hãy nhấp vào biểu tượng Thêm > Đổi tên. Đặt tênCalculatorcho tệp.Thay thế nội dung của
Calculator.gsbằng mã sau. Tệp này xác định một bước tuỳ chỉnh cho Google Workspace Studio có tên là "Calculate" (Tính toán), lấy hai số và một phép toán làm dữ liệu đầu vào rồi trả về kết quả của phép tính.Xem mã
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); }
Nhấp vào biểu tượng Cài đặt dự án rồi chọn hộp đánh dấu Hiển thị tệp kê khai "appsscript.json" trong trình chỉnh sửa.
Nhấp vào Editor (Trình chỉnh sửa) , mở tệp kê khai
appsscript.jsonrồi thay thế nội dung của tệp bằng mã sau:Xem mã
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" } } ] } } }
Nhấp vào biểu tượng Lưu .
Triển khai và kiểm thử bước của bạn
Để kiểm thử bước, hãy thiết lập một bản triển khai thử nghiệm cho tiện ích bổ sung, thêm bước vào một quy trình rồi chạy quy trình đó.
Thiết lập một bản triển khai thử nghiệm cho tiện ích bổ sung:
- Mở dự án tập lệnh trong trình chỉnh sửa Apps Script.
- Nhấp vào Deploy (Triển khai) > Test deployments (Bản triển khai thử nghiệm).
- Nhấp vào Install (Cài đặt).
- Ở dưới cùng, hãy nhấp vào Xong.
Bạn có thể cho phép người dùng khác kiểm thử tiện ích bổ sung bằng cách chia sẻ dự án Apps Script với tài khoản của họ (bạn cần có quyền chỉnh sửa). Sau đó, hãy nhắc người dùng làm theo các bước trước đó.
Sau khi cài đặt, tiện ích bổ sung sẽ có ngay trong Flows. Bạn có thể cần phải làm mới Flows thì mới thấy tiện ích bổ sung. Bạn cũng phải uỷ quyền cho tiện ích bổ sung trước khi sử dụng.
Để tìm hiểu thêm về các bản triển khai thử nghiệm, hãy xem bài viết Cài đặt tiện ích bổ sung chưa xuất bản.
Mở Flows.
Tạo một quy trình có bước của bạn:
- Nhấp vào Quy trình mới.
- Chọn cách bắt đầu quy trình. Nếu bước của bạn yêu cầu biến đầu vào, hãy định cấu hình biến đầu vào đó dưới dạng dữ liệu đầu ra của trình khởi động.
- Nhấp vào Thêm bước. Chọn bước bạn đã tạo hoặc cập nhật, có tên là Calculate (Tính toán).
- Định cấu hình bước của bạn. Đối với bước tính toán, hãy chọn hai giá trị và một phép toán. Bước này sẽ tự động lưu.
- Để kiểm tra kết quả của bước, hãy thêm một bước khác. Ví dụ: để thêm kết quả vào một tin nhắn trò chuyện trên Google Chat, hãy thêm bước Thông báo cho tôi trong Chat của Chat. Trong phần Thông báo, hãy nhấp vào Biến rồi chọn kết quả của bước. Đối với bước tính toán, hãy chọn Biến > Bước 2: Tính toán > Kết quả tính toán. Biến này sẽ xuất hiện dưới dạng một khối trong trường Tin nhắn.
- Nhấp vào Bật. Quy trình của bạn đã sẵn sàng chạy.
Chạy quy trình bằng cách kích hoạt điều kiện khởi động của quy trình. Ví dụ: nếu quy trình của bạn bắt đầu theo lịch biểu, thì quy trình đó sẽ chạy vào ngày và giờ đã chỉ định.
Xác minh rằng quy trình chạy như mong đợi. Kiểm tra nhật ký bằng cách truy cập vào thẻ Hoạt động của trình tạo quy trình. Để tìm hiểu cách tạo nhật ký tuỳ chỉnh trong thẻ Hoạt động, hãy xem bài viết Nhật ký hoạt động.
Các bước tiếp theo
Bạn đã tạo và thử nghiệm thành công một bước tuỳ chỉnh cho Workspace Studio. Hiện bạn có thể:
Tiếp tục tuỳ chỉnh bước này bằng cách đặt câu lệnh cho Gemini giúp bạn triển khai logic phức tạp hơn.
Tạo thẻ cấu hình để tuỳ chỉnh cấu hình bước.
Ghi nhật ký hoạt động và lỗi để ghi lại và khắc phục sự cố khi chạy bước.
Xem lại đối tượng sự kiện để xem lại tải trọng JSON mà luồng gửi và nhận khi các bước chạy.
Hãy thử tham gia lớp học lập trình Xây dựng các bước khởi động và hành động tuỳ chỉnh trong Workspace Studio để xây dựng một bước khởi động tuỳ chỉnh và một bước tuỳ chỉnh bằng Apps Script.