高级聊天服务

通过高级聊天服务,您可以在 Apps 脚本中使用 Google Chat API。此 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);
  }
}

创建聊天室

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

  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;
          }
          response.memberships.forEach((membership) => console.log(
              'Member resource name: %s (type: %s)',
              membership.name,
              membership.member.type));
          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"
]

限制和注意事项

高级聊天服务不支持以下功能:

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