Polyv Help Center

Help Center

Chat Messages

Updated: 2026-08-28 16:01:47

1. Feature Overview

聊天室模块(chat) provides a chat API for developers to integrate chat functionality.

2. Obtaining a Socket Instance

2.1 Obtaining the Chat Room Socket Instance

Api Method: getSocket(check?: false): undefined | Socket

Parameter Description:

  • check: No need to check whether the socket exists, false type, optional.

Return Value Description: undefined | Socket type

3. Chat Room Status Information

3.1 Retrieving Chat Room Information

All states related to users and chat rooms are stored in the chat room module, and the chat room state information is obtained through getChatInfo.

Api Method: getChatInfo(): ChatModuleInfo

Return Value Description: Chat room status information, ChatModuleInfo type. Detailed type description is as follows:

Property Name Description Type
chatExited Whether the chat room has been exited boolean
chatRoomIsClosed Whether the chat room is closed boolean
isKicked Whether the user has been kicked out boolean
isShield Whether the user has been muted boolean

Example:

const chatInfo = watchCore.chat.getChatInfo();
console.log('房间是否被关闭', chatInfo.chatRoomIsClosed);
console.log('当前用户是否被禁言', chatInfo.isShield);

IV. Chat Message Sources

The chat message types obtained through the chat room message event ChatEvents.ChatMessage, chat history API getChatHistory, etc., are all of the ChatMsgSource type.
All message data has a corresponding message source msgSource field, which is of the ChatMsgSource enum. Developers can display the corresponding message style based on this field.

Enum: ChatMsgSource

Constant Enum Member Description Message Type Server Message
'speak' ChatMsgSource.Speak Speech message ChatMsgSpeakType
'image' ChatMsgSource.Image Image message ChatMsgImageType
'emotion' ChatMsgSource.Emotion Emoji image message ChatMsgEmotionType
'reward' ChatMsgSource.Reward Reward message ChatMsgRewardType
'file' ChatMsgSource.File File sharing message ChatMsgFileType
'redpaper' ChatMsgSource.Redpaper Red envelope message ChatMsgRedpaperType
'redpaperReceive' ChatMsgSource.RedpaperReceive Red envelope claim message ChatMsgRedpaperReceiveType ×
'customerMessage' ChatMsgSource.CustomerMessage Custom message (server) ChatMsgCustomerMessageType
'customMessage' ChatMsgSource.CustomMessage Custom message (client) ChatMsgCustomMessageType x
'system' ChatMsgSource.System System message ChatMsgSystemType ×
'motivationLike' ChatMsgSource.MotivationLike Classroom incentive like message ChatMsgMotivationLikeType ×
'speakTop' ChatMsgSource.SpeakTop Comment pinned to wall - -
'speakCancelTop' ChatMsgSource.SpeakCancelTop - - -
'effect' ChatMsgSource.Effect Message effect - ×
'iarCheckIn' ChatMsgSource.IarCheckIn Check-in message ChatMsgIarCheckInMessageType
'iarAnswerCard' ChatMsgSource.IarAnswerCard Quiz card message ChatMsgIarAnswerCardMessageType
'iarQuestionnaire' ChatMsgSource.IarQuestionnaire Survey message ChatMsgIarQuestionnaireMessageType
'unknown' ChatMsgSource.Unknown Unknown message source - ×

5. Sending Chat Messages

5.1 Sending Text Messages

Used for audience members to send chat messages. Calling this will trigger the ChatEvents.ChatMessage chat message event.

Api Method: sendSpeakMsg(options: SendSpeakMsgOptions): Promise<ChatMsgSpeakType>

Parameter Description:

  • options: Speech parameters, SendSpeakMsgOptions type, required. Detailed type description is as follows:
Parameter Name Description Type Required Default Value
forceSend Force send, ignore mute judgment boolean No false
content Message content string Yes -
onlyLocalMsg Whether to send only local messages boolean No false
quoteMsg Referenced message ChatMsgQuoteOriginType No -

Return Value Description: The message object after being sent to the server, of type Promise<ChatMsgSpeakType>. The detailed type description is as follows:

Property Name Description Type
id Unique message identifier string
msgSource Message source Speak
time Message timestamp number
user User information ChatMessageUser<ChatUserType>
content Message content string
quote Reply content ChatMsgQuoteType
isLocal Whether the message was sent locally boolean
overLen Whether the text exceeds the server-side length limit boolean
isOverLength Whether it is an overly long text boolean
isSended Whether the message has been fully sent boolean
isSendFailed Whether the message failed to send boolean

