响应 Google Chat 应用命令

本页介绍了如何设置 Google Chat 应用并响应命令。

命令可帮助用户发现和使用 Chat 应用的关键功能。只有 Chat 应用才能看到命令的内容。例如,如果用户发送包含斜杠命令的消息,则只有该用户和 Chat 应用可以查看该消息。

如需确定是否应构建命令,并了解如何设计用户互动,请参阅定义所有用户历程

聊天应用命令的类型

您可以将 Chat 应用命令构建为斜杠命令或快速命令。如需发现和使用每种类型的命令,用户可以执行以下操作:
  1. 斜杠命令:用户通过输入斜杠 (/) 和预定义文本(例如 /about)来发送命令。聊天应用还可以要求为斜杠命令提供实参文本。例如,斜杠命令 /search 可能需要用于搜索查询的实参文本。
  2. 快速命令:用户可以通过打开 Chat 消息的回复区域中的菜单来使用命令。如需使用命令,他们可以点击添加图标 ,然后从菜单中选择命令。
以下图片展示了用户如何发现斜杠命令和快捷命令的菜单:
  • 用户发现斜杠命令。
    图 1. 用户可以在回复区域中输入斜杠 /,然后输入命令名称,从而发现和使用斜杠命令。
  • 用户通过菜单查看快捷命令。
    图 2. 用户可以在聊天消息的回复区域中通过菜单发现并使用快速命令。

前提条件

Node.js

一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建互动式 Chat 应用,请完成此快速入门

Apps 脚本

一种 Google Chat 应用,可接收并响应互动事件。如需在 Apps 脚本中创建交互式 Chat 应用,请完成此快速入门

Python

一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建互动式 Chat 应用,请完成此快速入门

Java

一种 Google Chat 应用,可接收并响应互动事件。如需使用 HTTP 服务创建互动式 Chat 应用,请完成此快速入门

设置命令

本部分介绍了如何完成以下步骤来设置命令:

  1. 为命令创建名称和说明
  2. 在 Google Cloud 控制台中配置命令

为命令命名并添加说明

命令名称是用户输入或选择以调用 Chat 应用的内容。名称下方还会显示简短说明,进一步提示用户如何使用该命令:

斜杠命令名称和说明
图 3:斜杠命令的名称和说明。

为命令选择名称和说明时,请考虑以下建议:

如需命名指令,请执行以下操作:

  • 使用简短、描述性强且可操作的字词或短语,让用户清楚了解命令。例如,使用 Remind me,而不是 Create a reminder
  • 考虑为命令使用唯一名称或常用名称。如果您的命令描述的是典型的互动或功能,则可以使用用户熟悉且预期的常用名称,例如 SettingsFeedback。否则,请尝试使用唯一的命令名称,因为如果您的命令名称与其他 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 控制台中,依次点击“菜单”图标 > API 和服务 > 已启用的 API 和服务 > Google Chat API

    前往 Google Chat API 页面

  2. 点击配置

  3. 命令下,点击添加命令

  4. 为命令输入命令 ID、说明、命令类型和名称:

    • 命令 ID:一个介于 1 到 1000 之间的数字,供 Chat 应用用于识别命令并返回响应。
    • 说明:描述命令作用的文本。 说明最多可包含 50 个字符,并且可以包含特殊字符。
    • 命令类型:选择快速命令Slash 命令
    • 为快速命令或斜杠命令指定名称:
      • 快速命令名称:用户从菜单中选择以调用命令的显示名称。最多可包含 50 个字符,并且可以包含特殊字符。例如 Remind me
      • 斜杠命令名称:用户在消息中输入以调用命令的文本。必须以斜杠开头,只能包含文本,并且最多可以包含 50 个字符。例如 /remindMe
  5. 可选:如果您希望 Chat 应用通过对话框响应命令,请选中打开对话框复选框。

  6. 点击保存

现在,该命令已针对 Chat 应用配置完毕。

响应命令

当用户使用命令时,Chat 应用会收到互动事件。事件载荷包含元数据,其中详细说明了所调用的命令(包括命令 ID 和命令类型),以便您返回适当的响应。

Cymbal Labs Chat 应用的私信。该消息指出 Chat 应用由 Cymbal Labs 创建,并分享了指向文档的链接和指向支持团队的联系链接。
Chat 应用会私下响应斜杠命令 /help,说明如何获取支持。

为了响应每种类型的命令,您必须处理事件载荷中的不同事件类型和元数据对象:

命令类型 事件类型 命令元数据
斜杠命令 MESSAGE message.slashCommandmessage.annotation.slashCommand
快速命令 APP_COMMAND appCommandMetadata

如需了解如何通过消息响应命令,请参阅以下部分。

响应斜杠命令

以下代码展示了一个聊天应用的示例,该应用可回复斜杠命令 /about。Chat 应用会处理 MESSAGE 互动事件,检测互动事件是否包含匹配的命令 ID,并返回一条私信:

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 脚本

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,并返回一条私信:

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 脚本

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。

测试命令

如需测试命令和代码,请参阅测试 Google Chat 应用的互动功能

如需了解如何在 Chat 界面中测试和使用该命令,请参阅 Google Chat 帮助文档中的在 Google Chat 中使用应用