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

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

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

前提条件

Node.js

更新调用用户的聊天室已读状态

如需更新用户在聊天室中的已读状态,请在请求中添加以下内容:

  • 指定 chat.users.readstate 授权范围。
  • 调用 UpdateSpaceReadState() 方法。
  • 传递 updateMask,其值为 lastReadTime
  • spaceReadState 作为 SpaceReadState 的实例传递,并包含以下内容:
    • name 字段设置为要更新的聊天室已读状态,其中包括用户 ID 或别名以及聊天室 ID。更新聊天室已读状态仅支持更新调用用户的已读状态,您可以通过设置以下任一项来指定该状态:
      • me 别名。例如, users/me/spaces/SPACE/spaceReadState
      • 调用用户的 Workspace 电子邮件地址。例如, users/user@example.com/spaces/SPACE/spaceReadState
      • 调用用户的用户 ID。例如, users/USER/spaces/SPACE/spaceReadState
    • lastReadTime 字段设置为用户聊天室已读状态更新时间的更新值。通常,这与最后一条已读消息的时间戳或用户指定的时间戳(用于标记聊天室中的最后一条已读消息的位置)相对应。当 lastReadTime 早于最新消息创建时间时,聊天室在界面中显示为未读。如需将聊天室标记为已读,请将 lastReadTime 设置为晚于(大于)最新消息创建时间的任何值。lastReadTime 会被强制转换为与最新消息创建时间一致。请注意,聊天室已读状态仅影响聊天室顶级对话中可见的消息的已读状态。线程中的回复不受此时间戳的影响,而是依赖于线程已读状态。

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

Node.js

chat/client-libraries/cloud/update-space-read-state-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = [
  'https://www.googleapis.com/auth/chat.users.readstate',
];

// This sample shows how to update a space read state for the calling user
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(
    USER_AUTH_OAUTH_SCOPES,
  );

  // Initialize request argument(s)
  const timestamp = new Date('2000-01-01').getTime();
  const request = {
    spaceReadState: {
      // Replace SPACE_NAME here
      name: 'users/me/spaces/SPACE_NAME/spaceReadState',
      lastReadTime: {
        seconds: Math.floor(timestamp / 1000),
        nanos: (timestamp % 1000) * 1000000,
      },
    },
    updateMask: {
      // The field paths to update.
      paths: ['last_read_time'],
    },
  };

  // Make the request
  const response = await chatClient.updateSpaceReadState(request);

  // Handle the response
  console.log(response);
}

await main();

如需运行此示例,请将 SPACE_NAME 替换为 聊天室 name中的 ID。 您可以通过调用 ListSpaces() 方法或从聊天室的网址获取 ID。

Google Chat API 会更新指定的聊天室已读状态,并返回 an instance of SpaceReadState