Example:

import { ChatMsgQuoteOriginType, ChatMsgSpeakType } from '@polyv/live-watch-sdk';
// 发送的文本
const content = '今天天气真好[呲牙][酷]';
// 被回复的消息
const currentQuoteMsg: ChatMsgSpeakType | undefined = undefined;
// 发送消息
watchCore.chat.sendSpeakMsg({
  content,
  quoteMsg: currentQuoteMsg,
});

5.2 Sending Image Messages

Used for viewers to send image messages. Calling this will trigger the ChatEvents.ChatMessage chat message event.

Api Method: sendImageMsg(options: SendImageMsgOptions): Promise<ChatMsgImageType>

Parameter Description:

  • options: Image sending parameters, SendImageMsgOptions type, required. Detailed type description is as follows:
Parameter Description Type Required Default
forceSend Force send, ignore mute judgment boolean No false
imageId Image ID, recommended to generate using uuid(v4) string Yes -
imageUrl Image URL string Yes -
size Image dimensions Object No -

Return Value Description: The image message object after being sent to the server, of type Promise<ChatMsgImageType>. The detailed type description is as follows:

Property Description Type
id Unique message identifier string
msgSource Message source Image
time Message timestamp number
user User information ChatMessageUser<ChatUserType>
imageId Image ID string
imageUrl Image URL string
size Image dimensions Object
isLocal Whether the message was sent locally boolean
isSended Whether sending is complete boolean
localImageUrl Image URL for locally sent messages string
isIllegal Whether it violates rules boolean
isSendFailed Whether sending failed boolean

Example:

import { uuidV4 } from '@polyv/utils/string';
// 图片 id
const imageId = uuidV4();
// 图片地址
const imageUrl = '发送到图片地址,需要带有协议';
// 图片地址
const size = { width: 200, height: 100 };
// 发送图片消息
watchCore.chat.sendImageMsg({ imageId, imageUrl, size });

5.3 Sending Emoji Image Messages

After obtaining the emoji image list via the getEmotionImages method, send emoji image messages using id and url of the list items. During the call, the ChatEvents.ChatMessage chat message event will be triggered.

Developers can obtain the list of emoji images via getEmotionImages.

Api Method: sendEmotionImageMsg(options: SendEmotionImageMsgOptions): Promise<ChatMsgEmotionType>

Parameter Description:

  • options: Parameters for sending emoji images, type SendEmotionImageMsgOptions, required. Detailed type description is as follows:
Parameter Description Type Required Default
forceSend Force send, ignore mute judgment boolean No false
emotionId Emoji ID string Yes -
emotionUrl Emoji image URL string Yes -

Return Value Description: The message object after being sent to the server, of type Promise<ChatMsgEmotionType>. The detailed type description is as follows:

Property Description Type
id Unique message identifier string
msgSource Message source Emotion
time Message timestamp number
user User information ChatMessageUser<ChatUserType>
emotionId Emoji ID string
emotionUrl Emoji image URL string
size Image dimensions (not returned in socket messages) Object
isLocal Whether the message was sent locally boolean
isSended Whether sending is complete boolean
isSendFailed Whether sending failed boolean

Example:

// 获取表情图片列表
const emotionImages = await watchCore.chat.getEmotionImages();
// 发送表情图片
const item = emotionImages[2];
watchCore.chat.sendEmotionImageMsg({ emotionId: item.id, emotionUrl: item.url });

5.4 Sending System Messages

Used to send system messages to the chat area. Note that this message is not sent to the server; during the call, it triggers the ChatEvents.ChatMessage chat message event.

Api Method: sendSystemMsg(content: string, type?: string): void

Parameter Description:

  • content: Message content, string type, required

  • type: string type, optional

Example:

watchCore.chat.sendSystemMsg('聊天室已关闭');

5.5 Sending Custom Messages (Client)

Used to send custom messages (client-side). During the call, the ChatEvents.ChatMessage chat message event is triggered. The data returned by this event corresponds to the chat message data of ChatMsgSource.CustomMessage.

Api Method: sendCustomMessage(options: SendCustomMessageOptions<T>): Promise<string>

Supported since version v0.10.0

