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

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

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

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

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

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

    اگر برنامه 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» بروید.
  3. در بخش ویژگی‌های تعاملی > پیام‌واره‌های آغازگر، روی افزودن پیام‌واره کلیک کنید.
  4. رتبه (۱ تا ۳) را برای ترتیب نمایش تنظیم کنید.
  5. در بخش انتخاب نوع، پیام‌واره فرمان را انتخاب کنید و فرمان موردنظرتان را از منو کرکره‌ای انتخاب کنید.
  6. روی تمام و سپس روی ذخیره کردن کلیک کنید.

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

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

پیام خصوصی برای
  برنامه «گپ Cymbal Labs». در این پیام گفته شده است که
  برنامه «گپ» توسط 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;
  }
}

شناسه فرمان را که هنگام پیکربندی فرمان در کنسول Google Cloud مشخص کرده‌اید جایگزین ABOUT_COMMAND_ID کنید.

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

کد زیر نمونه‌ای از برنامه 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

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

شناسه فرمان را که هنگام پیکربندی فرمان در کنسول Google Cloud مشخص کرده‌اید جایگزین HELP_COMMAND_ID کنید.

پاسخ دادن به کنش پیام

کد زیر نمونه‌ای از برنامه 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());
    }
  }
}

شناسه فرمان را که هنگام پیکربندی فرمان در کنسول Google Cloud مشخص کرده‌اید جایگزین REMIND_ME_COMMAND_ID کنید.