保利威文档中心

幫助中心

聊天訊息

更新時間:2026-07-17 15:16:39

一、功能概述

聊天室模块(chat) 提供聊天功能 API,供開發者整合聊天功能。

二、取得 Socket 實例

2.1 取得聊天室 socket 實例

Api 方法: getSocket(check?: false): undefined | Socket

參數說明:

  • check:無需檢查 socket 是否存在,false 類型,可選傳遞

回傳值說明: undefined | Socket 類型

三、聊天室狀態資訊

3.1 取得聊天室資訊

與使用者、聊天室相關的狀態均儲存在聊天室模組中,並透過 getChatInfo 取得聊天室狀態資訊。

Api 方法: getChatInfo(): ChatModuleInfo

回傳值說明: 聊天室狀態資訊,ChatModuleInfo 類型,詳細類型說明如下

屬性名稱 說明 類型
chatExited 聊天室是否已退出 boolean
chatRoomIsClosed 聊天室是否已關閉 boolean
isKicked 是否被踢出 boolean
isShield 是否被禁言 boolean

範例:

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

四、聊天訊息來源

透過聊天室訊息事件 ChatEvents.ChatMessage、聊天歷史記錄 API getChatHistory 等取得的聊天訊息類型皆為 ChatMsgSource 類型。 所有訊息資料都有對應的訊息來源 msgSource 欄位,該欄位為 ChatMsgSource 列舉,開發者可根據該欄位顯示對應的訊息樣式。

Enum 列舉: ChatMsgSource

常數 列舉成員 說明 訊息類型 伺服端訊息
'speak' ChatMsgSource.Speak 發言訊息 ChatMsgSpeakType
'image' ChatMsgSource.Image 圖片訊息 ChatMsgImageType
'emotion' ChatMsgSource.Emotion 表情圖片訊息 ChatMsgEmotionType
'reward' ChatMsgSource.Reward 打賞訊息 ChatMsgRewardType
'file' ChatMsgSource.File 檔案分享訊息 ChatMsgFileType
'redpaper' ChatMsgSource.Redpaper 紅包訊息 ChatMsgRedpaperType
'redpaperReceive' ChatMsgSource.RedpaperReceive 紅包領取訊息 ChatMsgRedpaperReceiveType ×
'customerMessage' ChatMsgSource.CustomerMessage 自訂訊息(伺服端) ChatMsgCustomerMessageType
'customMessage' ChatMsgSource.CustomMessage 自訂訊息(客戶端) ChatMsgCustomMessageType x
'system' ChatMsgSource.System 系統訊息 ChatMsgSystemType ×
'motivationLike' ChatMsgSource.MotivationLike 課堂激勵按讚訊息 ChatMsgMotivationLikeType ×
'speakTop' ChatMsgSource.SpeakTop 評論上牆 - -
'speakCancelTop' ChatMsgSource.SpeakCancelTop - - -
'effect' ChatMsgSource.Effect 訊息特效 - ×
'iarCheckIn' ChatMsgSource.IarCheckIn 簽到訊息 ChatMsgIarCheckInMessageType
'iarAnswerCard' ChatMsgSource.IarAnswerCard 答題卡訊息 ChatMsgIarAnswerCardMessageType
'iarQuestionnaire' ChatMsgSource.IarQuestionnaire 問卷訊息 ChatMsgIarQuestionnaireMessageType
'unknown' ChatMsgSource.Unknown 未知的訊息來源 - ×

五、發送聊天訊息

5.1 發送文字訊息

用於觀眾進行聊天發言,呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件。

Api 方法: sendSpeakMsg(options: SendSpeakMsgOptions): Promise<ChatMsgSpeakType>

參數說明:

  • options:發言參數,SendSpeakMsgOptions 類型,必傳,詳細類型說明如下
參數名 說明 類型 必填 預設值
forceSend 強制發送,忽略禁言判斷 boolean false
content 發言內容 string -
onlyLocalMsg 是否僅發送本地訊息 boolean false
quoteMsg 引用的訊息 ChatMsgQuoteOriginType -

回傳值說明: 發送到伺服器後的消息物件,Promise<ChatMsgSpeakType> 類型,詳細類型說明如下

屬性名稱 說明 類型
id 訊息唯一識別碼 string
msgSource 訊息來源 Speak
time 訊息時間 number
user 使用者資訊 ChatMessageUser<ChatUserType>
content 發言內容 string
quote 回覆內容 ChatMsgQuoteType
isLocal 是否為本地端發送的訊息 boolean
overLen 是否已超出伺服器端文字長度 boolean
isOverLength 是否為超長文字 boolean
isSended 是否已發送完成 boolean
isSendFailed 是否發送失敗 boolean

