Skip to content

Instant Messaging API

Chat messaging, history, revocation, and read status management.

API Reference

fetchHistoryMessages()

⚠️ 业务开发者通常无需调用本方法。 进房时 SDK 已自动加载课堂历史; 业务层使用消息列表请优先使用以下三个 API:

  • loadOlderMessages(count) — UI 滚动到顶部时向上分页
  • loadNewerMessages(count) — UI 滚动到底部时向下渐进分页
  • seekToLatestMessages() — 一键回到最新("↓ N 条新消息"按钮)

⚠️ Application developers normally do NOT need to call this method. The SDK auto-loads classroom history on join. For day-to-day list interaction, prefer the three sibling APIs:

  • loadOlderMessages(count) — backward pagination on scroll-to-top
  • loadNewerMessages(count) — progressive forward pagination on scroll-to-bottom
  • seekToLatestMessages() — one-shot jump-to-latest ("↓ N new messages" button)

── 以下为高级/兜底用途说明(业务侧基本不会用到) ──

Fetch full classroom history messages (join-time history; calls the record/getClassMessage backend API).

进房时 SDK 会自动调用一次(fire-and-forget,不阻断进房流程),通常无需外部主动调用; 如需手动重拉/刷新(例如自动调用失败后的兜底入口),可显式调用本方法。

The SDK invokes this automatically once during joinClass (fire-and-forget; does not block the join flow), so external code rarely needs to call it. Use it as a manual refresh / retry entry point when the auto-call failed.

loadOlderMessages / loadNewerMessages 的区别:

  • fetchHistoryMessages()课堂后台 HTTP,覆盖进房前服务端持久化的全部历史
  • loadOlderMessages(count)TIM SDK getMessageListHopping(direction=0),按 sequence 向上分页
  • loadNewerMessages(count)TIM SDK getMessageListHopping(direction=1),按 sequence 向下分页

Difference vs. loadOlderMessages / loadNewerMessages:

  • fetchHistoryMessages() uses the classroom HTTP backend, returning the full server-persisted history that existed before the user joined.
  • loadOlderMessages(count) uses TIM SDK getMessageListHopping (direction=0) for sequence-based backward pagination.
  • loadNewerMessages(count) uses TIM SDK getMessageListHopping (direction=1) for sequence-based forward pagination.

AV ChatRoom groups don't keep TIM history; pre-join content can only be retrieved here.

消息列表内置 500 条上限(IM_MSG_LIST_MAX_SIZE),后端返回过多时自动截断为最新一页; 截断的更老消息可后续通过 loadOlderMessages 按需补拉。

The list is capped at 500 messages; if the backend returns more, only the latest page is kept. Trimmed older messages can be paged in later via loadOlderMessages.

Returns: Promise<TResult<Message[]>>

Example:

ts
// 自动重试:进房后若 messageList$ 仍为空,主动重拉一次
setTimeout(async () => {
  if (classroom.state.messageList$.get().length === 0) {
    const res = await classroom.fetchHistoryMessages();
    console.log('补拉到', res.ok ? res.data.length : 0, '条历史消息');
  }
}, 3000);

loadNewerMessages()

Load newer messages (TIM SDK getMessageListHopping with direction=1; call when the user returns from history toward present).

使用场景:用户调用 loadOlderMessages 多次后,state.messageList$ 末尾停留在过去某个 seq; 期间又有实时消息因 500 条上限被裁掉,本方法把这段缺失的更新消息补回末尾。

Use case: after multiple loadOlderMessages calls the list tail sits at an older seq; meanwhile real-time messages were trimmed due to the 500-entry cap. This method fills the gap by appending newer messages to the list tail.

实现:调用 TIM getMessageListHopping,pivot 取 state.messageList$ 末尾最新消息的 seq, direction=1 表示拉更新的消息;返回结果按 seq 升序 + 与已有列表防御性 seq 去重后 append 到末尾; append 模式可能触发 IM_MSG_LIST_MAX_SIZE 裁剪(裁掉头部最老消息)。

Implementation: calls TIM getMessageListHopping with direction=1 using the tail (newest) message seq of state.messageList$ as the pivot; returned messages are sorted by seq ASC, deduped against the current list by seq, then appended to the tail. Append mode may trigger trimming of the oldest messages (IM_MSG_LIST_MAX_SIZE).