Parameter Description:

  • options: Custom message options, type SendCustomMessageOptions<T>, required. Detailed type description is as follows:
Parameter Description Type Required Default
EVENT Custom event, defaults to 'client-custom' string No -
data Custom data, must be an object T Yes -
version Custom version, defaults to 1 number No -
tip Custom prompt, defaults to empty string No -
joinHistoryList Whether to include chat history data, defaults to true boolean No -

Return Value Description: The ID of the custom message that was successfully sent, of type Promise<string>.

Example:

watchCore.chat.sendCustomMessage({ data: { test: '测试' } });

5.6 Inserting Local Tip Messages

Used for the audience to prioritize sending local reward messages. During the call, the ChatEvents.ChatMessage chat message event will be triggered.

Note: The local tip message will definitely be inserted for the current viewer.

Api Method: insertLocalRewardChatMsg(options: InsertLocalRewardChatMsgOptions): void

Supported since version v0.11.0

Parameter Description:

  • options: Tip message options, type InsertLocalRewardChatMsgOptions, required.

5.7 Remove Chat Message by ID

Api Method: removeChatMsg(id: string): void

Supported since version v1.2.0

Parameter Description:

  • id: string type, required

5.8 Replace the corresponding chat content by ID

Api Method: replaceChatMsg(id: string, chatMsg: ChatMsgType): void

Supported since version v1.2.0

Parameter Description:

  • id: string type, required

  • chatMsg: ChatMsgType type, required

VI. Listening to Chat Message Events

When a viewer speaks, sends a tip, or performs other chat message operations, the chat room module will trigger the ChatEvents.ChatMessage event. Developers can listen for this event to render chat messages.

Since local message sending triggers the ChatEvents.ChatMessage event before the message reaches the server, the message ID at this point, i.e., chatMsg.id, is a locally generated ID. After the server callback, message data is replaced via ChatEvents.ReplaceChatMessage (including modifications for violations such as inappropriate images, all handled through this event).

import { ChatEvents, ChatMsgType } from "@polyv/live-watch-sdk";

// 聊天消息列表
const chatMsgList: ChatMsgType[] = [];

// 聊天消息事件
watchCore.chat.eventEmitter.on(ChatEvents.ChatMessage, (data) => {
  // 插入到聊天消息列表
  chatMsgList.push(data.chatMsg);
  // 渲染聊天消息...
});

// 替换聊天消息数据事件
watchCore.chat.eventEmitter.on(ChatEvents.ReplaceChatMessage, (data) => {
  // 需要被替换的消息 id
  const replaceId = data.id;
  // 新的消息对象
  const chatMsg = data.chatMsg;

  const index = chatMsgList.findIndex((item) => item.id === replaceId);
  if (index !== -1) {
    chatMsgList[index] = chatMsg;
  }
  // 将视图的消息节点替换...
});

VII. Retrieving Chat History

7.1 Setting Whether Chat History Messages Are Encrypted

Only the getChatHistoryByTime method supports encrypted return.

Api Method: setChatHistoryEncrypt(chatHistoryEncrypt: boolean): void

Supported since version v2.9.0

Parameter Description:

  • chatHistoryEncrypt: Whether chat history messages are encrypted, type boolean, required.

7.2 Retrieving Chat History Messages

Api Method: getChatHistory(options?: GetChatHistoryOptions): Promise<ChatMsgType[]>

Deprecated since v2.16.0 Retrieve chat history messages under a channel using the getChatHistory method.

Parameter Description:

  • options: Get options, type GetChatHistoryOptions, optional, default {}, detailed type description as follows
Parameter Description Type Required Default
start Message start index number No 0
end Message end index number No 9
onlySpecialMsg Whether to retrieve only special role messages boolean No false
filterCustomMsg Whether to filter custom messages boolean No true
filterRedpaperMsg Whether to filter red envelope messages boolean No false

Return Value Description: Promise<ChatMsgType[]> type

Example:

// 获取 0 ~ 19 条消息
const historyData = await watchCore.chat.getChatHistory({
  start: 0,
  end: 19,
});
// 返回数据示例,类型为:ChatMsgType[]
[{
  id: '5191c230-c6c4-11ed-8c31-23e8ced55946',
  time: 1679278200247,
  msgSource: 'speak',
  content: '今天天气真好[呲牙][酷]',
  user: {
    userId: '18012345678',
    nick: '小明',
    pic: '头像地址',
  },
}]