範例:

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

5.2 發送圖片訊息

用於觀眾發送圖片訊息,呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件。

Api 方法: sendImageMsg(options: SendImageMsgOptions): Promise<ChatMsgImageType>

參數說明:

  • options:傳送圖片參數,SendImageMsgOptions 類型,必填,詳細類型說明如下
參數名 說明 類型 必須 預設值
forceSend 強制發送,忽略禁言判斷 boolean false
imageId 圖片 id,建議使用 uuid(v4) 生成 string -
imageUrl 圖片位址 string -
size 圖片尺寸 Object -

回傳值說明: 發送到伺服器後的圖片訊息物件,Promise<ChatMsgImageType> 類型,詳細類型說明如下

屬性名稱 說明 類型
id 訊息唯一識別碼 string
msgSource 訊息來源 Image
time 訊息時間 number
user 使用者資訊 ChatMessageUser<ChatUserType>
imageId 圖片 id string
imageUrl 圖片位址 string
size 圖片尺寸 Object
isLocal 是否為本地端發送的訊息 boolean
isSended 是否已發送完成 boolean
localImageUrl 本地端發送訊息的圖片位址 string
isIllegal 是否違規 boolean
isSendFailed 是否發送失敗 boolean

範例:

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 發送表情圖片訊息

透過 getEmotionImages 方法取得表情圖片列表後,透過列表項的 idurl 發送表情圖片訊息,呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件。

開發者可透過 getEmotionImages 取得表情圖片列表。

Api 方法: sendEmotionImageMsg(options: SendEmotionImageMsgOptions): Promise<ChatMsgEmotionType>

參數說明:

  • options:發送表情圖片參數,SendEmotionImageMsgOptions 類型,必填,詳細類型說明如下
參數名 說明 類型 必填 預設值
forceSend 強制發送,忽略禁言判斷 boolean false
emotionId 表情 ID string -
emotionUrl 表情圖片網址 string -

回傳值說明: 發送到伺服器後的消息物件,Promise<ChatMsgEmotionType> 類型,詳細類型說明如下

屬性名稱 說明 類型
id 訊息唯一識別碼 string
msgSource 訊息來源 Emotion
time 訊息時間 number
user 使用者資訊 ChatMessageUser<ChatUserType>
emotionId 表情 id string
emotionUrl 表情圖片位址 string
size 圖片尺寸,socket 訊息中沒有尺寸回傳 Object
isLocal 是否為本地端發送的訊息 boolean
isSended 是否已發送完成 boolean
isSendFailed 是否發送失敗 boolean

範例:

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

5.4 發送系統訊息

用於發送系統訊息到聊天區,請注意該訊息並不會發送到伺服器端,呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件。

Api 方法: sendSystemMsg(content: string, type?: string): void

參數說明:

  • content:訊息內容,string 類型,必填

  • type:string 類型,選填

範例:

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

5.5 發送自訂訊息(客戶端)

用於發送自訂訊息(客戶端),呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件,該事件回傳的資料中會對應 ChatMsgSource.CustomMessage 的聊天訊息資料

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

從 v0.10.0 版本開始支援

參數說明:

  • options:自訂訊息選項,SendCustomMessageOptions<T> 類型,必填,詳細類型說明如下
參數名 說明 類型 必須 預設值
EVENT 自訂事件,預設為 'client-custom' string -
data 自訂資料,但需傳入一個物件 T -
version 自訂版本,預設為 1 number -
tip 自訂提示,預設為空 string -
joinHistoryList 是否加入聊天歷史資料,預設為 true boolean -

回傳值說明: 發送成功的自訂訊息 ID,Promise<string> 類型

範例:

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

5.6 插入本地贊助訊息

用於觀眾優先發送本地打賞訊息,呼叫過程中會觸發 ChatEvents.ChatMessage 聊天訊息事件。

注意,插入本地打賞訊息必定為當前觀眾。

Api 方法: insertLocalRewardChatMsg(options: InsertLocalRewardChatMsgOptions): void

從 v0.11.0 版本開始支援

參數說明:

  • options:打賞訊息選項,InsertLocalRewardChatMsgOptions 類型,必填

5.7 根據 id 移除聊天訊息

