Update a user's space read state

This guide explains how to use the updateSpaceReadState method on the SpaceReadState resource of the Google Chat API to mark spaces as read or unread.

The SpaceReadState resource is a singleton resource that represents details about a specified user's last read message in a Google Chat space.

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
    
  • 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. Getting details about a user's read state within a space requires user authentication with the chat.users.readstate authorization scope.

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. Getting details about a user's read state within a space requires user authentication with the chat.users.readstate authorization scope.

Apps Script

  • A Google Workspace account with access to Google Chat.
  • A published Chat app. To build a Chat app, follow this quickstart.
  • Authorization configured for the Chat app. Getting details about a user's read state within a space requires user authentication with the chat.users.readstate authorization scope.

Update the calling user's space read state

To update a user's read state within a space, include the following in your request:

  • Specify the chat.users.readstate authorization scope.
  • Call the updateSpaceReadState method on the SpaceReadState resource.
  • Pass the name of the space read state to get, which includes a user ID or alias and a space ID. Getting space read state only supports getting the read state of the calling user, which can be specified by setting one of the following:
    • The me alias. For example, users/me/spaces/SPACE/spaceReadState.
    • The calling user's Workspace email address. For example, users/user@example.com/spaces/SPACE/spaceReadState.
    • The calling user's user ID. For example, users/USER/spaces/SPACE/spaceReadState.
  • Pass the updateMask, which specifies the aspects of the space read state to update, which supports the following field paths:
    • lastReadTime: The time when the user's space read state was updated. Usually this corresponds with either the timestamp of the last read message, or a timestamp specified by the user to mark the last read position in a space. When the lastReadTime is before the latest message create time, the space appears as unread in the UI. To mark the space as read, set lastReadTime to any value later (larger) than the latest message create time. The lastReadTime is coerced to match the latest message create time. Note that the space read state only affects the read state of messages that are visible in the space's top-level conversation. Replies in threads are unaffected by this timestamp, and instead rely on the thread read state.

The following example updates the calling user's space read state:

Python

  1. In your working directory, create a file named chat_spaceReadState_update.py.
  2. Include the following code in chat_spaceReadState_update.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.users.readstate"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates the space read state for the calling 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.users().spaces().updateSpaceReadState(
    
            # The space read state to update.
            #
            # Replace USER with the calling user's ID, Workspace email,
            # or the alias me.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='users/me/spaces/SPACE/spaceReadState',
            updateMask='lastReadTime',
            body={'lastReadTime': f'{datetime.datetime(2000, 1, 3).isoformat()}Z'}
    
          ).execute()
    
        # Prints the API's response.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. In the code, replace the following:

    • SPACE: a space name, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.
  4. In your working directory, build and run the sample:

    python3 chat_spaceReadState_update.py
    

Node.js

  1. In your working directory, create a file named chat_spaceReadState_update.js.
  2. Include the following code in chat_spaceReadState_update:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @return {!Promise<!Object>}
    */
    async function updateSpaceReadState() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.users.readstate',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.users.spaces.updateSpaceReadState({
    
        /**
        * The space read state to update.
        *
        * Replace USER with the calling user's ID, Workspace email,
        * or the alias me.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        */
        name: 'users/me/spaces/SPACE/spaceReadState',
        updateMask: 'lastReadTime',
        requestBody: {
          lastReadTime: '{datetime.datetime(2000, 1, 3).isoformat()}Z'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    getSpaceReadState().then(console.log);
    
  3. In the code, replace the following:

    • SPACE: a space name, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.
  4. In your working directory, build and run the sample:

    node chat_spaceReadState_update.js
    

Apps Script

This example calls the Chat API using the Advanced Chat Service.

  1. Add the chat.users.readstate authorization scope to the Apps Script project's appsscript.json file:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.users.readstate"
    ]
    
  2. Add a function like this one to the Apps Script project's code:

    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @param {string} spaceReadStateName The resource name of the space read state.
    */
    function updateSpaceReadState(spaceReadStateName) {
      try {
        const time = new Date('January 1, 2000')).toJSON();
        const body = {'lastReadTime': time};
        Chat.Users.Spaces.updateSpaceReadState(spaceReadStateName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to update read state with error %s', err.message);
      }
    }
    

The Google Chat API updates the specified space read state and returns an instance of SpaceReadState resource.