列出聊天室中的成員

本指南說明如何在 Google Chat API 的 Membership 資源上使用 list() 方法,將聊天室的成員列為分頁式可篩選的聊天室成員清單。

  • 使用應用程式驗證功能列出會員資格,系統會列出 Chat 應用程式可存取的聊天室中的會員資格,但會排除 Chat 應用程式會員資格,包括自己的會員資格。
  • 使用使用者驗證功能列出會員資格,會列出已驗證使用者可存取的聊天室會員資格。
  • 以具有管理員權限的使用者驗證方式,以 Google Workspace 管理員的身分列出成員,會在 Google Workspace 機構所有聊天室中列出成員資格。

Membership 資源代表使用者或 Google Chat 應用程式是否已受邀加入聊天室、是否已加入聊天室或未加入聊天室。

必要條件

Node.js

Python

Java

Apps Script

透過使用者驗證機制列出聊天室中的成員

如要在已驗證使用者可存取的空間中列出使用者、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 Script

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 Script

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 參考資料。