Api 方法: removeChatMsg(id: string): void

從 v1.2.0 版本開始支援

參數說明:

  • id:string 類型,必填

5.8 根據 id,替換對應的聊天內容

Api 方法: replaceChatMsg(id: string, chatMsg: ChatMsgType): void

從 v1.2.0 版本開始支援

參數說明:

  • id:string 類型,必填

  • chatMsg:ChatMsgType 類型,必填

六、監聽聊天訊息事件

當有觀眾發言、打賞等涉及聊天訊息操作時,聊天室模組會回呼 ChatEvents.ChatMessage 事件,開發者可透過監聽該事件進行聊天訊息的渲染。

由於本地發送訊息時,在發送至伺服器端前就會回呼 ChatEvents.ChatMessage 事件,此時回呼的訊息 id 即 chatMsg.id 為本地建立的 id,伺服器端回呼後,透過 ChatEvents.ReplaceChatMessage 進行訊息資料替換(包括圖片違規等均透過該事件修改訊息資料)。

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;
  }
  // 将视图的消息节点替换...
});

七、取得聊天歷史記錄

7.1 設定聊天歷史訊息是否加密

getChatHistoryByTime 方法支援加密回傳

Api 方法: setChatHistoryEncrypt(chatHistoryEncrypt: boolean): void

從 v2.9.0 版本開始支援

參數說明:

  • chatHistoryEncrypt:聊天歷史訊息是否加密,boolean 類型,必填

7.2 取得聊天歷史訊息

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

從 v2.16.0 開始棄用 透過 getChatHistory 方法取得頻道下的聊天歷史訊息。

參數說明:

  • options:獲取選項,GetChatHistoryOptions 類型,選填,預設 {},詳細類型說明如下
參數名稱 說明 類型 必要 預設值
start 訊息起始索引 number 0
end 訊息終止索引 number 9
onlySpecialMsg 是否僅取得特殊角色發言 boolean false
filterCustomMsg 是否過濾自訂訊息 boolean true
filterRedpaperMsg 是否過濾紅包資訊 boolean false

回傳值說明: Promise<ChatMsgType[]> 類型

範例:

// 获取 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 根據場次號碼分頁取得聊天歷史訊息

透過 getChatHistoryBySessionId 方法取得直播場次中的聊天歷史記錄

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

參數說明:

  • options:獲取選項,GetChatHistoryBySessionIdOptions 類型,必填,詳細類型說明如下
參數名稱 說明 類型 必填 預設值
sessionId 場次 ID string -
pageNumber 頁數 number 1
pageSize 每頁數量 number 10

回傳值說明: Promise<PageContent<ChatMsgType>> 類型

範例:

// 指定的场次号
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 根據時間戳記取得聊天歷史訊息

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

從 v0.9.0 版本開始支援

參數說明:

  • options:請求選項,GetChatHistoryByTimeOptions 類型,必填,詳細類型說明如下
參數名稱 說明 類型 必填 預設值
timestamp 時間戳記 number -
count 時間戳記對應的數量 number 1
size 取得的數量 number 10
exclude 排除的訊息類型 string[] -
validateExcludeMsgSource 是否驗證「排除的訊息類型」 boolean true
mode 聊天請求歷史資料模式 ChatRequestHistoryMode -
onlySpecialMsg 是否僅取得特殊身份訊息 boolean false

回傳值說明: 訊息列表,Promise<ChatMsgType[]> 類型

八、訊息/留言上牆

8.1 取得評論上牆資料

Api 方法: getSpeakTopInfo(): undefined | ChatMsgSpeakTopType

從 v1.5.0 版本開始支援

回傳值說明: undefined | ChatMsgSpeakTopType 類型

8.2 設定評論上牆資料

Api 方法: setSpeakTop(data: ChatMsgSpeakTopType | SliceIdSpeakTop): void

從 v1.5.0 版本開始支援

參數說明:

  • data:ChatMsgSpeakTopType | SliceIdSpeakTop 類型,必填

8.3 取消留言上牆

Api 方法: cancelSpeakTop(): void

從 v1.5.0 版本開始支援

九、訊息/檔案

9.1 取得頻道檔案列表

Api 方法: getChannelFileList(params: GetChannelFileListParams): Promise<GetChannelFileListResponse>

從 v2.6.0 版本開始支援

參數說明:

  • params:GetChannelFileListParams 類型,必填,詳細類型說明如下
參數名稱 說明 類型 必填 預設值
pageSize - number -
pageNumber - number -

