پاسخ دادن به فرمان‌های برنامه Google Chat

این صفحه نحوه راه‌اندازی و پاسخ دادن به فرمان‌ها را به‌عنوان برنامه Google Chat توضیح می‌دهد.

فرمان‌ها به کاربران کمک می‌کنند ویژگی‌های کلیدی برنامه Chat را کاوش و استفاده کنند. فقط برنامه‌های Chat می‌توانند محتوای فرمان را ببینند. برای مثال، اگر کاربری پیامی با فرمان خط مورب ارسال کند، پیام فقط برای کاربر و برنامه Chat قابل‌مشاهده است.

برای تصمیم‌گیری درباره اینکه آیا باید فرمان بسازید یا نه، و برای درک نحوه طراحی تعامل‌های کاربر، تعریف همه مسیرهای کاربر را ببینید.

انواع فرمان‌های برنامه Chat

می‌توانید فرمان‌های برنامه Chat را به‌صورت فرمان‌های خط مورب، فرمان‌های سریع، یا کنش‌های پیام بسازید. برای استفاده از هر نوع فرمان، کاربران می‌توانند کارهای زیر را انجام دهند:
  1. فرمان‌های خط مورب: کاربران می‌توانند فرمان خط مورب را از منو انتخاب کنند یا خط مورب (/) و سپس نوشتار ازپیش‌تعریف‌شده‌ای مثل /about را تایپ کنند. برنامه‌های Chat معمولاً برای فرمان خط مورب به نوشتار شناسه نیاز دارند.

    اگر برنامه Chat شما به ورودی بیشتری از کاربر نیاز دارد، فرمان خط مورب ایجاد کنید. برای مثال، می‌توانید فرمان خط موربی به‌نام /search ایجاد کنید که پس‌از وارد کردن عبارت موردنظر کاربر برای جستجو، مثلاً /search receipts، اجرا شود.

  2. فرمان‌های سریع: کاربران با باز کردن منو از قسمت پاسخ پیام Chat از فرمان‌ها استفاده می‌کنند. برای استفاده از فرمان، روی افزودن کلیک می‌کنند و فرمانی را از منو انتخاب می‌کنند.

    اگر برنامه Chat شما می‌تواند فوراً و بدون منتظر ماندن برای ورودی بیشتر به کاربر پاسخ دهد، فرمان سریع ایجاد کنید. برای مثال، می‌توانید فرمان سریعی به‌نام تصویر تصادفی ایجاد کنید که فوراً با تصویری پاسخ دهد.

  3. کنش‌های پیام: کاربران با نگه داشتن نشانگر روی پیام و کلیک کردن روی منوِ سه‌نقطه‌ای از کنش‌های پیام استفاده می‌کنند. برای استفاده از فرمان، منوِ سه‌نقطه‌ای را باز می‌کنند و فرمانی را از منو انتخاب می‌کنند.

    اگر برنامه Chat شما می‌تواند کنش‌هایی را براساس بافت پیام انجام دهد، کنش پیام ایجاد کنید.

تصاویر زیر نشان می‌دهند که کاربران چگونه منو فرمان‌های خط مورب و سریع و کنش‌های پیام را پیدا می‌کنند:

پیش‌نیازها

HTTP

برنامه Google Chat که تعامل‌های کاربر را دریافت می‌کند و به آن‌ها پاسخ می‌دهد. برای ساختن یکی، شروع سریع HTTP را تکمیل کنید.

Apps Script

برنامه Google Chat که تعامل‌های کاربر را دریافت می‌کند و به آن‌ها پاسخ می‌دهد. برای ساختن آن، شروع سریع Apps Script را تکمیل کنید.

راه‌اندازی فرمان

این بخش توضیح می‌دهد که چگونه مراحل زیر را برای راه‌اندازی یک فرمان تکمیل کنید:

  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

برای ایجاد فرمان خط مورب، فرمان سریع، یا کنش پیام، باید اطلاعات مربوط به فرمان یا کنش را در پیکربندی برنامه Chat برای Google Chat API مشخص کنید.

