الردّ على أوامر تطبيق Google Chat

توضّح هذه الصفحة كيفية إعداد الطلبات والردّ عليها كتطبيق في Google Chat.

تساعد الأوامر المستخدمين في اكتشاف الميزات الرئيسية لتطبيق Chat واستخدامها. يمكن لتطبيقات Chat فقط الاطّلاع على محتوى الأمر. على سبيل المثال، إذا أرسل مستخدم رسالة باستخدام أمر يبدأ بشرطة مائلة، لن تظهر الرسالة إلا للمستخدم وتطبيق Chat.

لتحديد ما إذا كان عليك إنشاء أوامر، وفهم كيفية تصميم تفاعلات المستخدمين، يُرجى الاطّلاع على تحديد جميع تجارب المستخدمين.

أنواع أوامر تطبيقات Chat

يمكنك إنشاء أوامر تطبيقات Chat كأوامر تبدأ بشرطة مائلة أو أوامر سريعة أو إجراءات رسائل. لاستخدام كل نوع من الأوامر، يمكن للمستخدمين إجراء ما يلي:
  1. الأوامر التي تبدأ بشرطة مائلة: يمكن للمستخدمين اختيار أمر يبدأ بشرطة مائلة من القائمة أو كتابة شرطة مائلة (/) ثم نص محدّد مسبقًا، مثل /about. تتطلّب تطبيقات Chat عادةً نص وسيطة للأمر الذي يبدأ بشرطة مائلة.

    يمكنك إنشاء أمر يبدأ بشرطة مائلة إذا كان تطبيق Chat يتطلّب إدخالاً إضافيًا من المستخدم. على سبيل المثال، يمكنك إنشاء أمر يبدأ بشرطة مائلة باسم /search يتم تنفيذه بعد أن يُدخل المستخدم عبارة للبحث عنها، مثل /search receipts.

  2. الأوامر السريعة: يستخدم المستخدمون الأوامر من خلال فتح القائمة من قسم الردّ في رسالة محادثة. لاستخدام أمر، ينقر المستخدم على إضافة ويختار أمرًا من القائمة.

    يمكنك إنشاء أمر سريع إذا كان بإمكان تطبيق Chat الردّ على المستخدم على الفور بدون انتظار إدخال إضافي. على سبيل المثال، يمكنك إنشاء أمر سريع باسم صورة عشوائية يستجيب فورًا بصورة.

  3. إجراءات الرسائل: يستخدم المستخدمون إجراءات الرسائل من خلال تمرير مؤشر الماوس فوق رسالة والنقر على قائمة الخيارات الإضافية. لاستخدام أمر، يفتح المستخدم قائمة الخيارات الإضافية ويختار أمرًا من القائمة.

    يمكنك إنشاء إجراء رسالة إذا كان بإمكان تطبيق Chat تنفيذ إجراءات استنادًا إلى سياق الرسالة.

توضّح الصور التالية كيفية عثور المستخدمين على قائمة الأوامر التي تبدأ بشرطة مائلة والأوامر السريعة وإجراءات الرسائل:

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

HTTP

تطبيق Google Chat يتلقّى تفاعلات المستخدمين ويستجيب لها لإنشاء واحدة، أكمِل دليل البدء السريع لبروتوكول HTTP.

برمجة التطبيقات

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

إعداد الطلب

يشرح هذا القسم كيفية إكمال الخطوات التالية لإعداد أمر:

  1. أنشئ اسمًا ووصفًا للأمر.
  2. اضبط الأمر في وحدة تحكّم Google Cloud.
  3. اختياري: ربط الطلبات بالطلبات الأولية

تسمية الأمر ووصفه

اسم الأمر هو ما يكتبه المستخدمون أو يختارونه لاستدعاء تطبيق Chat. يظهر أيضًا وصف قصير أسفل الاسم، لتوجيه المستخدمين بشكل أكبر حول كيفية استخدام الأمر:

اسم الأمر الذي يبدأ بشرطة مائلة ووصفه
اسم ووصف أمر يبدأ بشرطة مائلة

عند اختيار اسم ووصف لطلبك، يُرجى مراعاة الاقتراحات التالية:

لتسمية أمر:

  • استخدِم كلمات أو عبارات قصيرة ووصفية وقابلة للتنفيذ لتوضيح الطلبات للمستخدم. على سبيل المثال، بدلاً من الاسم Create a reminder، استخدِم Remind me.
  • ننصحك باستخدام اسم فريد أو شائع لأمرك. إذا كان الأمر يصف تفاعلاً أو ميزة شائعة، يمكنك استخدام اسم شائع يتعرّف عليه المستخدمون ويتوقعونه، مثل Settings أو Feedback. بخلاف ذلك، حاوِل استخدام أسماء أوامر فريدة، لأنّه إذا كان اسم الأمر هو نفسه في تطبيقات Chat الأخرى، على المستخدم فلترة الأوامر المشابهة للعثور على الأمر الخاص بك واستخدامه.

