بدء الاستخدام السريع: إنشاء خطوة آلة حاسبة باستخدام "برمجة تطبيقات Google"

يعلّمك هذا الدليل السريع كيفية إنشاء خطوة مخصّصة في Workspace Studio باستخدام "برمجة تطبيقات Google". تتلقّى الخطوة المخصّصة رقمَين وعملية حسابية كمدخلات، وتُجري العملية الحسابية، ثم تعرض النتيجة.

يضبط المستخدم خطوة الآلة الحاسبة كجزء من وكيل.

الشكل 1: يضبط المستخدم خطوة الآلة الحاسبة كجزء من وكيل.

الأهداف

  • إنشاء خطوة مخصّصة في Workspace Studio باستخدام Google Apps Script
  • نشر الخطوة المخصّصة في مؤسسة Google Workspace الخاصة بك
  • اختبِر الخطوة المخصّصة في Workspace Studio.

المتطلبات الأساسية

  • حساب Google لديه إذن الوصول إلى Workspace Studio

إعداد النص البرمجي

لإعداد النص البرمجي، أنشئ مشروعًا جديدًا في "برمجة تطبيقات Google"، ثم اربطه بمشروعك على السحابة الإلكترونية.

  1. انقر على الزر التالي لفتح مشروع بدء سريع للآلة الحاسبة في "برمجة تطبيقات Google".

    فتح المشروع

  2. انقر على نظرة عامة.

  3. في صفحة النظرة العامة، انقر على رمز إنشاء نسخة إنشاء نسخة.

  4. أدخِل اسمًا لنسخة مشروع "برمجة التطبيقات Google":

    1. انقر على نسخة من دليل البدء السريع في الآلة الحاسبة.

    2. في عنوان المشروع، اكتب Calculator quickstart.

    3. انقر على إعادة تسمية.

اختياري: مراجعة رمز التشغيل السريع

في القسم السابق، نسخت مشروعًا كاملاً على Apps Script يتضمّن جميع رموز التطبيق المطلوبة لخطوة الوكيل المخصّصة، لذا ليس عليك نسخ كل ملف ولصقه.

يمكنك اختياريًا مراجعة كل ملف نسخته في القسم السابق هنا:

appsscript.json

ملف البيان ملف JSON خاص يحدّد معلومات أساسية عن المشروع تحتاجها "برمجة تطبيقات Google" لتشغيل النص البرمجي.

عرض رمز 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. تتلقّى الخطوة، التي تحمل الاسم "حساب"، رقمَين وعملية كمدخلات وتعرض نتيجة الحساب.

عرض رمز 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 مع حساباتهم (يجب منحهم إذن التعديل). بعد ذلك، اطلب من المستخدمين اتّباع الخطوات السابقة.

    بعد تثبيت الوظيفة الإضافية، ستتوفّر على الفور في "الوكلاء". قد تحتاج إلى إعادة تحميل الوكلاء قبل ظهور الإضافة. يجب أيضًا تفويض الإضافة قبل استخدامها.

    لمزيد من المعلومات عن عمليات النشر التجريبية، اطّلِع على مقالة تثبيت إضافة غير منشورة.

  2. افتح "الوكلاء".

  3. أنشِئ وكيلاً يتضمّن خطوتك:

    1. انقر على وكيل جديد.
    2. اختَر طريقة بدء تشغيل الوكيل. عند اختبار خطوة، اختَر إجراء تفعيل يمكنك تنفيذه بنفسك، مثل إرسال رسالة إلكترونية إلى نفسك. إذا كانت خطوتك تتطلّب متغيّر إدخال، اضبط متغيّر الإدخال كجزء من ناتج المشغّل.
    3. انقر على إضافة خطوة. اختَر الخطوة التي أنشأتها أو عدّلتها، والتي تُسمى الحساب.
    4. اضبط خطوتك. بالنسبة إلى خطوة الحساب، اختَر قيمتَين وعملية حسابية. يتم حفظ الخطوة تلقائيًا.
    5. لاختبار ناتج الخطوة، أضِف خطوة أخرى. على سبيل المثال، لإضافة ناتج إلى رسالة إلكترونية، يمكنك إضافة خطوة إرسال رسالة في Gmail. في الرسالة، انقر على المتغيرات واختَر ناتج الخطوة. بالنسبة إلى خطوة الحساب، اختَر المتغيرات > الخطوة 2: النتيجة المحسوبة > النتيجة المحسوبة. يظهر المتغيّر على شكل شريحة في حقل الرسالة.
    6. انقروا على تفعيل. الوكيل جاهز للتنفيذ.
  4. شغِّل الوكيل من خلال تفعيل إجراء التفعيل الخاص به. على سبيل المثال، إذا كان وكيلك يبدأ العمل عند تلقّي رسالة إلكترونية، أرسِل لنفسك رسالة إلكترونية.

  5. تأكَّد من أنّ الوكيل يعمل على النحو المتوقّع. يمكنك الاطّلاع على السجلات من خلال الانتقال إلى علامة التبويب النشاط في "أداة إنشاء الوكيل". لمعرفة كيفية إنشاء سجلّات مخصّصة في علامة التبويب "النشاط"، اطّلِع على سجلّات الأنشطة.

الخطوات التالية

لقد أنشأت خطوة مخصّصة واختبرتها بنجاح في Workspace Studio. ويمكنك الآن: