Find a direct message (DM) space

This guide explains how to use the findDirectMessage method on the Space resource of the Google Chat API to get details about a direct message (DM) space.

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.

Authenticating with app authentication lets a Chat app get DMs that the Chat app has access to in Google Chat (for example, DMs it's a member of). Authenticating with user authentication returns DMs 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. Finding a direct message supports both:

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. Finding a direct message supports both:

Find a direct message

To find a direct message in Google Chat, pass the following in your request:

  • With app authentication, specify the chat.bot authorization scope. With user authentication, specify the chat.spaces.readonly or chat.spaces authorization scope.
  • Call the findDirectMessage method on the User resource, passing the name of the other user in the DM to return. With user authentication, this method returns a DM between the calling user and the specified user. With app authentication, this method returns a DM between the calling app and the specified user.
  • To add a human user as a space member, specify users/{user}, where {user} is either the {person_id} for the person from the People API, or the ID of a user in the Directory API. For example, if the People API person resourceName is people/123456789, you can add the user to the space by including a membership with users/123456789 as the member.name.

Find a direct message with user authentication

Here's how to find a direct message with user authentication:

Python

  1. In your working directory, create a file named chat_space_find_dm_user.py.
  2. Include the following code in chat_space_find_dm_user.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 returns details about a specified DM.
        '''
    
        # 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().findDirectMessage(
    
              # The other user in the direct message (DM) to return.
              #
              # Replace USER with a user name.
              name='users/USER'
    
          ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. In the code, replace USER with the name of a User in Google Chat.

  4. In your working directory, build and run the sample:

    python3 chat_space_find_dm_user.py
    

Node.js

  1. In your working directory, create a file named find-direct-message-space.js.

  2. Include the following code in find-direct-message-space.js:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Find a direct message Chat space for a user.
    * @return {!Promise<!Object>}
    */
    async function findDirectMessageSpace() {
      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.findDirectMessage(
          {name: 'users/USER'});
    }
    
    findDirectMessageSpace().then(console.log);
    
  3. In the code, replace USER with the name of a User in Google Chat.

  4. In your working directory, run the sample:

    node find-direct-message-space.js
    

The Chat API returns an instance of Space that details the specified DM.

Find a direct message with app authentication

Here's how to find a direct message with app authentication:

Python

  1. In your working directory, create a file named chat_space_find_dm_app.py.
  2. Include the following code in chat_space_find_dm_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().findDirectMessage(
    
        # The other user in the direct message (DM) to return.
        #
        # Replace USER with a user name.
        name='users/USER'
    
    ).execute()
    
    print(result)
    
  3. In the code, replace USER with the name of a User in Google Chat.

  4. In your working directory, build and run the sample:

    python3 chat_space_find_dm_app.py
    

Node.js

  1. In your working directory, create a file named app-find-direct-message-space.js.

  2. Include the following code in app-find-direct-message-space.js:

    const chat = require('@googleapis/chat');
    
    /**
    * Find a direct message Chat space for a user.
    * @return {!Promise<!Object>}
    */
    async function findDirectMessageSpace() {
      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.findDirectMessage(
          {name: 'users/USER'});
    }
    
    findDirectMessageSpace().then(console.log);
    
  3. In the code, replace USER with the name of a User in Google Chat.

  4. In your working directory, run the sample:

    node app-find-direct-message-space.js
    

The Chat API returns an instance of Space that details the specified DM.