クイックスタート: Google Apps Script を使用して計算機ステップを作成する

このクイックスタートでは、Google Apps Script を使用して Workspace Studio のカスタム ステップを作成する方法について説明します。カスタムステップは、2 つの数値と算術演算を入力として受け取り、計算を実行して結果を出力します。

Workspace Studio の計算ステップカード。2 つの数値入力フィールドと、算術演算のプルダウン メニューが表示されている。
図 1: ユーザーがフローの一部として計算ステップを構成する。

目標

  • Google Apps Script を使用して Workspace Studio のカスタム ステップを作成します。
  • カスタム ステップを独自の Google Workspace 組織にデプロイします。
  • Workspace Studio でカスタム ステップをテストします。

前提条件

  • Workspace Studio にアクセスできる Google アカウント。

スクリプトを設定する

スクリプトを設定するには、新しい Apps Script プロジェクトを作成し、クイックスタート コードを追加します。

  1. 次のボタンをクリックして、新しい Apps Script プロジェクトを作成します。

    プロジェクトを作成する

  2. Apps Script プロジェクトに名前を付けます。

    1. [無題のプロジェクト] をクリックします。

    2. [プロジェクトのタイトル] に「Calculator quickstart」と入力します。

    3. [名前を変更] をクリックします。

  3. Code.gs ファイルの横にあるその他アイコン > [名前を変更] をクリックします。ファイルに Calculator という名前を付けます。

  4. Calculator.gs の内容を次のコードに置き換えます。このファイルは、2 つの数値と演算を入力として受け取り、計算結果を返す「Calculate」という名前の Google Workspace Studio のカスタム ステップを定義します。

    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);
    }
  5. [プロジェクト設定] をクリックし、[「appsscript.json」マニフェスト ファイルをエディタで表示する] チェックボックスをオンにします。

  6. [エディタ] をクリックし、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"
              }
            }
          ]
        }
      }
    }
  7. [保存] をクリックします。

ステップをデプロイしてテストする

ステップをテストするには、アドオンのテストデプロイを設定し、ステップをフローに追加して、フローを実行します。

  1. アドオンのテストデプロイを設定します。

    1. Apps Script エディタでスクリプト プロジェクトを開きます。
    2. [デプロイ] > [デプロイをテスト] をクリックします。
    3. [インストール] をクリックします。
    4. 下部の [完了] をクリックします。

    Apps Script プロジェクトを他のユーザーのアカウントと共有することで、他のユーザーにアドオンをテストしてもらうことができます(編集権限が必要です)。次に、上記の手順を行うようユーザーに促します。

    インストールすると、アドオンは Flows ですぐに使用できるようになります。アドオンが表示される前に、Flows を更新する必要がある場合があります。また、アドオンを使用する前に承認する必要があります。

    テストデプロイの詳細については、未公開のアドオンをインストールするをご覧ください。

  2. [Flows] を開きます。

  3. ステップを含むフローを作成します。

    1. [新しいフロー] をクリックします。
    2. フローの開始方法を選択します。ステップに入力変数が必要な場合は、入力変数をスターターの出力の一部として構成します。
    3. [ステップを追加] をクリックします。作成または更新したステップ(Calculate)を選択します。
    4. ステップを構成します。計算ステップでは、2 つの値と数学演算を選択します。ステップは自動的に保存されます。
    5. ステップの出力をテストするには、別のステップを追加します。たとえば、Google Chat メッセージに出力を追加するには、Chat の [Chat で通知する] ステップを追加します。[メッセージ] で、 [変数] をクリックし、ステップの出力を選択します。計算ステップでは、変数 > ステップ 2: 計算 > 計算結果を選択します。変数は [メッセージ] フィールドにチップとして表示されます。
    6. [有効にする] をクリックします。フローの実行準備が整いました。
  4. フローの開始条件をトリガーしてフローを実行します。たとえば、フローがスケジュールで開始される場合、指定した日時に実行されます。

  5. フローが想定どおりに実行されることを確認します。フロービルダーの [アクティビティ] タブにアクセスして、ログを確認します。[アクティビティ] タブでカスタムログを作成する方法については、アクティビティ ログをご覧ください。

次のステップ

Workspace Studio のカスタム ステップを作成してテストしました。以下の操作を行えます。