List spaces

This guide explains how to use the list resource on the Space resource of the Google Chat API to list spaces. Listing spaces returns a paginated, filterable list of spaces.

The Space resource represents a place where people and Chat apps can send messages, share files, and collaborate. There are several types of spaces:

  • Direct messages (DMs) are conversations between two users or a user and a Chat app.
  • Group chats are conversations between three or more users and Chat apps.
  • Named spaces are persistent places where people send messages, share files, and collaborate.

Listing spaces with app authentication lists spaces that the Chat app has access to. Listing spaces with User authentication lists spaces that the authenticated user has access to.

Prerequisites

Python

  • Python 3.6 or greater
  • The pip package management tool
  • The latest Google client libraries for Python. To install or update them, run the following command in your command-line interface:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app. Listing spaces supports both of the following authentication methods:

Node.js

  • Node.js & npm
  • The latest Google client libraries for Node.js. To install them, run the following command in your command-line interface:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app. Listing spaces supports both of the following authentication methods:

List spaces with user authentication

To list spaces in Google Chat, pass the following in your request:

The following example lists named spaces and group chats (but not direct messages, which are filtered out) visible to the authenticated user:

Python

  1. In your working directory, create a file named chat_space_list.py.
  2. Include the following code in 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. In your working directory, build and run the sample:

    python3 chat_space_list.py
    

Node.js

  1. In your working directory, create a file named list-spaces.js.
  2. Include the following code in 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. In your working directory, run the sample:

    node list-spaces.js
    

The Chat API returns a paginated array of named spaces and group chats.

List spaces with app authentication

To list spaces in Google Chat, pass the following in your request:

The following example lists named spaces and group chats (but not direct messages) visible to the Chat app:

Python

  1. In your working directory, create a file named chat_space_list_app.py.
  2. Include the following code in 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. In your working directory, build and run the sample:

    python3 chat_space_list_app.py
    

Node.js

  1. In your working directory, create a file named app-list-spaces.js.
  2. Include the following code in 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. In your working directory, run the sample:

    node app-list-spaces.js
    

The Chat API returns a paginated array of spaces.

Customize pagination or filter the list

To list spaces in Google Chat, pass the following optional query parameters to customize pagination of or filter listed spaces:

  • pageSize: The maximum number of spaces to return. The service might return fewer than this value. If unspecified, at most 100 spaces are returned. The maximum value is 1,000; values above 1,000 are automatically changed to 1,000.
  • pageToken: A page token, received from a previous list spaces call. Provide this token to retrieve the subsequent page. When paginating, the filter value should match the call that provided the page token. Passing a different value might lead to unexpected results.
  • filter: A query filter. For supported query details, see the spaces.list method.