برای پیکربندی کردن فرمان در Google Chat API، مراحل زیر را تکمیل کنید:

  1. در کنسول Google Cloud، روی «منو» > میاناهای برنامه‌سازی کاربردی و سرویس‌ها > میاناهای برنامه‌سازی کاربردی و سرویس‌های فعال‌شده > Google Chat API کلیک کنید

    به صفحه Google Chat API بروید

  2. روی پیکربندی کلیک کنید.

  3. در بخش تنظیمات اتصال، به راه‌اندازها بروید و جزئیات نقطه پایانی را مشخص کنید. برای پاسخ دادن به فرمان، باید از این راه‌انداز در بخش زیر استفاده کنید.

    1. نشانی وب نقطه پایان HTTP: می‌توانید یک نشانی وب نقطه پایان HTTP رایج را در اینجا مشخص کنید. یا برای استفاده از نقاط پایانی HTTP متفاوت برای راه‌اندازهای متفاوت، نقطه پایانی را مستقیماً در فیلد فرمان برنامه مشخص کنید.
    2. Apps Script: «شناسه پیاده‌سازی Apps Script» را وارد کنید. به‌طور پیش‌فرض، تابع onAppCommand فراخوانی خواهد شد. برای استفاده از تابع Apps Script دیگر، نام تابع سفارشی را در فیلد فرمان برنامه مشخص کنید.
  4. در بخش فرمان‌ها، روی افزودن فرمان کلیک کنید.

  5. اطلاعات زیر را درباره فرمان وارد کنید:

    1. شناسه فرمان: عددی از ۱ تا ۱۰۰۰ که برنامه Chat شما از آن برای تشخیص فرمان و برگرداندن پاسخ استفاده می‌کند.
    2. شرح: نوشتاری که نحوه استفاده و قالب‌بندی فرمان را شرح می‌دهد. شرح می‌تواند حداکثر ۵۰ نویسه داشته باشد.
    3. نوع فرمان: فرمان سریع، فرمان خط مورب، یا کنش پیام را انتخاب کنید.
    4. نامی برای فرمان مشخص کنید:
      • نام فرمان سریع: نام نمایشی که کاربران از منو برای فراخوانی فرمان انتخاب می‌کنند. می‌تواند حداکثر ۵۰ نویسه داشته باشد و شامل نویسه‌های خاص باشد. به‌عنوان مثال، Remind me.
      • نام فرمان خط مورب: نوشتاری که کاربران برای فراخوانی فرمان در پیام تایپ می‌کنند. باید با خط مورب شروع شود، فقط حاوی نوشتار باشد، و می‌تواند حداکثر ۵۰ نویسه داشته باشد. به‌عنوان مثال، /remindMe.
      • نام کنش پیام: نام نمایشی که کاربران از منو برای فراخوانی کنش پیام انتخاب می‌کنند. می‌تواند حداکثر ۵۰ نویسه داشته باشد و شامل نویسه‌های خاص باشد. به‌عنوان مثال، Remind me.
  6. اختیاری: پیام اعلان بار کردن: پیام اعلان موقتی که هنگام اجرای کنش پیام به کاربر نشان داده می‌شود. فقط برای کنش‌های پیامی که کادر گفتگو باز نمی‌کنند دردسترس است.

  7. اختیاری: اگر می‌خواهید برنامه Chat شما با کادر گفتگو به فرمان پاسخ دهد، چارگوش انتخاب باز کردن کادر گفتگو را انتخاب کنید.

  8. روی ذخیره کلیک کنید.

اکنون فرمان برای برنامه Chat پیکربندی شده است.

فرمان‌های نقشه برای پیام‌واره‌های آغازگر

می‌توانید فرمان‌هایتان را به‌عنوان پیام‌واره‌های آغازگر برجسته کنید تا کاربران آن‌ها را به‌صورت تراشه‌های تعاملی هنگام شروع پیام مستقیم یک‌به‌یک خالی با برنامه Chat شما ببینند.

برای نگاشت کردن فرمان به پیام‌واره آغازگر:

  1. مطمئن شوید که فرمان شما به متغیرهای مستقل سفارشی اضافی نیاز ندارد (فقط فرمان‌های دارای بدون متغیر مستقل یا متغیرهای مستقل پایه به‌عنوان پیام‌واره آغازگر پشتیبانی می‌شوند).
  2. در کنسول Google Cloud، به صفحه پیکربندی Chat API بروید.
  3. در بخش ویژگی‌های تعاملی > پیام‌واره‌های آغازگر، روی افزودن پیام‌واره کلیک کنید.
  4. رتبه (۱-۳) را برای ترتیب نمایش تنظیم کنید.
  5. در بخش انتخاب نوع، فرمان‌بر را انتخاب کنید و فرمان خود را از منو کرکره‌ای انتخاب کنید.
  6. روی تمام و سپس ذخیره کلیک کنید.

پاسخ دادن به فرمان

وقتی کاربران از فرمانی استفاده می‌کنند، برنامه Chat شما شیء رویداد دریافت می‌کند. بار داده رویداد (event.chat.appCommandPayload) حاوی یک شیء appCommandPayload با جزئیات مربوط به فرمان فراخوانده‌شده (ازجمله شناسه فرمان و نوع فرمان) است تا بتوانید پاسخ مناسبی برگردانید. شیء رویداد به نقطه پایانی HTTP یا تابع Apps Script ارسال می‌شود که هنگام پیکربندی راه‌انداز فرمان برنامه مشخص کرده‌اید.

پیام خصوصی برای
  برنامه 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

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());
    }
  }
}

Apps Script

/**
 * 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 که برافزاهای 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

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 را نشان می‌دهد که برافزا نیست و به فرمان سریع Help پاسخ می‌دهد. برنامه 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

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}"`
    });
  }
}

Apps Script

/**
 * 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 مشخص کرده‌اید جایگزین کنید.