Google Chat スペースのイベントを一覧表示する

このガイドでは、Google Chat API の SpaceEvent リソースで list() メソッドを使用して、スペース内のリソースの変更を一覧表示する方法について説明します。

SpaceEvent リソースは、メッセージ、リアクション、メンバーシップなどのスペースの子リソースを含む、ターゲット スペースの変更を表します。サポートされているイベントタイプとイベント ペイロードのリストの詳細については、SpaceEvent リソース リファレンス ドキュメントの eventType フィールドと payload フィールドをご覧ください。

リクエストの時点から 28 日前までのイベントを一覧表示できます。サーバーは、影響を受けるリソースの最新バージョンを含むイベントを返します。たとえば、新しいスペース メンバーに関するイベントを一覧表示すると、サーバーは最新のメンバーシップの詳細を含む Membership リソースを返します。リクエストされた期間中に新しいメンバーが削除された場合、イベント ペイロードには空の Membership リソースが含まれます。

スペースのイベントを一覧表示するには、認証済みのユーザーまたは Chat 用アプリがスペースのメンバーである必要があります。

前提条件

Node.js

Python

スペース イベントを一覧表示する(ユーザー認証)

Chat スペースのスペース イベントを一覧表示するには、リクエストで次の値を渡します。

  • リクエストで各イベントタイプをサポートする 1 つ以上の認可スコープを指定します。ベスト プラクティスとして、アプリが機能する範囲で最も制限の大きいスコープを選択します。スコープを選択するには、認証と認可の概要をご覧ください。

  • ListSpaceEvents() メソッドを呼び出し、一覧表示するイベントタイプの filter を渡します。少なくとも 1 つのイベントタイプを指定する必要があります。また、日付でフィルタすることもできます。サポートされているイベントタイプの一覧については、SpaceEvent リソースの eventType フィールドのリファレンス ドキュメントをご覧ください。

次の例では、スペース内の新しいメンバーシップとメッセージに関するイベントを一覧表示します。

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);
  }
}

await main();

このサンプルを実行するには、SPACE_NAME をスペースの name から取得した ID に置き換えます。ID は、ListSpaces() メソッドを呼び出すか、スペースの URL から取得できます。

Chat API は、新しいメンバーシップとメッセージに関するスペース イベントのページネーション リストを返します。

スペース イベントを一覧表示する(Chat 用アプリの認証)

アプリの認証には、1 回限りの管理者による承認が必要です。

アプリ認証Chat REST API を使用して Space のイベントを一覧表示するには、リクエストで次の情報を渡します。

  • リクエストで各イベントタイプをサポートする 1 つ以上の認可スコープを指定します。ベスト プラクティスとして、アプリが機能する範囲で最も制限の大きいスコープを選択します。スコープの選択の詳細については、認証と認可の概要をご覧ください。
    • https://www.googleapis.com/auth/chat.app.memberships
    • https://www.googleapis.com/auth/chat.app.messages.readonly
    • https://www.googleapis.com/auth/chat.app.spaces
  • spaceEvents リソースlist メソッドを呼び出します。
  • メッセージを一覧表示するスペースの name を渡します。
  • 特定のイベントタイプをクエリするには、filter を渡します。

API キーを作成する

デベロッパー プレビュー API メソッドを呼び出すには、API ディスカバリ ドキュメントの非公開のデベロッパー プレビュー バージョンを使用する必要があります。リクエストを認証するには、API キーを渡す必要があります。

API キーを作成するには、アプリの Google Cloud プロジェクトを開いて次の操作を行います。

  1. Google Cloud コンソールで、メニュー > [API とサービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [API キー] をクリックします。
  3. 新しい API キーが表示されます。
    • [コピー] をクリックして、アプリのコードで使用する API キーをコピーします。API キーは、プロジェクトの認証情報の [API キー] セクションでも確認できます。
    • 不正使用を防ぐため、API キーを使用できる場所と対象の API を制限することをおすすめします。詳細については、API 制限を追加するをご覧ください。

Chat API を呼び出すスクリプトを作成する

アプリ認証Chat REST API を使用してスペース イベントを一覧表示する方法は次のとおりです。

Python

  1. 作業ディレクトリに chat_spaceevents_list_app.py という名前のファイルを作成します。
  2. chat_spaceevents_list_app.py に次のコードを含めます。

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # Set authorization scopes based on the
    # event type. For example, if you are getting a space event
    # about a new membership, use the `chat.app.memberships.readonly` scope.
    #
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.memberships",
              "https://www.googleapis.com/auth/chat.app.messages.readonly",
              "https://www.googleapis.com/auth/chat.app.spaces"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists space events from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().spaceEvents().list(
    
            # The space to list events from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME',
    
            # A required filter. Filters events by event type.
            #
            # Update this filter to match your requirements.
            filter='eventTypes:"google.workspace.chat.message.v1.created"'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. コードで、次の値を置き換えます。

    • API_KEY: Chat API のサービス エンドポイントを構築するために作成した API キー。
    • SPACE_NAME: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。
  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_spaceevents_list_app.py

Chat API は、新しいメンバーシップとメッセージに関するスペース イベントのページネーション リストを返します。