高级聊天服务

管理 Chat 聊天室、成员和消息。

通过高级聊天服务,您可以在 Google Chat API 中使用 Google Apps 脚本。借助此 API,脚本可以查找、创建和修改 Chat 聊天室,向聊天室添加或移除成员,以及阅读或发布包含文字、卡片、附件和回应的消息。

前提条件

这是一项高级服务,您必须 先开启才能使用

参考

如需详细了解此服务,请参阅 Chat API 参考文档。 与 Apps 脚本中的所有高级服务一样,Chat 服务使用的对象、方法和参数均与公共 API 相同。

示例代码

这些示例展示了如何使用高级服务执行常见的 Google Chat API 操作。

使用用户凭据发布消息

以下示例演示了如何代表用户向 Chat 聊天室发布消息。

  1. chat.messages.create 授权范围添加到 Apps 脚本项目的 appsscript.json 文件中:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.messages.create"
    ]
    
  2. 向 Apps 脚本项目的代码添加如下所示的函数:

    advanced/chat.gs
    /**
     * Posts a new message to the specified space on behalf of the user.
     * @param {string} spaceName The resource name of the space.
     */
    function postMessageWithUserCredentials(spaceName) {
      try {
        const message = { text: "Hello world!" };
        Chat.Spaces.Messages.create(message, spaceName);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create message with error %s", err.message);
      }
    }

使用应用凭据发布消息

以下示例演示了如何代表应用向 Chat 聊天室发布消息。使用高级 Chat 服务和服务账号时,您无需在 appsscript.json 中指定授权范围。如需详细了解如何使用服务账号进行身份验证,请参阅 以 Google Chat 应用的身份进行身份验证

advanced/chat.gs
/**
 * Posts a new message to the specified space on behalf of the app.
 * @param {string} spaceName The resource name of the space.
 */
function postMessageWithAppCredentials(spaceName) {
  try {
    // See https://developers.google.com/chat/api/guides/auth/service-accounts
    // for details on how to obtain a service account OAuth token.
    const appToken = getToken_();
    const message = { text: "Hello world!" };
    Chat.Spaces.Messages.create(
      message,
      spaceName,
      {},
      // Authenticate with the service account token.
      { Authorization: `Bearer ${appToken}` },
    );
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed to create message with error %s", err.message);
  }
}

获取聊天室

以下示例演示了如何获取有关 Chat 聊天室的信息。

  1. chat.spaces.readonly 授权范围添加到 Apps 脚本项目的 appsscript.json 文件中:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.readonly"
    ]
    
  2. 向 Apps 脚本项目的代码添加如下所示的函数:

    advanced/chat.gs
    /**
     * Gets information about a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function getSpace(spaceName) {
      try {
        const space = Chat.Spaces.get(spaceName);
        console.log("Space display name: %s", space.displayName);
        console.log("Space type: %s", space.spaceType);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to get space with error %s", err.message);
      }
    }

创建聊天室

以下示例演示了如何创建 Chat 聊天室。

  1. chat.spaces.create 授权范围添加到 Apps 脚本项目的 appsscript.json 文件中:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.create"
    ]
    
  2. 向 Apps 脚本项目的代码添加如下所示的函数:

    advanced/chat.gs
    /**
     * Creates a new Chat space.
     */
    function createSpace() {
      try {
        const space = { displayName: "New Space", spaceType: "SPACE" };
        Chat.Spaces.create(space);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create space with error %s", err.message);
      }
    }

列出成员资格

以下示例演示了如何列出 Chat 聊天室的所有成员。

  1. chat.memberships.readonly 授权范围添加到 Apps 脚本项目的 appsscript.json 文件中:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships.readonly"
    ]
    
  2. 向 Apps 脚本项目的代码添加如下所示的函数:

    advanced/chat.gs
    /**
     * Lists all the members of a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function listMemberships(spaceName) {
      let response;
      let pageToken = null;
      try {
        do {
          response = Chat.Spaces.Members.list(spaceName, {
            pageSize: 10,
            pageToken: pageToken,
          });
          if (!response.memberships || response.memberships.length === 0) {
            pageToken = response.nextPageToken;
            continue;
          }
          for (const membership of response.memberships) {
            console.log(
              "Member: %s, Role: %s",
              membership.member.displayName,
              membership.role,
            );
          }
          pageToken = response.nextPageToken;
        } while (pageToken);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed with error %s", err.message);
      }
    }

问题排查

如果您遇到 Error 400: invalid_scope 错误,并显示错误消息 Some requested scopes cannot be shown,则表示您未在 Apps 脚本项目的 appsscript.json 文件中指定任何授权范围。在大多数情况下,Apps 脚本会自动确定脚本所需的范围,但当您使用 Chat 高级服务时,必须手动将脚本使用的授权范围添加到 Apps 脚本项目的清单文件中。请参阅 设置显式范围

如需解决此错误,请将相应的授权范围添加到 Apps 脚本项目的 appsscript.json 文件中,作为 oauthScopes 数组的一部分。例如,如需调用 spaces.messages.create 方法,请添加以下内容:

"oauthScopes": [
  "https://www.googleapis.com/auth/chat.messages.create"
]

限制和注意事项

高级聊天服务不支持:

  • Chat API 方法 media.download
  • 开发者预览版中提供的 Chat API 方法

如需下载消息附件或调用开发者预览版方法,请改用 UrlFetchApp