7.3 Paginate Chat History Messages by Session ID

Obtain the chat history of a live broadcast session using the getChatHistoryBySessionId method.

Api Method: getChatHistoryBySessionId(options: GetChatHistoryBySessionIdOptions): Promise<PageContent<ChatMsgType>>

Parameter Description:

  • options: Get options, type GetChatHistoryBySessionIdOptions, required, detailed type description as follows
Parameter Description Type Required Default
sessionId Session ID string Yes -
pageNumber Page Number number No 1
pageSize Items Per Page number No 10

Return Value Description: Promise<PageContent<ChatMsgType>> type

Example:

// 指定的场次号
const sessionId = 'gksk8f2itb';
const result = await watchCore.chat.getChatHistoryBySessionId({
  sessionId,
});
console.log('当前页', result.pageNumber);
console.log('每页数量', result.pageSize);
console.log('总条目数', result.totalItems);
console.log('总页数', result.totalPages);
console.log('消息列表', result.contents); // ChatMsgType[]

7.4 Retrieve Chat History Messages by Timestamp

Api Method: getChatHistoryByTime(options: GetChatHistoryByTimeOptions): Promise<ChatMsgType[]>

Supported since version v0.9.0

Parameter Description:

  • options: Request options, type GetChatHistoryByTimeOptions, required. Detailed type description is as follows:
Parameter Name Description Type Required Default Value
timestamp Timestamp number No -
count Quantity corresponding to the timestamp number No 1
size Quantity retrieved number No 10
exclude Excluded message types string[] No -
validateExcludeMsgSource Whether to validate "excluded message types" boolean No true
mode Chat request history data mode ChatRequestHistoryMode No -
onlySpecialMsg Whether to retrieve only special identity messages boolean No false

Return Value Description: Message list, Promise<ChatMsgType[]> type

8. Message/Comment Pinning

8.1 Retrieve Comment Wall Data

Api Method: getSpeakTopInfo(): undefined | ChatMsgSpeakTopType

Supported since version v1.5.0

Return Value Description: undefined | ChatMsgSpeakTopType type

8.2 Setting Comment Approval Data

Api Method: setSpeakTop(data: ChatMsgSpeakTopType | SliceIdSpeakTop): void

Supported since version v1.5.0

Parameter Description:

  • data: ChatMsgSpeakTopType | SliceIdSpeakTop type, required

8.3 Cancel Comment Approval

Api Method: cancelSpeakTop(): void

Supported since version v1.5.0

IX. Messages/Files

9.1 Get Channel File List

Api Method: getChannelFileList(params: GetChannelFileListParams): Promise<GetChannelFileListResponse>

Supported since version v2.6.0

Parameter Description:

  • params: GetChannelFileListParams type, required, detailed type description as follows
Parameter Name Description Type Required Default Value
pageSize - number No -
pageNumber - number No -

Return Value Description: Promise<GetChannelFileListResponse> type, detailed type description as follows

Property Name Description Type
list - ChannelFileListItem[]
page - number
size - number
totalCount - number
totalPage - number

10. Miscellaneous

10.1 Retrieving the Full Text of an Overly Long Message

Instructors can send text messages exceeding 2,000 characters, which are considered extra-long text messages (determined by chatMsg.isOverLength === true). chat only returns the first 1,000 characters of the message string. To display the complete message text, you can call this method to retrieve it.

Api Method: getFullMessage(id: string, chatMsg?: ChatMsgSpeakType): Promise<string>

Parameter Description:

  • id: Chat message ID, type string, required.

  • chatMsg: Chat message. When the chat text does not exceed the server's length limit or when a request exception occurs, the chat message content will be returned [Added in v0.11.0], ChatMsgSpeakType type, optional. Detailed type description is as follows:

Parameter Name Description Type Required Default Value
id Unique message identifier string Yes -
msgSource Message source Speak Yes -
time Message timestamp number Yes -
user User information ChatMessageUser<ChatUserType> Yes -
content Message content string Yes -
quote Reply content ChatMsgQuoteType No -
isLocal Whether the message was sent locally boolean No -
overLen Whether the server-side text length has been exceeded boolean No -
isOverLength Whether it is an overly long text boolean No -
isSended Whether the message has been fully sent boolean No -
isSendFailed Whether the message failed to send boolean No -