Note: When messageList$ is empty there's no anchor; this returns tok([]).

对齐腾讯云 IM Web SDK 文档:https://cloud.tencent.com/document/product/269/75322

ParameterTypeDescription
count?numberMessages per call (default 15, TIM hard-cap 15)

Returns: Promise<TResult<Message[]>>

Example:

ts
// 滚动到底部时回追到最新 / Catch up to the present on scroll-to-bottom
msgListEl.addEventListener('scroll', async () => {
  const atBottom = msgListEl.scrollTop + msgListEl.clientHeight >= msgListEl.scrollHeight - 2;
  if (atBottom) {
    const more = await classroom.loadNewerMessages(15);
    if (more.ok && more.data.length === 0) console.log('已是最新');
  }
});

loadOlderMessages()

Load older messages (TIM SDK getMessageListHopping with direction=0; call when chat list scrolls to top).

实现:调用 TIM getMessageListHopping,pivot 取 state.messageList$ 头部最老消息的 seq, direction=0 表示拉更旧的消息;返回结果按 seq 升序 + 与已有列表防御性 seq 去重后 prepend 到头部。

Implementation: calls TIM getMessageListHopping with direction=0 using the head (oldest) message seq of state.messageList$ as the pivot; returned messages are sorted by seq ASC, deduped against the current list by seq, then prepended to the head.

Note: When messageList$ is empty there's no anchor; this returns tok([]) and you should call fetchHistoryMessages() first to populate the initial history.

Difference vs. fetchHistoryMessages(): this method uses TIM SDK pagination, while fetchHistoryMessages() uses the classroom HTTP backend (one-shot).

消息列表内置 500 条上限,本方法 prepend 时不强制裁剪——允许用户主动扩窗加载更老内容; 后续实时消息追加(append 模式)会逐步把超额的老消息挤出。

The list is capped at 500 entries; this method prepends without forced trimming so users can intentionally widen the view. Subsequent real-time appends gradually displace the over-cap older messages.

对齐腾讯云 IM Web SDK 文档:https://cloud.tencent.com/document/product/269/75322

ParameterTypeDescription
count?numberMessages per call (default 15, TIM hard-cap 15)

Returns: Promise<TResult<Message[]>>

Example:

ts
// 滚动到顶部时分页加载 / Page in older messages on scroll-to-top
msgListEl.addEventListener('scroll', async () => {
  if (msgListEl.scrollTop === 0) {
    const more = await classroom.loadOlderMessages(15);
    if (more.ok && more.data.length === 0) console.log('已到最顶');
  }
});

markAllMessagesAsRead()

Mark all messages as read, resetting the unread count to zero.

Synchronously updates state.messageUnreadCount$ to 0.

Returns: void

Example:

ts
// 用户切换到聊天面板时调用 / Call when user switches to chat panel
onActivateChatPanel(() => classroom.markAllMessagesAsRead());

markMessageAsRead()

Mark messages up to (and including) the specified seq as read.

Use to incrementally update read state when the chat list scrolls past a message.

ParameterTypeDescription
seqnumberMessage sequence number (Message.seq)

Returns: void

Example:

ts
// 滚动到底部时标记最新消息已读 / Mark latest as read when scrolled to bottom
onScrollToBottom(() => {
  const last = classroom.state.messageList$.get().at(-1);
  if (last) classroom.markMessageAsRead(last.seq);
});

revokeMessage()

