スペースを一覧表示する

このガイドでは、Google Chat API の Space リソースで list リソースを使用してスペースを一覧表示する方法について説明します。スペースを一覧表示すると、ページ分けされたフィルタ可能なスペースのリストが返されます。

Space リソースは、ユーザーと Chat アプリがメッセージの送信、ファイル共有、コラボレーションを行う場所を表します。スペースには次の種類があります。

  • ダイレクト メッセージ(DM)は、2 人のユーザー間の会話、またはユーザーと Chat アプリ間の会話です。
  • グループ チャットとは、3 人以上のユーザーと Chat アプリの間で交わされる会話のことです。
  • 名前付きスペースは、メッセージの送信、ファイルの共有、共同編集を行う永続的な場所です。

アプリ認証を使用してスペースを一覧表示すると、Chat アプリがアクセスできるスペースが一覧表示されます。ユーザー認証を使用してスペースを一覧表示すると、認証されたユーザーがアクセスできるスペースが一覧表示されます。

前提条件

Python

  • Python 3.6 以降
  • pip パッケージ管理ツール
  • Python 用の最新の Google クライアント ライブラリ。これらをインストールまたは更新するには、コマンドライン インターフェースで次のコマンドを実行します。

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリ用に構成された認可。スペースの一覧表示では、次の両方の認証方法がサポートされています。

Node.js

  • Node.js と npm
  • Node.js 用の最新の Google クライアント ライブラリ。これらをインストールするには、コマンドライン インターフェースで次のコマンドを実行します。

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリ用に構成された認可。スペースの一覧表示では、次の両方の認証方法がサポートされています。

ユーザー認証を使用してスペースを一覧表示する

Google Chat のスペースを一覧表示するには、リクエストに次の内容を渡します。

次の例では、認証されたユーザーが閲覧できる名前付きスペースとグループ チャットを一覧表示します(ダイレクト メッセージでフィルタでは表示されません)。

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.spaces.readonly"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then lists named spaces and group chats (but not direct messages)
        visible to the authenticated user.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                          'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().list(
    
              # An optional filter that returns named spaces or unnamed group chats,
              # but not direct messages (DMs).
              filter='spaceType = "SPACE" OR spaceType = "GROUP_CHAT"'
    
          ).execute()
    
        # Prints the returned list of spaces.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_space_list.py
    

Node.js

  1. 作業ディレクトリに、list-spaces.js という名前のファイルを作成します。
  2. list-spaces.js に次のコードを追加します。

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * List Chat spaces.
    * @return {!Promise<!Object>}
    */
    async function listSpaces() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.spaces.readonly',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.list({
        filter: 'spaceType = "SPACE" OR spaceType = "GROUP_CHAT"'
      });
    }
    
    listSpaces().then(console.log);
    
  3. 作業ディレクトリでサンプルを実行します。

    node list-spaces.js
    

Chat API は、名前付きスペースとグループ チャットのページ分けされた配列を返します。

アプリ認証を使用してスペースを一覧表示する

Google Chat のスペースを一覧表示するには、リクエストに次の内容を渡します。

次の例では、Chat アプリに表示される名前付きスペースとグループ チャットを一覧表示します(ダイレクト メッセージは表示されません)。

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Use the service endpoint to call Chat API.
    result = chat.spaces().list(
    
            # An optional filter that returns named spaces or unnamed
            # group chats, but not direct messages (DMs).
            filter='spaceType = "SPACE" OR spaceType = "GROUP_CHAT"'
    
        ).execute()
    
    print(result)
    
  3. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_space_list_app.py
    

Node.js

  1. 作業ディレクトリに、app-list-spaces.js という名前のファイルを作成します。
  2. app-list-spaces.js に次のコードを追加します。

    const chat = require('@googleapis/chat');
    
    /**
    * List Chat spaces.
    * @return {!Promise<!Object>}
    */
    async function listSpaces() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.bot',
      ];
    
      const auth = new chat.auth.GoogleAuth({
        scopes,
        keyFilename: 'credentials.json',
      });
    
      const authClient = await auth.getClient();
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.list({
        filter: 'spaceType = "SPACE" OR spaceType = "GROUP_CHAT"'
      });
    }
    
    listSpaces().then(console.log);
    
  3. 作業ディレクトリでサンプルを実行します。

    node app-list-spaces.js
    

Chat API は、ページ分けされたスペースの配列を返します。

ページ分けのカスタマイズやリストのフィルタリングを行う

Google Chat のスペースを一覧表示するには、次のオプションのクエリ パラメータを渡して、ページ分けをカスタマイズしたり、リストされたスペースをフィルタしたりできます。

  • pageSize: 返されるスペースの最大数。サービスはこの値よりも少ない数を返す場合があります。指定しない場合は、最大 100 個のスペースが返されます。最大値は 1,000 です。1,000 を超える値は、自動的に 1,000 に変更されます。
  • pageToken: 前回のリスト スペース呼び出しから受け取ったページトークン。次のページを取得するには、このトークンを指定します。ページ分割を行う場合、フィルタ値はページトークンを提供した呼び出しと一致する必要があります。別の値を渡すと、予期しない結果が生じる可能性があります。
  • filter: クエリフィルタ。サポートされているクエリの詳細については、spaces.list メソッドをご覧ください。