Return Value Description: Promise<string> type

Example:

import { ChatMsgSpeakType } from '@polyv/live-watch-sdk';

async function getFullMessageText(chatMsg: ChatMsgSpeakType): Promise<string> {
  if (!chatMsg.isOverLength) {
    throw new Error('该消息非超长文本');
  }

  const result = await watchCore.chat.getFullMessage(chatMsg.id, chatMsg);
  console.log('完整的文本', result);
  return result;
}

10.2 Retrieving Chat Room Settings

Starting from v1.2.0, the default configuration can be obtained via PlvChatModule.generateDefaultChatSetting().

Used to retrieve the chat room settings information for the admin backend.

Api Method: getChatSetting(): ChatSetting

Return Value Description: Chat room settings information, ChatSetting type. Detailed type description is as follows:

Property Name Description Type
watchChatEnabled Whether the chat room has been unused for a long time boolean
showCustomMessageEnabled Whether to display custom messages boolean
quoteReplyEnabled Chat quote reply toggle boolean
chatTranslateEnabled Translation toggle boolean
chatRobotEnabled Virtual user count toggle boolean
restrictChatEnabled Chat room concurrent user limit toggle boolean
likeEnabled Like toggle boolean
likeSingleClickEnabled Single-click like toggle boolean
likeHoldEnabled Long-press like toggle boolean
filterManagerMsgEnabled Whether to view only host messages boolean
viewerSendImgEnabled Send image toggle boolean
welcomeEnabled Welcome message toggle boolean
emotionalFeedbackEnabled Emotion feedback toggle boolean
chatOnlineNumberEnable Chat room online user count toggle boolean
faceEmotionEnabled Yellow face emoji toggle boolean
imageEmotionEnabled Image emoji toggle boolean
getChatHistoryByTimestampEnabled Retrieve chat history by timestamp boolean
chatMessageLayout Chat message layout ChatMessageLayout
portraitChatMessageLayout Portrait chat message layout ChatMessageLayout
chatMessageAvatarDisplay Whether to show chat message avatar boolean
portraitChatMessageAvatarDisplay Whether to show portrait chat message avatar boolean
chatUIVersion Chat room UI version 'v1' | 'v2'
likeIconUrl Like icon string
likeIconType Like icon type string
likeEffectType Like effect type LikeEffectType
likeEffectIcons Like effect configuration string[]
likeCountEnabled Whether to display like count boolean
customViewerLabelUrl Custom audience tag URL string

Example:

const setting = watchCore.chat.getChatSetting();
console.log('观看页聊天室开关', setting.watchChatEnabled);
console.log('是否显示翻译功能', setting.chatTranslateEnabled);

10.3 Converting Speech Content

Convert the emojis and links in the audience's speech into HTML elements using parseSpeakContent.

Conversion order: parseLink > removeEmotion > parseEmotion > parseLineBreak

Api Method: parseSpeakContent(content: string, options?: ParseOptions): string

Parameter Description:

  • content: The content of the speech, type string, required.

  • options: Conversion options, type ParseOptions, optional, detailed type description as follows

Parameter Name Description Type Required Default Value
parseLink Whether to convert links boolean No false
removeEmotion Remove emoji content boolean No false
parseEmotion Whether to convert emojis boolean No false
parseLineBreak Whether to convert line breaks boolean No false

Return Value Description: Converted HTML characters

Example:

// 转换链接
watchCore.chat.parseSpeakContent('这是我们的官网地址:https://www.polyv.net/', { parseLink: true });
// 转换后的字符串:这是我们的官网地址:<a target="_blank" rel="noopener" href="https://www.polyv.net/">https://www.polyv.net/</a>

// 移除表情
watchCore.chat.parseSpeakContent('今天天气真好[呲牙]', { removeEmotion: true });
// 转换后的字符串:今天天气真好

// 转换表情
watchCore.chat.parseSpeakContent('今天天气真好[呲牙]', { parseEmotion: true });
// 转换后的字符串:今天天气真好<img src="黄脸表情图片地址" alt="呲牙" class="plv-emotion-img" title="呲牙" />

// 将换行符转成 <br />
watchCore.chat.parseSpeakContent('这是一段文字\n这是另一段文字', { parseLineBreak: true });
// 转换后的字符串:这是一段文字<br />这是另一段文字
联系客服,在线咨询
在线咨询