列出 Google Chat 聊天室中的事件

本指南說明如何使用 Google Chat API SpaceEvent 資源的 list() 方法,列出空間中資源的變更。

SpaceEvent 資源代表目標聊天室的變更,包括聊天室的子項資源,例如訊息、回應和成員。如要進一步瞭解支援的事件類型和事件酬載清單,請參閱 SpaceEvent 資源參考文件的eventTypepayload欄位。

您最多可以列出要求時間前 28 天的活動。伺服器會傳回含有受影響資源最新版本的事件。舉例來說,如果您列出有關新空間成員的事件,伺服器會傳回包含最新成員詳細資料的 Membership 資源。如果新成員在要求期間遭到移除,事件酬載會包含空白的 Membership 資源。

如要呼叫這個方法,您必須使用使用者驗證。如要列出聊天室的活動,已驗證的使用者必須是聊天室成員。

必要條件

Node.js

列出聊天室活動

如要列出 Chat 聊天室的活動,請在要求中傳遞下列項目:

  • 請指定一或多個授權範圍,以支援要求中的每個事件類型。最佳做法是選擇限制最多的範圍,但仍允許應用程式運作。如要選擇範圍,請參閱「驗證和授權總覽」。

  • 呼叫 ListSpaceEvents() 方法,並傳遞要列出的事件類型 filter。您必須指定至少一個事件類型,也可以依日期篩選。 如需支援的事件類型清單,請參閱eventType 欄位的 SpaceEvent 資源參考說明文件。

以下範例列出有關新成員和訊息的事件:

Node.js

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

// Authorization scopes based on the event types
const USER_AUTH_OAUTH_SCOPES = [
  'https://www.googleapis.com/auth/chat.memberships.readonly',
  'https://www.googleapis.com/auth/chat.messages.readonly'
];

// This sample shows how to list space events 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',
    // A required filter. Filters events about new memberships and messages
    filter: 'eventTypes:"google.workspace.chat.membership.v1.created" OR eventTypes:"google.workspace.chat.message.v1.created"'
  };

  // Make the request
  const pageResult = chatClient.listSpaceEventsAsync(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);

如要執行這個範例,請將 SPACE_NAME 替換為空間的 ID name。您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。

Chat API 會傳回空間事件的分頁清單,其中包含新成員和訊息。