列出聊天室中的成员

本指南介绍了如何针对 Google Chat API 的 Membership 资源使用 list() 方法,将聊天室中的成员作为可过滤的分页成员列表列出。

  • 使用应用身份验证列出成员会列出 Chat 应用有权访问的聊天室中的成员,但会排除 Chat 应用成员(包括 Chat 应用本身的成员)。
  • 使用用户身份验证列出会员资格会列出已通过身份验证的用户有权访问的聊天室中的会员资格。
  • 以 Google Workspace 管理员身份列出成员资格(使用管理员权限进行用户身份验证)会列出您 Google Workspace 组织中的所有聊天室中的成员资格。

Membership 资源表示有人为用户或 Google Chat 应用发出了加入聊天室的邀请、用户或 Google Chat 应用已加入聊天室,还是未加入聊天室。

前提条件

Node.js

Python

Java

Apps 脚本

在经过用户身份验证的聊天室中列出成员

如需列出经过身份验证的用户有权访问的聊天室中的用户、Google 群组和 Chat 应用,请在请求中传递以下内容:

  • 使用用户身份验证时,请指定 chat.memberships.readonlychat.memberships 授权范围。
  • 调用 ListMemberships() 方法。
  • 如需列出 Google 群组,请将查询参数 showGroups 设置为 true

以下示例列出了对经过身份验证的用户可见的 Google 群组、真人和应用成员。

Node.js

chat/client-libraries/cloud/list-memberships-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.readonly'];

// This sample shows how to list memberships with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME',
    // Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
    // ROLE_MANAGER)
    filter: 'member.type = "HUMAN"'
  };

  // Make the request
  const pageResult = chatClient.listMembershipsAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_memberships_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships.readonly"]

# This sample shows how to list memberships with user credential
def list_memberships_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.ListMembershipsRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
        # ROLE_MANAGER)
        filter = 'member.type = "HUMAN"',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_memberships(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_memberships_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMembershipsRequest;
import com.google.chat.v1.ListMembershipsResponse;
import com.google.chat.v1.Membership;

// This sample shows how to list memberships with user credential.
public class ListMembershipsUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships.readonly";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListMembershipsRequest.Builder request = ListMembershipsRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Filter membership by type (HUMAN or BOT) or role
        // (ROLE_MEMBER or ROLE_MANAGER).
        .setFilter("member.type = \"HUMAN\"")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterating over results and resolve additional pages automatically.
      for (Membership response :
          chatServiceClient.listMemberships(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to list memberships with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listMembershipsUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = 'spaces/SPACE_NAME';
  // Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
  // ROLE_MANAGER)
  const filter = 'member.type = "HUMAN"';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Members.list(parent, {
      filter: filter,
      pageSize: 10,
      pageToken: pageToken
    });
    // Handle response pages
    if (responsePage.memberships) {
      responsePage.memberships.forEach((membership) => console.log(membership));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

如需运行此示例,请将 SPACE_NAME 替换为聊天室的 name 字段中的 ID。您可以通过调用 ListSpaces() 方法或从聊天室的网址中获取 ID。

Google Chat API 会返回指定聊天室中的 Google 群组成员、用户成员和应用成员的列表

在进行应用身份验证的聊天室中列出成员

如需列出经过身份验证的应用有权访问的聊天室中的用户和 Chat 应用,请在请求中传递以下内容:

  • 使用应用身份验证时,请指定 chat.bot 授权范围。
  • 调用 ListMemberships() 方法。
  • 如需列出 Google 群组,请将查询参数 showGroups 设置为 true

以下示例列出了 Chat 应用可见的聊天室成员(而非聊天室管理员):

Node.js

chat/client-libraries/cloud/list-memberships-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to list memberships with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME',
    // Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
    // ROLE_MANAGER)
    filter: 'member.type = "HUMAN"'
  };

  // Make the request
  const pageResult = chatClient.listMembershipsAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_memberships_app_cred.py
from authentication_utils import create_client_with_app_credentials
from google.apps import chat_v1 as google_chat

# This sample shows how to list memberships with app credential
def list_memberships_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.ListMembershipsRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
        # ROLE_MANAGER)
        filter = 'member.type = "HUMAN"',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_memberships(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_memberships_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMembershipsRequest;
import com.google.chat.v1.ListMembershipsResponse;
import com.google.chat.v1.Membership;

// This sample shows how to list memberships with app credential.
public class ListMembershipsAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      ListMembershipsRequest.Builder request = ListMembershipsRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Filter membership by type (HUMAN or BOT) or role
        // (ROLE_MEMBER or ROLE_MANAGER).
        .setFilter("member.type = \"HUMAN\"")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Membership response :
          chatServiceClient.listMemberships(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to list memberships with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function listMembershipsAppCred() {
// Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = 'spaces/SPACE_NAME';
  // Filter membership by type (HUMAN or BOT) or role (ROLE_MEMBER or
  // ROLE_MANAGER)
  const filter = 'member.type = "HUMAN"';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Members.list(parent, {
      filter: filter,
      pageSize: 10,
      pageToken: pageToken
    }, getHeaderWithAppCredentials());
    // Handle response pages
    if (responsePage.memberships) {
      responsePage.memberships.forEach((membership) => console.log(membership));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

如需运行此示例,请将 SPACE_NAME 替换为聊天室的 name 字段中的 ID。您可以通过调用 ListSpaces() 方法或从聊天室的网址中获取此 ID。

Google Chat API 会返回指定聊天室中的人类聊天室成员(不包括聊天室管理员)的列表

将成员列为 Google Workspace 管理员

如果您是 Google Workspace 管理员,则可以调用 ListMemberships() 方法来列出 Google Workspace 组织中任何聊天室的成员资格。Chat API 仅返回贵组织中的用户(内部和外部用户)或 Google 群组的成员资格,因此会忽略任何 Chat 应用的成员资格。

如需以 Google Workspace 管理员身份调用此方法,请执行以下操作:

  • 使用用户身份验证调用该方法,并指定支持使用管理员权限调用该方法的授权范围
  • 在请求中,指定以下查询参数:
    • useAdminAccess 设置为 true
    • 如需仅返回用户,请将 member.typefilter 设置为等于 HUMAN
    • 如需返回用户和群组,请将 member.typefilter 设为不等于 BOT AND showGroups 等于 true

如需了解详情和示例,请参阅以 Google Workspace 管理员身份管理 Google Chat 聊天室

自定义分页或过滤列表

如需列出成员,请传递以下查询参数以对列出的成员进行自定义分页或过滤:

  • pageSize:要返回的会员资格数量上限。服务返回的数量可能小于此值。如果未指定,则最多返回 100 个空格。最大值为 1,000;大于 1,000 的值会自动更改为 1,000。
  • pageToken:从上一个列出聊天室的调用接收的页面令牌。 提供此令牌以检索后续页面。进行分页时,过滤条件值应与提供页面令牌的调用相一致。传递其他值可能会导致意外结果。
  • filter:查询过滤条件。需要用户身份验证。如需了解支持的查询详情,请参阅 ListMembershipsRequest 参考文档。