回覆 Google Chat 應用程式指令

本頁面說明如何設定及回應 Google Chat 應用程式的指令。

指令可協助使用者探索及使用 Chat 擴充應用程式的主要功能。只有 Chat 擴充應用程式可以查看指令內容。舉例來說,如果使用者傳送含有斜線指令的訊息,則只有該使用者和 Chat 擴充應用程式能看到該訊息。

如要決定是否應建構指令,以及瞭解如何設計使用者互動,請參閱「定義所有使用者歷程」。

Chat 應用程式指令類型

您可以將 Chat 應用程式指令建構為斜線指令、快速指令或訊息動作。如要使用各種類型的指令,使用者可以執行下列操作:
  1. 斜線指令:使用者可以從選單中選取斜線指令,或輸入斜線 (/) 和預先定義的文字,例如 /about。Chat 擴充應用程式通常需要斜線指令的引數文字。

    如果 Chat 應用程式需要使用者提供額外輸入內容,請建立斜線指令。舉例來說,您可以建立名為 /search 的斜線指令,在使用者輸入要搜尋的詞組 (例如 /search receipts) 後執行。

  2. 快速指令:使用者從即時通訊訊息的回覆區開啟選單,即可使用指令。如要使用指令,請按一下「新增」圖示 ,然後從選單中選取指令。

    如果 Chat 擴充應用程式可以立即回覆使用者,不必等待額外輸入內容,請建立快速指令。舉例來說,您可以建立名為「隨機圖片」的快速指令,讓系統立即回覆圖片。

  3. 訊息動作:使用者只要將滑鼠游標懸停在訊息上,然後按一下三點圖示選單,即可使用訊息動作。如要使用指令,請開啟三點圖示選單,然後從選單中選取指令。

    如果 Chat 擴充應用程式可以根據訊息內容執行動作,請建立訊息動作。

下圖顯示使用者如何找到斜線指令、快速指令和訊息動作的選單:

必要條件

HTTP

Google Chat 應用程式,可接收及回應使用者互動。如要建構,請完成 HTTP 快速入門導覽課程。

Apps Script

Google Chat 應用程式,可接收及回應使用者互動。如要建構,請完成 Apps Script 快速入門導覽課程。

設定指令

本節說明如何完成下列步驟來設定指令:

  1. 建立指令的名稱和說明。
  2. 在 Google Cloud 控制台中設定指令。
  3. 選用:將指令對應至啟動提示詞。

為指令命名並輸入說明

指令名稱是使用者輸入或選取來叫用 Chat 擴充應用程式的名稱。名稱下方也會顯示簡短說明,進一步提示使用者如何使用指令:

斜線指令名稱和說明
斜線指令的名稱和說明。

為指令選擇名稱和說明時,請考量下列建議:

如何命名指令:

  • 使用簡短、描述性和可執行的字詞或詞組,讓使用者清楚瞭解指令。例如,請使用 Remind me,而非 Create a reminder。
  • 建議使用不重複或常見的指令名稱。如果指令描述的是一般互動或功能,可以使用使用者熟悉且預期的常見名稱,例如 Settings 或 Feedback。否則,請盡量使用不重複的指令名稱,因為如果指令名稱與其他 Chat 擴充應用程式相同,使用者就必須篩選類似的指令,才能找到並使用您的指令。

如要描述指令,請按照下列步驟操作:

  • 說明應簡短清楚,讓使用者瞭解指令的用途。
  • 告知使用者指令是否有任何格式規定。舉例來說,如果您建立的斜線指令需要引數文字,請將說明設為類似 Remind me to do [something] at [time] 的內容。
  • 讓使用者知道 Chat 擴充應用程式會回覆聊天室中的所有人,還是私下回覆叫用指令的使用者。舉例來說,如果是快速指令 About,您可以將其描述為 Learn about this app (Only visible to you)。

在 Google Cloud 控制台中設定指令

如要建立斜線指令、快速指令或訊息動作,請在 Google Chat API 的 Chat 應用程式設定中,指定指令或動作的相關資訊。

如要在 Google Chat API 中設定指令,請完成下列步驟:

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「API 和服務」>「已啟用的 API 和服務」>「Google Chat API」

    前往 Google Chat API 頁面

  2. 按一下「設定」。

  3. 在「連線設定」下方,前往「觸發條件」並指定端點詳細資料。您必須在下一節中使用這個觸發條件,才能回應指令。

    1. HTTP 端點網址:您可以在這裡指定一個通用的 HTTP 端點網址。或者,如要為不同觸發條件使用不同的 HTTP 端點,請直接在「App command」(應用程式指令) 欄位中指定端點。
    2. Apps Script:輸入 Apps Script 部署作業 ID。根據預設,系統會叫用 onAppCommand 函式。如要使用其他 Apps Script 函式,請在「App command」(應用程式指令) 欄位中指定自訂函式名稱。
  4. 在「指令」下方,按一下「新增指令」。

  5. 輸入下列指令相關資訊:

    1. 指令 ID:1 到 1000 之間的數字,Chat 擴充應用程式會用來辨識指令並傳回回應。
    2. 說明:說明如何使用指令及設定指令格式的文字。說明長度上限為 50 個半形字元。
    3. 指令類型:選取「快速指令」、「斜線指令」或「訊息動作」。
    4. 指定指令名稱:
      • 快速指令名稱:使用者從選單中選取來叫用指令的顯示名稱。最多可輸入 50 個字元,包括特殊字元。例如:Remind me。
      • 斜線指令名稱:使用者在訊息中輸入來叫用指令的文字。開頭須為正斜線,只能使用文字,長度上限為 50 個半形字元。例如:/remindMe。
      • 訊息動作名稱:使用者從選單中選取,用來叫用訊息動作的顯示名稱。最多可輸入 50 個字元,且可包含特殊字元。例如:Remind me。
  6. 選用:載入通知訊息:在執行訊息動作時,向使用者顯示的浮動式通知訊息。僅適用於不會開啟對話方塊的訊息動作。

  7. 選用:如要讓 Chat 擴充應用程式以對話方塊回應指令,請勾選「Open a dialog」(開啟對話方塊) 核取方塊。

  8. 按一下「儲存」。