لوصف أمر:

  • يجب أن يكون الوصف قصيرًا وواضحًا ليعرف المستخدمون ما يمكن توقّعه عند استخدام الأمر.
  • أعلِم المستخدمين إذا كانت هناك أي متطلبات تنسيق للطلب. على سبيل المثال، إذا أنشأت أمرًا يبدأ بشرطة مائلة يتطلّب نص وسيطة، يمكنك ضبط الوصف على عبارة مثل Remind me to do [something] at [time].
  • أعلِم المستخدمين بما إذا كان تطبيق Chat يردّ على الجميع في المساحة أو بشكل خاص على المستخدم الذي يستدعي الأمر. على سبيل المثال، بالنسبة إلى الطلب السريع About، يمكنك وصفه على النحو التالي: Learn about this app (Only visible to you).

ضبط الأمر في Google Cloud Console

لإنشاء أمر يبدأ بشرطة مائلة أو أمر سريع أو إجراء رسالة، عليك تحديد معلومات عن الأمر أو الإجراء في إعدادات تطبيق Chat في Google Chat API.

لضبط أمر في Google Chat API، أكمِل الخطوات التالية:

  1. في وحدة تحكّم Google Cloud، انقر على "القائمة " > واجهات برمجة التطبيقات والخدمات > واجهات برمجة التطبيقات والخدمات المفعَّلة > Google Chat API

    الانتقال إلى صفحة Google Chat API

  2. انقر على الإعداد.

  3. ضمن إعدادات الاتصال، انتقِل إلى المشغّلات وحدِّد تفاصيل نقطة النهاية. يجب استخدام هذا المشغّل في القسم التالي للرد على الأمر.

    1. عنوان URL لنقطة نهاية HTTP: يمكنك تحديد عنوان URL واحد شائع لنقطة نهاية HTTP هنا. بدلاً من ذلك، لاستخدام نقاط نهاية HTTP مختلفة لمشغّلات مختلفة، حدِّد نقطة النهاية مباشرةً في حقل أمر التطبيق.
    2. برمجة تطبيقات Google: أدخِل معرّف نشر "برمجة تطبيقات Google". سيتم استدعاء الدالة onAppCommand تلقائيًا. لاستخدام دالة مختلفة في "برمجة تطبيقات Google"، حدِّد اسم الدالة المخصّصة في حقل أمر التطبيق.
  4. ضمن الطلبات، انقر على إضافة طلب.

  5. أدخِل المعلومات التالية حول الأمر:

    1. رقم تعريف الطلب: رقم من 1 إلى 1000 يستخدمه تطبيق Chat للتعرّف على الطلب وعرض ردّ.
    2. الوصف: النص الذي يصف كيفية استخدام الأمر وتنسيقه يمكن أن يصل طول الأوصاف إلى 50 حرفًا.
    3. نوع الأمر: اختَر أمر سريع أو أمر يبدأ بشرطة مائلة أو إجراء الرسالة.
    4. حدِّد اسمًا للأمر:
      • اسم الأمر السريع: الاسم المعروض الذي يختاره المستخدمون من القائمة لتنفيذ الأمر. يمكن أن يتضمّن ما يصل إلى 50 حرفًا، بما في ذلك الرموز الخاصة. مثلاً: Remind me
      • اسم الأمر الذي يبدأ بشرطة مائلة: النص الذي يكتبه المستخدمون لاستدعاء الأمر في رسالة. يجب أن يبدأ بشرطة مائلة، وأن يحتوي على نص فقط، ويمكن أن يتألف من 50 حرفًا كحد أقصى. مثلاً: /remindMe
      • اسم إجراء الرسالة: الاسم المعروض الذي يختاره المستخدمون من القائمة لتنفيذ إجراء الرسالة. يمكن أن يتضمّن ما يصل إلى 50 حرفًا وأن يشمل أحرفًا خاصة. مثلاً: Remind me
  6. اختياري: رسالة إشعار التحميل: رسالة إشعار منبثقة تظهر للمستخدم أثناء تنفيذ إجراء الرسالة. لا يتوفّر إلا لإجراءات الرسائل التي لا تفتح مربّعات حوار.

  7. اختياري: إذا أردت أن يستجيب تطبيق Chat للأمر من خلال مربّع حوار، ضَع علامة في المربّع فتح مربّع حوار.

  8. انقر على حفظ.

