更新用户聊天室的读取状态

本指南介绍了如何在 Google Chat API 的 SpaceReadState 资源中使用 updateSpaceReadState 方法将聊天室标记为已读或未读。

SpaceReadState 资源是一种单例资源,表示 Google Chat 聊天室中指定用户上次阅读的消息的详细信息。

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 适用于 Python 的最新 Google 客户端库。如需安装或更新它们,请在命令行界面中运行以下命令:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用
  • 为 Chat 应用配置授权。要获取聊天室中用户读取状态的详细信息,需要通过 chat.users.readstate 授权范围进行用户身份验证

Node.js

  • Node.js 和 npm
  • 适用于 Node.js 的最新 Google 客户端库。如需安装这些软件包,请在命令行界面中运行以下命令:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用
  • 为 Chat 应用配置授权。要获取聊天室中用户读取状态的详细信息,需要通过 chat.users.readstate 授权范围进行用户身份验证

Apps 脚本

  • 有权访问 Google ChatGoogle Workspace 帐号。
  • 一款已发布的 Chat 应用。如需构建 Chat 应用,请按照此quickstart操作。
  • 为 Chat 应用配置授权。要获取聊天室中用户读取状态的详细信息,需要通过 chat.users.readstate 授权范围进行用户身份验证

更新发起调用的用户的聊天室读取状态

如需在聊天室中更新用户的读取状态,请在请求中包含以下内容:

  • 指定 chat.users.readstate 授权范围。
  • SpaceReadState 资源调用 updateSpaceReadState 方法
  • 传递要获取的聊天室读取状态的 name,其中包括用户 ID 或别名以及聊天室 ID。获取空间读取状态仅支持获取发起调用的用户的读取状态,可以通过设置以下某项来指定该状态:
    • me 别名。例如 users/me/spaces/SPACE/spaceReadState
    • 发起调用的用户的 Workspace 电子邮件地址。例如,users/user@example.com/spaces/SPACE/spaceReadState
    • 发起调用的用户的用户 ID。例如,users/USER/spaces/SPACE/spaceReadState
  • 传递 updateMask,用于指定要更新的空间读取状态的各个方面,该状态支持以下字段路径:
    • lastReadTime:用户聊天室读取状态的更新时间。通常,此值对应于上次读取消息的时间戳,或与用户为标记空间中的上次读取位置而指定的时间戳相对应。当 lastReadTime 早于最新消息创建时间时,相应聊天室在界面中显示为未读。如需将聊天室标记为已读,请将 lastReadTime 设置为比最新消息创建时间更晚(更大)的任何值。系统会强制 lastReadTime 以匹配最新消息创建时间。请注意,聊天室读取状态只会影响在聊天室的顶级对话中可见的消息的读取状态。线程中的回复不受此时间戳的影响,而是依赖于线程读取状态。

以下示例会更新发起调用的用户的聊天室读取状态:

Python

  1. 在您的工作目录中,创建一个名为 chat_spaceReadState_update.py 的文件。
  2. 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. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。
  4. 在您的工作目录中,构建并运行示例:

    python3 chat_spaceReadState_update.py
    

Node.js

  1. 在您的工作目录中,创建一个名为 chat_spaceReadState_update.js 的文件。
  2. 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. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。
  4. 在您的工作目录中,构建并运行示例:

    node chat_spaceReadState_update.js
    

Apps 脚本

此示例使用高级聊天服务调用 Chat API。

  1. 在 Apps 脚本项目的 appsscript.json 文件中添加 chat.users.readstate 授权范围:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.users.readstate"
    ]
    
  2. 在 Apps 脚本项目的代码中添加一个与下面类似的函数:

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

Google Chat API 会更新指定的聊天室读取状态,并返回 SpaceReadState 资源的实例。