Chat 擴充應用程式的指令設定完成。

將指令對應至啟動提示詞

您可以將指令設為啟動提示詞,這樣一來,當使用者與 Chat 應用程式發起空白的 1 對 1 即時訊息時,就會看到這些指令以互動式方塊顯示。

如要將指令對應至啟動提示詞,請按照下列步驟操作:

  1. 確認指令不需要額外的自訂引數 (只有「無引數」或「基本引數」的指令可做為啟動提示詞)。
  2. 在 Google Cloud 控制台中,前往 Chat API 的「設定」頁面。
  3. 在「互動功能」>「啟動提示詞」下方,點按「新增提示詞」。
  4. 設定顯示順序的排名 (1 至 3)。
  5. 在「Type selection」(類型選取) 下方,選擇「Command prompt」(命令提示字元),然後從下拉式選單中選取指令。
  6. 依序點選「Done」(完成) 和「Save」(儲存)。

回應指令

使用者使用指令時,Chat 擴充應用程式會收到事件物件。事件酬載 (event.chat.appCommandPayload) 包含 appCommandPayload 物件,其中包含叫用指令的詳細資料 (包括指令 ID 和指令類型),以便您傳回適當的回應。事件物件會傳送至您設定應用程式指令觸發條件時指定的 HTTP 端點或 Apps Script 函式。

Cymbal Labs Chat 應用程式的私人訊息。訊息指出 Chat 應用程式是由 Cymbal Labs 建立,並分享說明文件連結和支援團隊聯絡連結。
Chat 擴充應用程式會私下回覆斜線指令 /help,說明如何取得支援。

回應斜線指令或快速指令

下列程式碼範例顯示 Chat 擴充應用程式如何使用文字訊息回覆斜線指令 /about。如要回應斜線指令或快速指令,Chat 擴充應用程式會處理來自應用程式指令觸發條件的事件物件 (event.chat.appCommandPayload)。如果事件物件的酬載包含相符的指令 ID,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 中設定指令時指定的指令 ID。

回應訊息動作

下列程式碼範例顯示 Chat 擴充應用程式如何以文字訊息回覆「提醒我」訊息動作。為回應訊息動作,Chat 擴充應用程式會處理應用程式指令觸發條件中的事件物件。如果事件物件的酬載包含訊息動作指令 ID,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 中設定指令時指定的指令 ID。

測試指令

如要測試指令和程式碼,請參閱「測試 Google Chat 應用程式的互動功能」。

如要瞭解如何在 Chat UI 中測試及使用指令,請參閱 Google Chat 說明文件中的「在 Google Chat 中使用應用程式」。

非外掛程式的 Chat 擴充應用程式:回應指令

下列說明文件適用於非 Google Workspace 外掛程式的 Chat 應用程式。如要遷移非外掛程式的 Chat 擴充應用程式,請參閱「將 Google Chat 擴充應用程式轉換為 Google Workspace 外掛程式」。

使用者使用指令時,非外掛程式的 Chat 應用程式會收到互動事件,並可直接傳回 Message 物件來回應。事件酬載包含中繼資料,其中包含叫用指令的詳細資料 (包括指令 ID 和指令類型),以便您傳回適當的回應。

如要在非外掛程式的 Chat 應用程式中回應各類指令,您必須處理事件酬載中的不同事件類型和中繼資料物件:

指令類型 事件類型 指令中繼資料
斜線指令 MESSAGE message.slashCommand 或 message.annotation.slashCommand
快速指令 APP_COMMAND appCommandMetadata
訊息動作 APP_COMMAND appCommandMetadata

回應斜線指令

下列程式碼範例顯示,非外掛程式的 Chat 擴充應用程式如何回覆斜線指令 /about。Chat 擴充應用程式會處理 MESSAGE 互動事件、偵測互動事件是否包含相符的指令 ID,並傳回私人 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 控制台中設定指令時指定的指令 ID。

回應快捷指令

下列程式碼範例顯示,非外掛程式的 Chat 擴充應用程式如何回覆快速指令 Help。Chat 擴充應用程式會處理 APP_COMMAND 互動事件、偵測互動事件是否包含相符的指令 ID,並傳回私人 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 控制台中設定指令時指定的指令 ID。

回應訊息動作

下列程式碼範例顯示,非外掛程式的 Chat 應用程式如何回覆訊息動作「提醒我」。Chat 擴充應用程式會處理 APP_COMMAND 互動事件、偵測互動事件是否包含相符的指令 ID,並傳回私人 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 控制台中設定指令時指定的指令 ID。