تم الآن إعداد الأمر لتطبيق Chat.

ربط الطلبات بالطلبات الأوّلية

يمكنك عرض أوامرك كـ طلبات أوّلية ليراها المستخدمون كشرائح تفاعلية عند بدء رسالة مباشرة على الخاص فارغة مع تطبيق Chat.

لربط أمر بطلب أوّلي:

  1. تأكَّد من أنّ طلبك لا يتطلّب وسيطات مخصّصة إضافية (الطلبات التي تتضمّن بدون وسيطات أو وسيطات أساسية هي فقط المتوافقة كطلبات أوّلية).
  2. في وحدة تحكّم Google Cloud، انتقِل إلى صفحة الإعدادات في Chat API.
  3. ضمن الميزات التفاعلية > الطلبات الأولية، انقر على إضافة طلب.
  4. اضبط الترتيب (1-3) لترتيب العرض.
  5. ضمن اختيار النوع، اختَر موجّه الأوامر، ثم اختَر الأمر من القائمة المنسدلة.
  6. انقر على تم، ثم انقر على حفظ.

الرد على طلب

عندما يستخدم المستخدمون أمرًا، يتلقّى تطبيق Chat كائن حدث. تحتوي حمولة الحدث (event.chat.appCommandPayload) على عنصر appCommandPayload يتضمّن تفاصيل عن الأمر الذي تم استدعاؤه (بما في ذلك رقم تعريف الأمر ونوعه)، لكي تتمكّن من عرض ردّ مناسب. يتم إرسال كائن الحدث إلى نقطة نهاية HTTP أو دالة "برمجة تطبيقات Google" التي حدّدتها عند ضبط مشغّل أمر التطبيق.

رسالة خاصة لتطبيق Cymbal Labs في Chat. تشير الرسالة إلى أنّ تطبيق Chat تم إنشاؤه بواسطة Cymbal Labs وتشارك رابطًا يؤدي إلى المستندات ورابطًا للتواصل مع فريق الدعم.
يردّ تطبيق Chat بشكل خاص على الأمر الذي يبدأ بشرطة مائلة /help لشرح كيفية الحصول على الدعم.

الردّ على أمر يبدأ بشرطة مائلة أو أمر سريع

يعرض الرمز التالي مثالاً على تطبيق Chat يردّ على الأمر الذي يبدأ بشرطة مائلة /about برسالة نصية. للردّ على الأوامر التي تبدأ بشرطة مائلة أو الأوامر السريعة، يتعامل تطبيق Chat مع كائنات الأحداث (event.chat.appCommandPayload) من مشغّل أمر التطبيق. عندما تتضمّن حمولة كائن الحدث معرّف أمر مطابق، يعرض تطبيق Chat الإجراء DataActions مع كائن createMessageAction (hostAppDataAction.chatDataAction.createMessageAction):

Node.js

node/chat/avatar-app/index.js
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Handle requests from Google Workspace add on
 *
 * @param {Object} req Request sent by Google Chat
 * @param {Object} res Response to be sent back to Google Chat
 */
http('avatarApp', (req, res) => {
  const chatEvent = req.body.chat;
  let message;
  if (chatEvent.appCommandPayload) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: {
    message: message
  }}}});
});

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 * @return the response message object.
 */
