איך עונים לפקודות באפליקציית Google Chat

בדף הזה מוסבר איך להגדיר אפליקציה ל-Google Chat ולהגיב לפקודות.

פקודות עוזרות למשתמשים לגלות ולהשתמש בתכונות מרכזיות של אפליקציית Chat. רק אפליקציות Chat יכולות לראות את התוכן של פקודה. לדוגמה, אם משתמש שולח הודעה עם פקודת לוכסן, ההודעה גלויה רק למשתמש ולאפליקציית Chat.

כדי להחליט אם כדאי ליצור פקודות, וכדי להבין איך לעצב אינטראקציות עם משתמשים, אפשר לעיין במאמר הגדרת כל תהליכי המשתמש.

סוגים של פקודות לאפליקציות ל-Chat

אפשר ליצור פקודות לאפליקציות ל-Chat כפקודות באמצעות לוכסן, כפקודות מהירות או כפעולות על הודעות. כדי להשתמש בכל סוג של פקודה, המשתמשים יכולים לבצע את הפעולות הבאות:
  1. פקודות דרך שורת הפקודות: המשתמשים יכולים לבחור פקודה דרך שורת הפקודות מהתפריט או להקליד לוכסן (/) ואז טקסט מוגדר מראש, כמו /about. בדרך כלל, אפליקציות צ'אט דורשות טקסט של ארגומנט לפקודה דרך שורת הפקודות.

    יוצרים פקודה דרך שורת הפקודות אם אפליקציית Chat דורשת קלט נוסף מהמשתמש. לדוגמה, אפשר ליצור פקודה דרך שורת הפקודות בשם /search שמופעלת אחרי שהמשתמש מזין ביטוי לחיפוש, כמו /search receipts.

  2. פקודות מהירות: משתמשים יכולים להשתמש בפקודות על ידי פתיחת התפריט מאזור התשובה של הודעת צ'אט. כדי להשתמש בפקודה, לוחצים על הוספה ובוחרים פקודה מהתפריט.

    כדאי ליצור פקודה מהירה אם אפליקציית Chat יכולה להגיב למשתמש באופן מיידי, בלי לחכות לקלט נוסף. לדוגמה, אתם יכולים ליצור פקודה מהירה בשם תמונה אקראית שתגיב מיד עם תמונה.

  3. פעולות בהודעות: כדי להשתמש בפעולות בהודעות, המשתמשים מעבירים את העכבר מעל ההודעה ולוחצים על סמל האפשרויות הנוספות (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, לוחצים על סמל התפריט > APIs & Services > Enabled APIs & Services > Google Chat API

    כניסה לדף Google Chat API

  2. לוחצים על הגדרה.

  3. בקטע הגדרות חיבור, עוברים אל טריגרים ומציינים את פרטי נקודת הקצה. צריך להשתמש בטריגר הזה בקטע הבא כדי להגיב לפקודה.

    1. כתובת URL של נקודת קצה (endpoint) ב-HTTP: אפשר לציין כאן כתובת URL אחת משותפת של נקודת קצה ב-HTTP. לחלופין, כדי להשתמש בנקודות קצה שונות של HTTP לטריגרים שונים, מציינים את נקודת הקצה ישירות בשדה App command (פקודת האפליקציה).
    2. ‫Apps Script: מזינים את מזהה הפריסה של Apps Script. כברירת מחדל, הפונקציה onAppCommand תופעל. כדי להשתמש בפונקציה אחרת של Apps Script, מציינים את שם הפונקציה בהתאמה אישית בשדה פקודת האפליקציה.
  4. בקטע Commands, לוחצים על Add a command.

  5. מזינים את המידע הבא על הפקודה:

    1. מזהה הפקודה: מספר מ-1 עד 1,000 שאפליקציית Chat משתמשת בו כדי לזהות את הפקודה ולהחזיר תשובה.
    2. Description: הטקסט שמתאר איך להשתמש בפקודה ואיך לעצב אותה. התיאורים יכולים להכיל עד 50 תווים.
    3. סוג הפקודה: בוחרים באפשרות פקודה מהירה, פקודה דרך שורת הפקודות או פעולה בהודעה.
    4. מציינים שם לפקודה:
      • שם הפקודה המהירה: השם המוצג שהמשתמשים בוחרים מהתפריט כדי להפעיל את הפקודה. יכול לכלול עד 50 תווים, כולל תווים מיוחדים. לדוגמה, Remind me.
      • שם הפקודה דרך שורת הפקודות: הטקסט שהמשתמשים מקלידים כדי להפעיל את הפקודה בהודעה. הנתיב חייב להתחיל בלוכסן, להכיל רק טקסט ולהיות באורך של עד 50 תווים. לדוגמה, /remindMe.
      • שם ההצעה לפעולה: השם המוצג שהמשתמשים בוחרים מהתפריט כדי להפעיל את ההצעה לפעולה. יכול לכלול עד 50 תווים, כולל תווים מיוחדים. לדוגמה, Remind me.
  6. אופציונלי: הודעת טוסט על טעינה: הודעת טוסט שמוצגת למשתמש בזמן שההצעה לפעולה מתבצעת. האפשרות הזו זמינה רק לפעולות בהודעות שלא פותחות תיבות דו-שיח.

  7. אופציונלי: אם רוצים שאפליקציית Chat תגיב לפקודה עם תיבת דו-שיח, מסמנים את התיבה פתיחת תיבת דו-שיח.

  8. לוחצים על שמירה.

הפקודה מוגדרת עכשיו לאפליקציית Chat.

מיפוי פקודות להצעות לפרומפטים

אתם יכולים להציג את הפקודות שלכם כהנחיות ראשוניות כדי שהמשתמשים יראו אותן כצ'יפים אינטראקטיביים כשהם מתחילים צ'אט ישיר ריק עם אפליקציית Chat שלכם.

כדי למפות פקודה להצעה לפרומפט:

  1. חשוב לוודא שהפקודה לא דורשת ארגומנטים מותאמים אישית נוספים (רק פקודות עם No arguments או Basic arguments נתמכות כהנחיות התחלתיות).
  2. במסוף Google Cloud, עוברים לדף Configuration של Chat API.
  3. בקטע תכונות אינטראקטיביות > הצעות להתחלת שיחה, לוחצים על הוספת הצעה.
  4. מגדירים את הדירוג (1-3) של סדר ההצגה.
  5. בקטע בחירת סוג, בוחרים באפשרות שורת פקודה ובוחרים את הפקודה הרצויה מהתפריט הנפתח.
  6. לוחצים על סיום ולאחר מכן על שמירה.

איך מגיבים לפקודה

כשמשתמשים משתמשים בפקודה, אפליקציית Chat מקבלת אובייקט אירוע. המטען הייעודי (payload) של האירוע (event.chat.appCommandPayload) מכיל אובייקט appCommandPayload עם פרטים על הפקודה שהופעלה (כולל מזהה הפקודה וסוג הפקודה), כדי שתוכלו להחזיר תגובה מתאימה. אובייקט האירוע נשלח לנקודת הקצה של HTTP או לפונקציית Apps Script שציינתם כשהגדרתם את הטריגר App command.

הודעה פרטית מאפליקציית הצ'אט של Cymbal Labs. בהודעה כתוב שאפליקציית הצ'אט נוצרה על ידי Cymbal Labs, ויש בה קישור למסמכים וקישור ליצירת קשר עם צוות התמיכה.
אפליקציית Chat מגיבה באופן פרטי לפקודה דרך שורת הפקודות /help כדי להסביר איך לקבל תמיכה.

תשובה לפקודה דרך שורת הפקודות או לפקודה מהירה

הקוד הבא מציג דוגמה של אפליקציית Chat שעונה לפקודה דרך שורת הפקודות /about בהודעת טקסט. כדי להגיב לפקודות דרך שורת הפקודות או לפקודות מהירות, אפליקציית Chat מטפלת באובייקטים של אירועים (event.chat.appCommandPayload) מטריגר של פקודה לאפליקציה. כשמטען הייעודי (payload) של אובייקט אירוע מכיל מזהה פקודה תואם, אפליקציית 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

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 מטפלת באובייקטים של אירועים מטריגר של פקודת אפליקציה. כשמטען הייעודי (payload) של אובייקט אירוע מכיל מזהה של פקודת פעולה בהודעה, אפליקציית 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}"'
                        }
                    }
                }
            }
        }