回傳值說明: Promise<GetChannelFileListResponse> 類型,詳細類型說明如下

屬性名稱 說明 類型
list - ChannelFileListItem[]
page - number
size - number
totalCount - number
totalPage - number

十、其他

10.1 取得超長訊息的完整文字

講師可發送超過 2000 字的文字訊息,該訊息為超長文字訊息(透過 chatMsg.isOverLength === true 判斷),chat 提供的訊息文字只會回傳前 1000 字的訊息字串,如需顯示完整的訊息文字,可呼叫該方法取得。

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

參數說明:

  • id:聊天訊息 id,string 類型,必填

  • chatMsg:聊天訊息,在未超過伺服器端聊天文字長度或請求異常時,會使用聊天訊息內容回傳 [v0.11.0 新增],ChatMsgSpeakType 類型,選填,詳細類型說明如下

參數名 說明 類型 必須 預設值
id 訊息唯一識別碼 string -
msgSource 訊息來源 Speak -
time 訊息時間 number -
user 使用者資訊 ChatMessageUser<ChatUserType> -
content 發言內容 string -
quote 回覆內容 ChatMsgQuoteType -
isLocal 是否為本地端發送的訊息 boolean -
overLen 是否已超出伺服器端文字長度 boolean -
isOverLength 是否為超長文字 boolean -
isSended 是否已發送完成 boolean -
isSendFailed 是否發送失敗 boolean -

回傳值說明: Promise<string> 類型

範例:

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 取得聊天室設定

從 v1.2.0 開始可以透過 PlvChatModule.generateDefaultChatSetting() 來取得預設配置

用於獲取管理後台的聊天室設定資訊。

Api 方法: getChatSetting(): ChatSetting

回傳值說明: 聊天室設定資訊,ChatSetting 類型,詳細類型說明如下

屬性名稱 說明 類型
watchChatEnabled 聊天室是否長時間未使用 boolean
showCustomMessageEnabled 是否顯示自訂訊息 boolean
quoteReplyEnabled 聊天引用回覆開關 boolean
chatTranslateEnabled 翻譯開關 boolean
chatRobotEnabled 虛擬人數開關 boolean
restrictChatEnabled 聊天室並發人數限制開關 boolean
likeEnabled 點讚開關 boolean
likeSingleClickEnabled 單擊點讚開關 boolean
likeHoldEnabled 長按點讚開關 boolean
filterManagerMsgEnabled 是否只看主持人資訊 boolean
viewerSendImgEnabled 傳送圖片開關 boolean
welcomeEnabled 歡迎語開關 boolean
emotionalFeedbackEnabled 情緒回饋開關 boolean
chatOnlineNumberEnable 聊天室線上人數開關 boolean
faceEmotionEnabled 黃臉表情開關 boolean
imageEmotionEnabled 圖片表情開關 boolean
getChatHistoryByTimestampEnabled 根據時間戳記取得聊天歷史記錄 boolean
chatMessageLayout 聊天訊息佈局 ChatMessageLayout
portraitChatMessageLayout 直式聊天訊息佈局 ChatMessageLayout
chatMessageAvatarDisplay 聊天訊息頭像是否顯示 boolean
portraitChatMessageAvatarDisplay 直式聊天訊息頭像是否顯示 boolean
chatUIVersion 聊天室 UI 版本 'v1' | 'v2'
likeIconUrl 點讚圖示 string
likeIconType 點讚圖示類型 string
likeEffectType 點讚特效類型 LikeEffectType
likeEffectIcons 點讚特效配置 string[]
likeCountEnabled 是否顯示點讚數 boolean

範例:

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

10.3 轉換發言內容

透過 parseSpeakContent 將觀眾發言中的表情、連結轉換為 HTML 元素。

轉換順序:parseLink > removeEmotion > parseEmotion > parseLineBreak

Api 方法: parseSpeakContent(content: string, options?: ParseOptions): string

參數說明:

  • content:發言內容,string 類型,必傳

  • options:轉換選項,ParseOptions 類型,選填,詳細類型說明如下

參數名 說明 類型 必須 預設值
parseLink 是否轉換連結 boolean false
removeEmotion 移除表情內容 boolean false
parseEmotion 是否轉換表情 boolean false
parseLineBreak 是否轉換換行符 boolean false

回傳值說明: 轉換後的 HTML 字元

範例:

// 转换链接
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 />这是另一段文字
联系客服,在线咨询