function handleAppCommand(event) {
  switch (event.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return {
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/chat/avatar-app/main.py
# The ID of the slash command "/about".
# You must use the same ID in the Google Chat API configuration.
ABOUT_COMMAND_ID = 1

@functions_framework.http
def avatar_app(req: flask.Request) -> Mapping[str, Any]:
  """Handle requests from Google Workspace add on

  Args:
    flask.Request req: the request sent by Google Chat

  Returns:
    Mapping[str, Any]: the response to be sent back to Google Chat
  """
  chat_event = req.get_json(silent=True)["chat"]
  if chat_event and "appCommandPayload" in chat_event:
    message = handle_app_command(chat_event)
  else:
    message = handle_message(chat_event)
  return { "hostAppDataAction": { "chatDataAction": { "createMessageAction": {
      "message": message
  }}}}

def handle_app_command(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Responds to an APP_COMMAND event in Google Chat.

  Args:
    Mapping[str, Any] event: the event object from Google Chat

  Returns:
    Mapping[str, Any]: the response message object.
  """
  if event["appCommandPayload"]["appCommandMetadata"]["appCommandId"] == ABOUT_COMMAND_ID:
    return {
      "text": "The Avatar app replies to Google Chat messages.",
    }
  return {}

جافا

java/chat/avatar-app/src/main/java/com/google/chat/avatar/App.java
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
private static final int ABOUT_COMMAND_ID = 1;

private static final Gson gson = new Gson();

/**
 * Handle requests from Google Workspace add on
 * 
 * @param request the request sent by Google Chat
 * @param response the response to be sent back to Google Chat
 */
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
  JsonObject event = gson.fromJson(request.getReader(), JsonObject.class);
  JsonObject chatEvent = event.getAsJsonObject("chat");
  Message message;
  if (chatEvent.has("appCommandPayload")) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  JsonObject createMessageAction = new JsonObject();
  createMessageAction.add("message", gson.fromJson(gson.toJson(message), JsonObject.class));
  JsonObject chatDataAction = new JsonObject();
  chatDataAction.add("createMessageAction", createMessageAction);
  JsonObject hostAppDataAction = new JsonObject();
  hostAppDataAction.add("chatDataAction", chatDataAction);
  JsonObject dataActions = new JsonObject();
  dataActions.add("hostAppDataAction", hostAppDataAction);
  response.getWriter().write(gson.toJson(dataActions));
}

/**
 * Handles an APP_COMMAND event in Google Chat.
 *
 * @param event the event object from Google Chat
 * @return the response message object.
 */
private Message handleAppCommand(JsonObject event) throws Exception {
  switch (event.getAsJsonObject("appCommandPayload")
    .getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt()) {
    case ABOUT_COMMAND_ID:
      return new Message()
        .setText("The Avatar app replies to Google Chat messages.");
    default:
      return null;
  }
}

برمجة التطبيقات

apps-script/chat/avatar-app/Code.gs
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onAppCommand(event) {
  // Executes the app command logic based on ID.
  switch (event.chat.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return { hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
        text: 'The Avatar app replies to Google Chat messages.'
      }}}}};
  }
}

لاستخدام عينة التعليمات البرمجية هذه، استبدِل ABOUT_COMMAND_ID برقم تعريف الأمر الذي حدّدته عند إعداد الأمر في Chat API.

الرد على إجراء رسالة

يعرض الرمز التالي مثالاً على تطبيق Chat يردّ على إجراء الرسالة تذكيري برسالة نصية. للردّ على إجراءات الرسائل، يتعامل تطبيق Chat مع كائنات الأحداث من مشغّل طلب التطبيق. عندما تتضمّن حمولة كائن الحدث معرّف أمر إجراء الرسالة، يعرض تطبيق Chat الإجراء DataActions مع كائن createMessageAction:

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return res.json({
      "hostAppDataAction": {
        "chatDataAction": {
          "createMessageAction": {
            "message": {
              "text": `Setting a reminder for message: "${messageText}"`
            }
          }
        }
      }
    });
  }
}

Python

def on_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    payload = event.get('chat', {}).get('appCommandPayload', {})
    metadata = payload.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = payload.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "hostAppDataAction": {
                "chatDataAction": {
                    "createMessageAction": {
                        "message": {
                            "text": f'Setting a reminder for message: "{message_text}"'
                        }
                    }
                }
            }
        }

جافا

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void onAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject payload = event.getAsJsonObject("chat").getAsJsonObject("appCommandPayload");
  JsonObject metadata = payload.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = payload.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);

      JsonObject createMessageAction = new JsonObject();
      createMessageAction.add("message", responseMessage);

      JsonObject chatDataAction = new JsonObject();
      chatDataAction.add("createMessageAction", createMessageAction);

      JsonObject hostAppDataAction = new JsonObject();
      hostAppDataAction.add("chatDataAction", chatDataAction);

      JsonObject finalResponse = new JsonObject();
      finalResponse.add("hostAppDataAction", hostAppDataAction);

      response.getWriter().write(finalResponse.toString());
    }
  }
}

برمجة التطبيقات

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return CardService.newChatResponseBuilder()
        .setText("Setting a reminder for message: " + messageText)
        .build();
  }
}

لاستخدام عينة التعليمات البرمجية هذه، استبدِل REMIND_ME_COMMAND_ID بمعرّف الأمر الذي حدّدته عند ضبط الأمر في Chat API.

اختبار الأمر

لاختبار الأمر والرمز، يُرجى الاطّلاع على اختبار الميزات التفاعلية لتطبيقات Google Chat.

للتعرّف على كيفية اختبار الأمر واستخدامه في واجهة مستخدم Chat، يُرجى الاطّلاع على مقالة استخدام التطبيقات في Google Chat في مستندات مساعدة Google Chat.

تطبيقات Chat التي ليست إضافات: الاستجابة للأوامر

تنطبق المستندات التالية على تطبيقات Chat التي ليست إضافات Google Workspace. لنقل تطبيق Chat ليس إضافة، يُرجى الاطّلاع على المقالة تحويل تطبيق Google Chat إلى إضافة Google Workspace.

عندما يستخدم المستخدمون أمرًا، يتلقّى تطبيق Chat الذي ليس إضافةً حدث تفاعل ويمكنه الردّ من خلال عرض عنصر Message مباشرةً. تحتوي حمولة الحدث على بيانات وصفية تتضمّن تفاصيل عن الأمر الذي تم استدعاؤه (بما في ذلك معرّف الأمر ونوعه)، لكي تتمكّن من إرسال ردّ مناسب.

للردّ على كل نوع من الطلبات في تطبيق Chat ليس إضافة، عليك التعامل مع أنواع الأحداث المختلفة وعناصر البيانات الوصفية في حمولة الحدث:

نوع الطلب نوع الحدث البيانات الوصفية للأوامر
أمر يبدأ بشرطة مائلة MESSAGE message.slashCommand أو message.annotation.slashCommand
الأمر السريع APP_COMMAND appCommandMetadata
إجراء مقترح APP_COMMAND appCommandMetadata

الردّ على أمر يبدأ بشرطة مائلة

يعرض الرمز التالي مثالاً على تطبيق Chat ليس إضافة يردّ على الأمر الذي يبدأ بشرطة مائلة /about. يتعامل تطبيق Chat مع أحداث التفاعل MESSAGE، ويرصد ما إذا كان حدث التفاعل يحتوي على معرّف الطلب المطابق، ويعرض عنصر Message خاصًا:

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

برمجة التطبيقات

apps-script/avatar-app/avatar-app.gs
// Checks for the presence of a slash command in the message.
if (event.message.slashCommand) {
  // Executes the slash command logic based on its ID.
  // Slash command IDs are set in the Google Chat API configuration.
  switch (event.message.slashCommand.commandId) {
    case ABOUT_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

جافا

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

استبدِل ABOUT_COMMAND_ID برقم تعريف الأمر الذي حدّدته عند ضبط الأمر في وحدة تحكّم Google Cloud.

الردّ على طلب سريع

يعرض الرمز التالي مثالاً على تطبيق Chat ليس إضافة يردّ على الأمر السريع مساعدة. يتعامل تطبيق Chat مع أحداث التفاعل APP_COMMAND، ويرصد ما إذا كان حدث التفاعل يحتوي على معرّف الطلب المطابق، ويعرض عنصر Message خاصًا:

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

برمجة التطبيقات

apps-script/avatar-app/avatar-app.gs
/**
 * Handles the APP_COMMAND event type. This function is triggered when a user
 * interacts with a quick command within the Google Chat app.  It responds
 * based on the command ID.
 *
 * @param {Object} event The event object from Google Chat, containing details
 *     about the app command interaction.  It includes information like the
 *     command ID and the user who triggered it.
 */
function onAppCommand(event) {
  // Executes the quick command logic based on its ID.
  // Command IDs are set in the Google Chat API configuration.
  switch (event.appCommandMetadata.appCommandId) {
    case HELP_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

جافا

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

استبدِل HELP_COMMAND_ID برقم تعريف الأمر الذي حدّدته عند ضبط الأمر في وحدة تحكّم Google Cloud.

الرد على إجراء رسالة

يعرض الرمز التالي مثالاً على تطبيق Chat ليس إضافة يردّ على إجراء الرسالة تذكيري. يتعامل تطبيق Chat مع أحداث التفاعل APP_COMMAND، ويكتشف ما إذا كان حدث التفاعل يحتوي على معرّف الأمر المطابق، ويعرض عنصر Message خاص:

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function handleAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  // Use appCommandType to detect message actions.
  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return res.send({
      text: `Setting a reminder for this message: "${messageText}"`
    });
  }
}

برمجة التطبيقات

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return { "text": "Setting a reminder for message: " + messageText };
  }
}

Python

def handle_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    metadata = event.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = event.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "text": f'Setting a reminder for message: "{message_text}"'
        }

جافا

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void handleAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject metadata = event.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = event.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);
      response.getWriter().write(responseMessage.toString());
    }
  }
}

استبدِل REMIND_ME_COMMAND_ID برقم تعريف الأمر الذي حدّدته عند ضبط الأمر في وحدة تحكّم Google Cloud.