Java

/**
 * 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 מוסבר איך לבדוק את הפקודה והקוד.

במאמר איך משתמשים באפליקציות ב-Google Chat במרכז העזרה של Google Chat מוסבר איך לבדוק את הפקודה ולהשתמש בה בממשק המשתמש של Chat.

אפליקציות ל-Chat שלא מוגדרות כתוספים: מגיבות לפקודות

המסמכים הבאים רלוונטיים לאפליקציות ל-Chat שהן לא תוספים ל-Google Workspace. כדי להעביר אפליקציה ל-Chat שלא מוגדרת כתוסף, אפשר לעיין במאמר בנושא המרת אפליקציה ל-Google Chat לתוסף ל-Google Workspace.

כשמשתמשים מזינים פקודה, אפליקציה ל-Chat שהיא לא תוסף מקבלת אירוע אינטראקציה ויכולה להגיב על ידי החזרת אובייקט Message ישירות. מטען הייעודי (payload) של האירוע מכיל מטא-נתונים עם פרטים על הפקודה שהופעלה (כולל מזהה הפקודה וסוג הפקודה), כדי שתוכלו להחזיר תגובה מתאימה.

כדי להגיב לכל סוג של פקודה באפליקציית Chat שהיא לא תוסף, צריך לטפל בסוגים שונים של אירועים ובאובייקטים של מטא-נתונים במטען הייעודי (payload) של האירוע:

סוג הפקודה סוג אירוע מטא-נתונים של פקודות
פקודה דרך שורת הפקודות 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

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

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 שהיא לא תוסף, שמגיבה לפעולת ההודעה תזכור לי. אפליקציית הצ'אט מטפלת באירועי אינטראקציה מסוג 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}"'
        }

Java

/**
 * 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.