Revoke a message by message ID (only revokes the caller's own messages).

For teacher/assistant to revoke others' messages, use revokeClassMessage(messageSeq) (revoke by IM seq, teacher/assistant permission).

ParameterTypeDescription
messageIdstringMessage ID (the id field on Message, string)

Returns: Promise<TResult>

Example:

ts
// 撤回自己的消息 / Revoke one's own message
await classroom.revokeMessage(message.id);

// 老师撤回他人消息 / Teacher revoking another's message
await classroom.revokeClassMessage(message.seq);

seekToLatestMessages()

Jump back to the latest messages in one call (used to exit history-browsing mode).

用途:用户向上 loadOlderMessages 翻阅一段历史后,想直接返回"实时尾", 不再渐进 loadNewerMessages。本方法循环调用 TIM SDK getMessageList, 累积最新约 100 条消息并整批替换 state.messageList$

Use case: after scrolling up via loadOlderMessages for a while, the user wants to jump straight back to the live tail without progressively calling loadNewerMessages. This method loops getMessageList to gather the latest ~100 messages and replacesstate.messageList$ in a single batch.

状态:

  • state.hasNewerMessages$ → false
  • state.newerMessagesCount$ → 0
  • state.hasOlderMessages$ → 仅当服务端确认无更早消息时置 false,否则保持/置 true

State updates:

  • state.hasNewerMessages$ → false
  • state.newerMessagesCount$ → 0
  • state.hasOlderMessages$ → set to false only when the server confirms no older messages exist; otherwise kept/set to true.

与其它历史 API 的对比:

  • fetchHistoryMessages() — 课堂后台 HTTP,进房历史
  • loadOlderMessages(count) — TIM 向上分页
  • loadNewerMessages(count) — TIM 向下分页(渐进)
  • seekToLatestMessages() — TIM 向后整批拉取,replace,固定 100 条

Comparison with other history APIs:

  • fetchHistoryMessages() — classroom HTTP backend (initial join history)
  • loadOlderMessages(count) — TIM upward pagination
  • loadNewerMessages(count) — TIM downward pagination (progressive)
  • seekToLatestMessages() — TIM batch fetch latest, replace, fixed 100

Returns: Promise<TResult<Message[]>>

Example:

ts
// 用户点击"↓ N 条新消息"按钮 / User taps the "↓ N new messages" button
if (classroom.state.hasNewerMessages$.get()) {
  const r = await classroom.seekToLatestMessages();
  if (r.ok) scrollChatToBottom();
}

sendCustomMessage()

Send a custom message to the group chat (content is serialized as JSON; for business-specific extensions).

Recipients receive the raw payload via TEvent.RECV_CUSTOM_IM_MSG; the protocol structure is up to your business (e.g., reaction effects, interactive commands).

ParameterTypeDescription
dataobjectCustom message data object, will be JSON.stringify'd

Returns: Promise<TResult>

Example:

ts
// 发送 / Send
await classroom.sendCustomMessage({ type: 'reaction', emoji: '👏' });

// 接收 / Receive
classroom.on(TEvent.RECV_CUSTOM_IM_MSG, ({ data, fromUserId }) => {
  const payload = JSON.parse(data); // { type: 'reaction', emoji: '👏' }
  if (payload.type === 'reaction') showReactionAnimation(payload.emoji);
});

sendDirectedMessage()

Send a directed private message visible only to the specified user; excluded from the group chat list.

The recipient sees it in state.messageList$ (with a toUserId field); other members do not.

ParameterTypeDescription
toUserIdstringTarget user ID
textstringMessage text

Returns: Promise<TResult>

Example:

ts
// 老师私下提示某位学生 / Teacher privately reminds a student
await classroom.sendDirectedMessage('student_001', '请准备回答下一个问题');

sendFileMessage()

Send a file message to the group chat (any file format supported).

Difference from uploadCourseware(): this only sends the file link to chat — no courseware library entry and no server-side transcoding.

ParameterTypeDescription
fileFileFile object to send

Returns: Promise<TResult>

Example:

ts
const result = await classroom.sendFileMessage(file);
if (!result.ok) toast.error(result.message);

sendImageMessage()

Send an image message to the group chat (supports jpg/png/gif and other common formats).

The SDK internally handles COS upload + thumbnail generation + group broadcast; upload progress is not exposed.

ParameterTypeDescription
fileFileImage File object (typically from <input type="file"> or a drag event)

Returns: Promise<TResult>

Example:

ts
// 通过 input 上传 / Upload via input
const file = (document.querySelector('input[type=file]') as HTMLInputElement).files![0];
const result = await classroom.sendImageMessage(file);
if (!result.ok) toast.error(result.message);

sendTextMessage()

Send a text message to the group chat, visible to all classroom participants.

ParameterTypeDescription
textstringText content to send

Returns: Promise<TResult>

Example:

ts
const result = await classroom.sendTextMessage('大家好!');
if (!result.ok) toast.error(result.message);