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

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

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

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

סוגי הפקודות באפליקציות ל-Chat

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

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

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

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

  3. פעולות בהודעות: המשתמשים יכולים להשתמש בפעולות בהודעות על ידי העברת העכבר מעל הודעה ולחיצה על סמל האפשרויות הנוספות (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. אחרת, נסו להשתמש בשמות ייחודיים לפקודות, כי אם שם הפקודה שלכם זהה לשמות של פקודות באפליקציות צ'אט אחרות, המשתמש יצטרך לסנן פקודות דומות כדי למצוא את הפקודה שלכם ולהשתמש בה.

כדי לתאר פקודה:

  • התיאור צריך להיות קצר וברור כדי שהמשתמשים יבינו מה יקרה כשהם ישתמשו בפקודה.
  • כדאי להודיע למשתמשים אם יש דרישות פורמט לפקודה. לדוגמה, אם אתם יוצרים פקודה דרך שורת הפקודות שדורשת טקסט של ארגומנט, הגדירו את התיאור למשהו כמו 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. בקטע Connection settings, עוברים אל Triggers ומציינים את פרטי נקודת הקצה. כדי להגיב לפקודה, צריך להשתמש בטריגר הזה בקטע הבא.

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

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

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

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

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

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

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

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

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

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

להגיב לפקודה

כשהמשתמשים משתמשים בפקודה, האפליקציה ל-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 שמשיבה לפעולה Remind me בהודעת טקסט. כדי להגיב לפעולות בהודעות, האפליקציה ל-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 שהן לא תוספים: מגיבות לפקודות

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