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

本指南介绍了如何在updateSpaceReadState SpaceReadState 资源,用于将聊天室标记为已读或未读。

通过 SpaceReadState 资源 是一种单例资源, 指定用户最近在 Google Chat 聊天室中阅读的消息。

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Node.js

  • Node.js 14 或更高版本
  • npm 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    npm install @google-cloud/local-auth @googleapis/chat
    

Apps 脚本

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

如需在聊天室中更新用户的读取状态,请将以下代码添加到 您的请求:

  • 指定 chat.users.readstate 授权范围。
  • 调用 updateSpaceReadState 方法SpaceReadState 资源
  • 传递要获取的聊天室读取状态的 name,其中包括用户 ID 或 别名和聊天室 ID。获取空间读取状态仅支持获取读取 调用用户的状态,可以通过设置 以下:
    • me 别名。例如 users/me/spaces/SPACE/spaceReadState
    • 发起调用的用户的 Workspace 电子邮件地址。例如,users/user@example.com/spaces/SPACE/spaceReadState
    • 发起调用的用户的用户 ID。例如,users/USER/spaces/SPACE/spaceReadState
  • 传递 updateMask,用于指定空间读取状态的各个方面。 update,它支持以下字段路径:
    • 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:聊天室名称。 您可以从 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:聊天室名称。 您可以从 spaces.list 方法 或通过聊天室网址发送。
  4. 在您的工作目录中,构建并运行该示例:

    node chat_spaceReadState_update.js
    

Apps 脚本

此示例使用 高级聊天服务

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

    "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 资源