本指南介绍如何使用 Cloudflare RealtimeKit 在会议中发送和接收聊天消息。
可以在聊天中发送四种类型的消息:
- 文本消息
- 图片
- 文件
- 自定义消息,可在单条消息中组合文本、HTML、文件、图片和视频
会议聊天对象存储在 meeting.chat 中,该对象具有发送、接收和获取消息的方法。
console.log("Chat object:", meeting.chat);要加载聊天历史记录,请使用分页的获取方法。要实时响应新增、编辑和删除的消息,请监听 chatUpdate 事件。
可以在聊天中发送四种类型的消息:
- 文本消息
- 图片
- 文件
- 自定义消息,可在单条消息中组合文本、HTML、文件、图片和视频
会议聊天对象存储在 meeting.chat 中,该对象具有发送、接收和获取消息的方法。
meeting.chat;要加载聊天历史记录,请使用分页的获取方法。要实时响应新增、编辑和删除的消息,请监听 chatUpdate 事件。
可以在聊天中发送三种类型的消息:
- 文本消息
- 图片
- 文件
会议聊天对象存储在 meeting.chat 中,该对象具有发送和接收消息的方法。
meeting.chatmeeting.chat.messages 数组包含在聊天中发送的所有消息。这是一个对象数组,其中每个对象的类型为 com.cloudflare.realtimekit.chat.ChatMessage。
meeting.chat.messages可以在聊天中发送三种类型的消息:
- 文本消息
- 图片
- 文件
会议聊天对象存储在 meeting.chat 中,该对象具有发送和接收消息的方法。
meeting.chatmeeting.chat.messages 数组包含在聊天中发送的所有消息。这是一个对象数组,其中每个对象的类型为 RealtimeKit.ChatMessage。
meeting.chat.messages可以在聊天中发送四种类型的消息:
- 文本消息
- 图片
- 文件
- 自定义消息,可在单条消息中组合文本、HTML、文件、图片和视频
会议聊天对象存储在 meeting.chat 中,该对象具有发送、接收和获取消息的方法。
meeting.chat;要加载聊天历史记录,请使用分页的获取方法。要实时响应新增、编辑和删除的消息,请监听 chatUpdate 事件。
Message 类型的定义如下:
interface BaseMessage<T extends MessageType> {
type: T;
userId: string;
displayName: string;
time: Date;
timeMs?: number;
id: string;
isEdited?: boolean;
read?: boolean;
pluginId?: string;
pinned?: boolean;
targetUserIds?: string[];
}
interface TextMessage extends BaseMessage<MessageType.text> {
message: string;
}
interface ImageMessage extends BaseMessage<MessageType.image> {
link: string;
}
interface FileMessage extends BaseMessage<MessageType.file> {
name: string;
size: number;
link: string;
}
interface MediaItem {
link: string;
type?: string;
name?: string;
size?: number;
}
interface CustomMessage extends BaseMessage<MessageType.custom> {
message?: string;
html?: string;
files?: MediaItem[];
images?: MediaItem[];
videos?: MediaItem[];
}
type Message = TextMessage | ImageMessage | FileMessage | CustomMessage;timeMs 是消息的发送时间,以自 Unix 纪元以来的毫秒数表示。分页获取消息时,请将其用作游标。targetUserIds 在私聊消息中设置,包含该会话中参与者的用户 ID。
Message 类型的定义如下:
interface BaseMessage<T extends MessageType> {
type: T;
userId: string;
displayName: string;
time: Date;
timeMs?: number;
id: string;
isEdited?: boolean;
read?: boolean;
pluginId?: string;
pinned?: boolean;
targetUserIds?: string[];
}
interface TextMessage extends BaseMessage<MessageType.text> {
message: string;
}
interface ImageMessage extends BaseMessage<MessageType.image> {
link: string;
}
interface FileMessage extends BaseMessage<MessageType.file> {
name: string;
size: number;
link: string;
}
interface MediaItem {
link: string;
type?: string;
name?: string;
size?: number;
}
interface CustomMessage extends BaseMessage<MessageType.custom> {
message?: string;
html?: string;
files?: MediaItem[];
images?: MediaItem[];
videos?: MediaItem[];
}
type Message = TextMessage | ImageMessage | FileMessage | CustomMessage;timeMs 是消息的发送时间,以自 Unix 纪元以来的毫秒数表示。分页获取消息时,请将其用作游标。targetUserIds 在私聊消息中设置,包含该会话中参与者的用户 ID。
ChatMessage 类的定义如下:
enum class ChatMessageType {
TEXT,
IMAGE,
FILE
}
open class ChatMessage(
val userId: String,
val displayName: String,
val read: Boolean,
val pluginId: String?,
val type: ChatMessageType,
val time: String,
val createdAtMillis: Long,
val targetUserIds: List<String>?,
)
class TextMessage(val message: String): ChatMessage(...)
class ImageMessage(val link: String): ChatMessage(...)
class FileMessage(
val name: String,
val link: String,
val size: Long,
): ChatMessage(...)ChatMessage 类的定义如下:
public enum ChatMessageType {
case text
case image
case file
}
open class ChatMessage {
public let userId: String
public let displayName: String
public let read: Bool
public let pluginId: String?
public let type: ChatMessageType
public let time: String
public let createdAtMillis: Int64
public let targetUserIds: [String]?
}
public final class TextMessage: ChatMessage {
public let message: String
}
public final class ImageMessage: ChatMessage {
public let link: String
}
public final class FileMessage: ChatMessage {
public let name: String
public let link: String
public let size: Int64
}Message 类型的定义如下:
interface BaseMessage<T extends MessageType> {
type: T;
userId: string;
displayName: string;
time: Date;
timeMs?: number;
id: string;
isEdited?: boolean;
read?: boolean;
pluginId?: string;
pinned?: boolean;
targetUserIds?: string[];
}
interface TextMessage extends BaseMessage<MessageType.text> {
message: string;
}
interface ImageMessage extends BaseMessage<MessageType.image> {
link: string;
}
interface FileMessage extends BaseMessage<MessageType.file> {
name: string;
size: number;
link: string;
}
interface MediaItem {
link: string;
type?: string;
name?: string;
size?: number;
}
interface CustomMessage extends BaseMessage<MessageType.custom> {
message?: string;
html?: string;
files?: MediaItem[];
images?: MediaItem[];
videos?: MediaItem[];
}
type Message = TextMessage | ImageMessage | FileMessage | CustomMessage;timeMs 是消息的发送时间,以自 Unix 纪元以来的毫秒数表示。分页获取消息时,请将其用作游标。targetUserIds 在私聊消息中设置,包含该会话中参与者的用户 ID。
meeting.chat 中有一个用于发送每种类型消息的方法。
要发送文本消息,请使用 meeting.chat.sendTextMessage() 方法。该方法接受字符串消息并将其发送到房间。
const message = "Is this the real life?";
await meeting.chat.sendTextMessage(message);如果消息为空、超过最大文本长度,或者本地参与者没有发送文本消息的权限,该方法会抛出错误。
meeting.chat 中有一个用于发送每种类型消息的方法。
要发送文本消息,请使用 meeting.chat.sendTextMessage() 方法。该方法接受字符串消息并将其发送到房间。
const message = "Is this the real life?";
await meeting.chat.sendTextMessage(message);如果消息为空、超过最大文本长度,或者本地参与者没有发送文本消息的权限,该方法会抛出错误。
meeting.chat 中有一个用于发送每种类型消息的方法。
要发送文本消息,请使用 meeting.chat.sendTextMessage() 方法。该方法接受字符串消息并将其发送到房间。
val message = "Is this the real life?"
meeting.chat.sendTextMessage(message)meeting.chat 中有一个用于发送每种类型消息的方法。
要发送文本消息,请使用 meeting.chat.sendTextMessage() 方法。该方法接受字符串消息并将其发送到房间。
var message = "Is this the real life?"
meeting.chat.sendTextMessage(message)meeting.chat 中有一个用于发送每种类型消息的方法。
要发送文本消息,请使用 meeting.chat.sendTextMessage() 方法。该方法接受字符串消息并将其发送到房间。
const message = "Is this the real life?";
await meeting.chat.sendTextMessage(message);如果消息为空、超过最大文本长度,或者本地参与者没有发送文本消息的权限,该方法会抛出错误。
您可以使用 meeting.chat.sendImageMessage() 发送图片。该方法接受 File 类型的图片,并将其发送给会议中的参与者。支持的图片格式为 PNG、JPEG 和 GIF。
<label for="img">Select image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg, image/gif"
/>
<button onclick="onSendImage()">Send Image</button>async function onSendImage() {
const image = document.getElementById("img");
await meeting.chat.sendImageMessage(image.files[0]);
}您可以使用 meeting.chat.sendImageMessage() 发送图片。该方法接受 File 类型的图片,并将其发送给会议中的参与者。支持的图片格式为 PNG、JPEG 和 GIF。
import { useRef } from "react";
function ChatComponent() {
const imageInputRef = useRef(null);
const onSendImage = async () => {
const image = imageInputRef.current;
if (image && image.files[0]) {
await meeting.chat.sendImageMessage(image.files[0]);
}
};
return (
<>
<label htmlFor="img">Select image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg, image/gif"
ref={imageInputRef}
/>
<button onClick={onSendImage}>Send Image</button>
</>
);
}您可以使用 meeting.chat.sendImageMessage() 将图片发送给会议中的参与者。
meeting.chat.sendImageMessage(imageUri) { err ->
// Handle error if any
}您可以使用 meeting.chat.sendImageMessage() 将图片发送给会议中的参与者。
meeting.chat.sendImageMessage(imageURL: url) { err in
// Handle error if any
}您可以使用 meeting.chat.sendImageMessage() 发送图片。该方法接受包含 uri、name、size 和 type 字段的图片对象,并将其发送给会议中的参与者。支持的图片格式为 PNG、JPEG 和 GIF。
import DocumentPicker from "@react-native-documents/picker";
async function onSendImage() {
// Get the image uri and create an object with the following fields
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.images],
});
const image = {
uri: res.uri,
name: res.name,
size: res.size,
type: res.type,
};
await meeting.chat.sendImageMessage(image);
}发送文件与发送图片类似。唯一的区别是,当您发送图片时,会议聊天中会显示预览,而发送文件则不会。话虽如此,图片也可以使用 meeting.chat.sendFileMessage() 作为文件发送。
<label for="file">Select file:</label>
<input type="file" id="file" name="file" />
<button onclick="onSendFile()">Send File</button>async function onSendFile() {
const file = document.getElementById("file");
await meeting.chat.sendFileMessage(file.files[0]);
}发送文件与发送图片类似。唯一的区别是,当您发送图片时,会议聊天中会显示预览,而发送文件则不会。话虽如此,图片也可以使用 meeting.chat.sendFileMessage() 作为文件发送。
import { useRef } from "react";
function ChatComponent() {
const fileInputRef = useRef(null);
const onSendFile = async () => {
const file = fileInputRef.current;
if (file && file.files[0]) {
await meeting.chat.sendFileMessage(file.files[0]);
}
};
return (
<>
<label htmlFor="file">Select file:</label>
<input type="file" id="file" name="file" ref={fileInputRef} />
<button onClick={onSendFile}>Send File</button>
</>
);
}发送文件与发送图片类似。唯一的区别是,当您发送图片时,会议聊天中会显示预览,而发送文件则不会。话虽如此,图片也可以使用 meeting.chat.sendFileMessage() 作为文件发送。
meeting.chat.sendFileMessage(fileUri) { err ->
// Handle error if any
}发送文件与发送图片类似。唯一的区别是,当您发送图片时,会议聊天中会显示预览,而发送文件则不会。话虽如此,图片也可以使用 meeting.chat.sendFileMessage() 作为文件发送。
meeting.chat.sendFileMessage(fileURL: url) { err in
// Handle error if any
}发送文件与发送图片类似。唯一的区别是,当您发送图片时,会议聊天中会显示预览,而发送文件则不会。话虽如此,图片也可以使用 meeting.chat.sendFileMessage() 作为文件发送。
import DocumentPicker from "@react-native-documents/picker";
async function onSendFile() {
// Get the file uri and create an object with the following fields
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
const file = {
uri: res.uri,
name: res.name,
size: res.size,
type: res.type,
};
await meeting.chat.sendFileMessage(file);
}使用 meeting.chat.sendCustomMessage() 发送一条组合了文本、HTML、文件、图片和视频的消息。该方法接受以下类型的有效负载:
interface CustomMessagePayload {
type: "custom";
message?: string;
html?: string;
files?: (File | string)[];
images?: (File | string)[];
videos?: (File | string)[];
}files、images 和 videos 中的每个条目可以是 File(在发送消息前上传),也可以是 URL 字符串(按原样发送)。
async function onSendCustomMessage() {
const file = document.getElementById("file");
await meeting.chat.sendCustomMessage({
type: "custom",
message: "Here are the slides from today's session",
files: [file.files[0]],
images: ["https://example.com/architecture-diagram.png"],
});
}参与者会收到类型为 custom 的消息。files、images 和 videos 中的每个条目都是一个 MediaItem,包含 link;对于上传的文件,还包含文件的 name、size 和 type。
发送自定义消息需要同时具有发送文本和文件的权限。
使用 meeting.chat.sendCustomMessage() 发送一条组合了文本、HTML、文件、图片和视频的消息。该方法接受以下类型的有效负载:
interface CustomMessagePayload {
type: "custom";
message?: string;
html?: string;
files?: (File | string)[];
images?: (File | string)[];
videos?: (File | string)[];
}files、images 和 videos 中的每个条目可以是 File(在发送消息前上传),也可以是 URL 字符串(按原样发送)。
const onSendCustomMessage = async (file) => {
await meeting.chat.sendCustomMessage({
type: "custom",
message: "Here are the slides from today's session",
files: [file],
images: ["https://example.com/architecture-diagram.png"],
});
};参与者会收到类型为 custom 的消息。files、images 和 videos 中的每个条目都是一个 MediaItem,包含 link;对于上传的文件,还包含文件的 name、size 和 type。
发送自定义消息需要同时具有发送文本和文件的权限。
使用 meeting.chat.sendCustomMessage() 发送一条组合了文本、HTML、文件、图片和视频的消息。该方法接受以下类型的有效负载:
interface CustomMessagePayload {
type: "custom";
message?: string;
html?: string;
files?: (File | string)[];
images?: (File | string)[];
videos?: (File | string)[];
}files、images 和 videos 中的每个条目可以是文件对象(在发送消息前上传),也可以是 URL 字符串(按原样发送)。
await meeting.chat.sendCustomMessage({
type: "custom",
message: "Here are the slides from today's session",
files: ["https://example.com/slides.pdf"],
images: ["https://example.com/architecture-diagram.png"],
});参与者会收到类型为 custom 的消息。files、images 和 videos 中的每个条目都是一个 MediaItem,包含 link;对于上传的文件,还包含文件的 name、size 和 type。
发送自定义消息需要同时具有发送文本和文件的权限。
还有一个名为 meeting.chat.sendMessage() 的通用方法,可用于发送文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。sendMessage() 方法接受一个 message 参数,以及一个可选的参与者 ID 列表,用于私密发送消息:
type MessagePayload =
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File };
async function sendMessage(
message: MessagePayload,
participantIds?: string[],
): Promise<void>;以下是您使用 sendMessage() 方法发送文本消息的方式:
const message = "Is this just fantasy?";
await meeting.chat.sendMessage({ type: "text", message });要发送自定义消息,请使用 sendCustomMessage()。
还有一个名为 meeting.chat.sendMessage() 的通用方法,可用于发送文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。sendMessage() 方法接受一个 message 参数,以及一个可选的参与者 ID 列表,用于私密发送消息:
type MessagePayload =
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File };
async function sendMessage(
message: MessagePayload,
participantIds?: string[],
): Promise<void>;以下是您使用 sendMessage() 方法发送文本消息的方式:
const message = "Is this just fantasy?";
await meeting.chat.sendMessage({ type: "text", message });要发送自定义消息,请使用 sendCustomMessage()。
还有一个名为 meeting.chat.sendMessage() 的通用方法,可用于发送文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。sendMessage() 方法接受一个 message 参数,以及一个可选的参与者 ID 列表,用于私密发送消息:
type MessagePayload =
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File };
async function sendMessage(
message: MessagePayload,
participantIds?: string[],
): Promise<void>;以下是您使用 sendMessage() 方法发送文本消息的方式:
const message = "Is this just fantasy?";
await meeting.chat.sendMessage({ type: "text", message });要发送自定义消息,请使用 sendCustomMessage()。
所有发送方法都接受一个可选的第二个参数:参与者 ID 数组。传入该参数时,消息只会发送给这些参与者以及本地参与者(本地参与者会被自动添加)。
请传入参与者的 id,而不是其 userId。
// Find the participant with name "Freddie".
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
await meeting.chat.sendTextMessage("Hey Freddie!", [participant.id]);
// Or, using sendMessage()
await meeting.chat.sendMessage({ type: "text", message: "Hey Freddie!" }, [
participant.id,
]);发送私聊消息需要私聊权限(meeting.self.permissions.chatPrivate)。收到的私聊消息包含 targetUserIds。
所有发送方法都接受一个可选的第二个参数:参与者 ID 数组。传入该参数时,消息只会发送给这些参与者以及本地参与者(本地参与者会被自动添加)。
请传入参与者的 id,而不是其 userId。
// Find the participant with name "Freddie".
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
await meeting.chat.sendTextMessage("Hey Freddie!", [participant.id]);
// Or, using sendMessage()
await meeting.chat.sendMessage({ type: "text", message: "Hey Freddie!" }, [
participant.id,
]);发送私聊消息需要私聊权限(meeting.self.permissions.chatPrivate)。收到的私聊消息包含 targetUserIds。
所有发送方法都接受一个可选的第二个参数:参与者 ID 数组。传入该参数时,消息只会发送给这些参与者以及本地参与者(本地参与者会被自动添加)。
请传入参与者的 id,而不是其 userId。
// Find the participant with name "Freddie".
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
await meeting.chat.sendTextMessage("Hey Freddie!", [participant.id]);
// Or, using sendMessage()
await meeting.chat.sendMessage({ type: "text", message: "Hey Freddie!" }, [
participant.id,
]);发送私聊消息需要私聊权限(meeting.self.permissions.chatPrivate)。收到的私聊消息包含 targetUserIds。
文本消息默认限制为 2,000 个字符。发送更长的消息会抛出错误。您可以从 meeting.chat.maxTextLimit 读取当前限制,并使用 meeting.chat.setMaxTextLimit() 进行更改。
console.log(meeting.chat.maxTextLimit); // 2000
meeting.chat.setMaxTextLimit(500);发送方法也受速率限制。超出限制的调用会抛出错误。
| 方法 | 默认限制 |
|---|---|
sendTextMessage(), sendMessage() |
每 60 秒 180 条消息 |
sendImageMessage(), sendFileMessage() |
每 60 秒 20 条消息 |
您可以从 meeting.chat.rateLimits 读取 sendTextMessage() 的速率限制,并使用 meeting.chat.updateRateLimits() 进行更改,该方法接受最大消息数和以秒为单位的时间段。
console.log(meeting.chat.rateLimits); // { maxInvocations: 180, period: 60 }
// Allow 60 messages every 30 seconds
meeting.chat.updateRateLimits(60, 30);文本消息默认限制为 2,000 个字符。发送更长的消息会抛出错误。您可以从 meeting.chat.maxTextLimit 读取当前限制,并使用 meeting.chat.setMaxTextLimit() 进行更改。
console.log(meeting.chat.maxTextLimit); // 2000
meeting.chat.setMaxTextLimit(500);发送方法也受速率限制。超出限制的调用会抛出错误。
| 方法 | 默认限制 |
|---|---|
sendTextMessage(), sendMessage() |
每 60 秒 180 条消息 |
sendImageMessage(), sendFileMessage() |
每 60 秒 20 条消息 |
您可以从 meeting.chat.rateLimits 读取 sendTextMessage() 的速率限制,并使用 meeting.chat.updateRateLimits() 进行更改,该方法接受最大消息数和以秒为单位的时间段。
console.log(meeting.chat.rateLimits); // { maxInvocations: 180, period: 60 }
// Allow 60 messages every 30 seconds
meeting.chat.updateRateLimits(60, 30);文本消息默认限制为 2,000 个字符。发送更长的消息会抛出错误。您可以从 meeting.chat.maxTextLimit 读取当前限制,并使用 meeting.chat.setMaxTextLimit() 进行更改。
console.log(meeting.chat.maxTextLimit); // 2000
meeting.chat.setMaxTextLimit(500);发送方法也受速率限制。超出限制的调用会抛出错误。
| 方法 | 默认限制 |
|---|---|
sendTextMessage(), sendMessage() |
每 60 秒 180 条消息 |
sendImageMessage(), sendFileMessage() |
每 60 秒 20 条消息 |
您可以从 meeting.chat.rateLimits 读取 sendTextMessage() 的速率限制,并使用 meeting.chat.updateRateLimits() 进行更改,该方法接受最大消息数和以秒为单位的时间段。
console.log(meeting.chat.rateLimits); // { maxInvocations: 180, period: 60 }
// Allow 60 messages every 30 seconds
meeting.chat.updateRateLimits(60, 30);每当有消息被添加、编辑或删除时,meeting.chat 对象都会触发 chatUpdate 事件。
meeting.chat.on("chatUpdate", ({ action, message }) => {
switch (action) {
case "add":
console.log("New message", message);
break;
case "edit":
console.log("Message edited", message);
break;
case "delete":
console.log("Message deleted", message.id);
break;
}
});事件有效负载包含以下字段:
action-add、edit或delete之一。message- 被添加、编辑或删除的消息,类型为Message。messages- 已弃用。与meeting.chat.messages相同的列表。
要停止监听,请将同一个处理函数传给 meeting.chat.off()。
每当有消息被添加、编辑或删除时,meeting.chat 对象都会触发 chatUpdate 事件。
import { useEffect } from "react";
function ChatListener({ meeting }) {
useEffect(() => {
const onChatUpdate = ({ action, message }) => {
switch (action) {
case "add":
console.log("New message", message);
break;
case "edit":
console.log("Message edited", message);
break;
case "delete":
console.log("Message deleted", message.id);
break;
}
};
meeting.chat.on("chatUpdate", onChatUpdate);
return () => {
meeting.chat.off("chatUpdate", onChatUpdate);
};
}, [meeting]);
return null;
}事件有效负载包含以下字段:
action-add、edit或delete之一。message- 被添加、编辑或删除的消息,类型为Message。messages- 已弃用。与meeting.chat.messages相同的列表。
为了能够接收聊天消息,您需要实现来自回调 RtkChatEventListener 的 onChatUpdates() 方法。您可以通过调用 meeting.addChatEventListener(rtkChatEventListener) 来订阅这些事件。
meeting.addChatEventListener(object : RtkChatEventListener {
override fun onChatUpdates(messages: List<ChatMessage>) {
// to load chat messages
}
override fun onNewChatMessage(message: ChatMessage) {
// when a new chat message is shared in the meeting
}
override fun onMessageRateLimitReset() {
// when the rate limit for sending messages of self is reset
}
})每当聊天消息发生变化时,都会调用 onChatUpdates() 方法。messages 参数是在聊天中发送的 ChatMessage 对象列表。
每当在会议中分享新的聊天消息时,都会调用 onNewChatMessage() 方法。message 参数是在聊天中发送的 ChatMessage 对象。
当重置自身发送消息的速率限制且您可以再次发送消息时,将调用 onMessageRateLimitReset() 方法。默认速率限制为 60 秒内 180 条消息。
为了能够接收聊天消息,您需要实现来自回调 RtkChatEventListener 的 onChatUpdates() 方法。您可以通过调用 meeting.addChatEventListener(rtkChatEventListener) 来订阅这些事件。
extension MainChatListener: RtkChatEventListener {
func onChatUpdates(messages: [ChatMessage]) {
// to load chat messages
}
func onNewChatMessage(message: ChatMessage) {
// when a new chat message is shared in the meeting
}
func onMessageRateLimitReset() {
// when the rate limit for sending messages of self is reset
}
}每当聊天消息发生变化时,都会调用 onChatUpdates() 方法。messages 参数是在聊天中发送的 ChatMessage 对象列表。
每当在会议中分享新的聊天消息时,都会调用 onNewChatMessage() 方法。message 参数是在聊天中发送的 ChatMessage 对象。
当重置自身发送消息的速率限制且您可以再次发送消息时,将调用 onMessageRateLimitReset() 方法。默认速率限制为 60 秒内 180 条消息。
每当有消息被添加、编辑或删除时,meeting.chat 对象都会触发 chatUpdate 事件。
meeting.chat.on("chatUpdate", ({ action, message }) => {
switch (action) {
case "add":
console.log("New message", message);
break;
case "edit":
console.log("Message edited", message);
break;
case "delete":
console.log("Message deleted", message.id);
break;
}
});事件有效负载包含以下字段:
action-add、edit或delete之一。message- 被添加、编辑或删除的消息,类型为Message。messages- 已弃用。与meeting.chat.messages相同的列表。
要停止监听,请将同一个处理函数传给 meeting.chat.off()。
使用获取方法逐页加载聊天历史记录。这些方法都接受一个包含以下字段的选项对象:
limit- 必需。要返回的最大消息数。timestamp- 游标,以自 Unix 纪元以来的毫秒数表示。默认为当前时间。direction- 获取在timestamp之前(before)还是之后(after)发送的消息。默认为after。
每个方法都返回一个 Promise,解析为 Message 对象数组。
使用获取方法逐页加载聊天历史记录。这些方法都接受一个包含以下字段的选项对象:
limit- 必需。要返回的最大消息数。timestamp- 游标,以自 Unix 纪元以来的毫秒数表示。默认为当前时间。direction- 获取在timestamp之前(before)还是之后(after)发送的消息。默认为after。
每个方法都返回一个 Promise,解析为 Message 对象数组。
使用获取方法逐页加载聊天历史记录。这些方法都接受一个包含以下字段的选项对象:
limit- 必需。要返回的最大消息数。timestamp- 游标,以自 Unix 纪元以来的毫秒数表示。默认为当前时间。direction- 获取在timestamp之前(before)还是之后(after)发送的消息。默认为after。
每个方法都返回一个 Promise,解析为 Message 对象数组。
使用 meeting.chat.fetchPublicMessages() 获取公开聊天中的消息。要加载最近的消息,请获取在当前时间之前发送的消息:
const messages = await meeting.chat.fetchPublicMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});要加载下一页更早的消息,请将您已有的最早消息的 timeMs 作为新的 timestamp 传入:
const oldestTimestamp = Math.min(...messages.map((m) => m.timeMs));
const olderMessages = await meeting.chat.fetchPublicMessages({
timestamp: oldestTimestamp,
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPublicMessages() 获取公开聊天中的消息。要加载最近的消息,请获取在当前时间之前发送的消息:
const messages = await meeting.chat.fetchPublicMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});要加载下一页更早的消息,请将您已有的最早消息的 timeMs 作为新的 timestamp 传入:
const oldestTimestamp = Math.min(...messages.map((m) => m.timeMs));
const olderMessages = await meeting.chat.fetchPublicMessages({
timestamp: oldestTimestamp,
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPublicMessages() 获取公开聊天中的消息。要加载最近的消息,请获取在当前时间之前发送的消息:
const messages = await meeting.chat.fetchPublicMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});要加载下一页更早的消息,请将您已有的最早消息的 timeMs 作为新的 timestamp 传入:
const oldestTimestamp = Math.min(...messages.map((m) => m.timeMs));
const olderMessages = await meeting.chat.fetchPublicMessages({
timestamp: oldestTimestamp,
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPrivateMessages() 获取本地参与者与另一位参与者之间的私聊会话。除了分页选项之外,还需传入另一位参与者的 userId。
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
const privateMessages = await meeting.chat.fetchPrivateMessages({
userId: participant.userId,
timestamp: Date.now(),
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPrivateMessages() 获取本地参与者与另一位参与者之间的私聊会话。除了分页选项之外,还需传入另一位参与者的 userId。
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
const privateMessages = await meeting.chat.fetchPrivateMessages({
userId: participant.userId,
timestamp: Date.now(),
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPrivateMessages() 获取本地参与者与另一位参与者之间的私聊会话。除了分页选项之外,还需传入另一位参与者的 userId。
const participant = meeting.participants.joined
.toArray()
.find((p) => p.name === "Freddie");
const privateMessages = await meeting.chat.fetchPrivateMessages({
userId: participant.userId,
timestamp: Date.now(),
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPinnedMessages() 获取已置顶的消息。
const pinnedMessages = await meeting.chat.fetchPinnedMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPinnedMessages() 获取已置顶的消息。
const pinnedMessages = await meeting.chat.fetchPinnedMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});使用 meeting.chat.fetchPinnedMessages() 获取已置顶的消息。
const pinnedMessages = await meeting.chat.fetchPinnedMessages({
timestamp: Date.now(),
limit: 25,
direction: "before",
});meeting.chat 中有一个用于编辑每种类型消息的方法。
要编辑文本消息,请使用 meeting.chat.editTextMessage() 方法。该方法接受 messageId(类型为 string)和 message(类型为 string)。
const messageId = "...";
const newMessage = "Is this the real life?";
await meeting.chat.editTextMessage(messageId, newMessage);消息被编辑后,参与者会收到 action 为 edit 的 chatUpdate 事件,且该消息带有 isEdited: true。
meeting.chat 中有一个用于编辑每种类型消息的方法。
要编辑文本消息,请使用 meeting.chat.editTextMessage() 方法。该方法接受 messageId(类型为 string)和 message(类型为 string)。
const messageId = "...";
const newMessage = "Is this the real life?";
await meeting.chat.editTextMessage(messageId, newMessage);消息被编辑后,参与者会收到 action 为 edit 的 chatUpdate 事件,且该消息带有 isEdited: true。
meeting.chat 中有一个用于编辑每种类型消息的方法。
要编辑文本消息,请使用 meeting.chat.editTextMessage() 方法。该方法接受 messageId(类型为 string)和 message(类型为 string)。
const messageId = "...";
const newMessage = "Is this the real life?";
await meeting.chat.editTextMessage(messageId, newMessage);消息被编辑后,参与者会收到 action 为 edit 的 chatUpdate 事件,且该消息带有 isEdited: true。
您可以使用 meeting.chat.editImageMessage() 编辑图片。该方法接受类型为 string 的 messageId 和类型为 File 的图片。支持的图片格式为 PNG、JPEG 和 GIF。
<label for="img">Edit image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg, image/gif"
/>
<button onclick="onEditImage()">Edit Image</button>async function onEditImage() {
const messageId = "...";
const image = document.getElementById("img");
await meeting.chat.editImageMessage(messageId, image.files[0]);
}您可以使用 meeting.chat.editImageMessage() 编辑图片。该方法接受类型为 string 的 messageId 和类型为 File 的图片。支持的图片格式为 PNG、JPEG 和 GIF。
import { useRef } from "react";
function ChatComponent() {
const imageInputRef = useRef(null);
const onEditImage = async () => {
const messageId = "...";
const image = imageInputRef.current;
if (image && image.files[0]) {
await meeting.chat.editImageMessage(messageId, image.files[0]);
}
};
return (
<>
<label htmlFor="img">Edit image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg, image/gif"
ref={imageInputRef}
/>
<button onClick={onEditImage}>Edit Image</button>
</>
);
}您可以使用 meeting.chat.editImageMessage() 编辑图片。该方法接受类型为 string 的 messageId,以及包含 uri、name、size 和 type 字段的图片对象。支持的图片格式为 PNG、JPEG 和 GIF。
import DocumentPicker from "@react-native-documents/picker";
async function onEditImage() {
const messageId = "...";
// Get the image uri and create an object with the following fields
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.images],
});
const image = {
uri: res.uri,
name: res.name,
size: res.size,
type: res.type,
};
await meeting.chat.editImageMessage(messageId, image);
}编辑文件与编辑图片类似。要编辑文件,请使用 meeting.chat.editFileMessage()。
<label for="file">Edit file:</label>
<input type="file" id="file" name="file" />
<button onclick="onEditFile()">Edit File</button>async function onEditFile() {
const messageId = "...";
const file = document.getElementById("file");
await meeting.chat.editFileMessage(messageId, file.files[0]);
}编辑文件与编辑图片类似。要编辑文件,请使用 meeting.chat.editFileMessage()。
import { useRef } from "react";
function ChatComponent() {
const fileInputRef = useRef(null);
const onEditFile = async () => {
const messageId = "...";
const file = fileInputRef.current;
if (file && file.files[0]) {
await meeting.chat.editFileMessage(messageId, file.files[0]);
}
};
return (
<>
<label htmlFor="file">Edit file:</label>
<input type="file" id="file" name="file" ref={fileInputRef} />
<button onClick={onEditFile}>Edit File</button>
</>
);
}编辑文件与编辑图片类似。要编辑文件,请使用 meeting.chat.editFileMessage()。
import DocumentPicker from "@react-native-documents/picker";
async function onEditFile() {
const messageId = "...";
// Get the file uri and create an object with the following fields
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
const file = {
uri: res.uri,
name: res.name,
size: res.size,
type: res.type,
};
await meeting.chat.editFileMessage(messageId, file);
}还有一个名为 meeting.chat.editMessage() 的通用方法,可用于编辑文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。editMessage() 方法接受以下类型的参数 messageId 和 message:
async function editMessage(
messageId: string,
message:
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File },
): Promise<void>;以下是您使用 editMessage() 方法编辑文本消息的方式:
const messageId = "...";
const message = "Is this just fantasy?";
await meeting.chat.editMessage(messageId, { type: "text", message });还有一个名为 meeting.chat.editMessage() 的通用方法,可用于编辑文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。editMessage() 方法接受以下类型的参数 messageId 和 message:
async function editMessage(
messageId: string,
message:
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File },
): Promise<void>;以下是您使用 editMessage() 方法编辑文本消息的方式:
const messageId = "...";
const message = "Is this just fantasy?";
await meeting.chat.editMessage(messageId, { type: "text", message });还有一个名为 meeting.chat.editMessage() 的通用方法,可用于编辑文本、图片和文件消息。它会根据您发送的有效负载的 type 调用上述方法之一。editMessage() 方法接受以下类型的参数 messageId 和 message:
async function editMessage(
messageId: string,
message:
| { type: "text"; message: string }
| { type: "image"; image: File }
| { type: "file"; file: File },
): Promise<void>;以下是您使用 editMessage() 方法编辑文本消息的方式:
const messageId = "...";
const message = "Is this just fantasy?";
await meeting.chat.editMessage(messageId, { type: "text", message });您可以将多条消息置顶到聊天中。置顶消息时,消息对象将具有属性 pinned: true,您可以通过该属性识别消息是否已被置顶。
要置顶消息,请将其 ID 传给 meeting.chat.pin()。本地参与者必须已加入会议,否则该方法会抛出错误。
const messageId = "...";
await meeting.chat.pin(messageId);要获取置顶消息列表,请使用 meeting.chat.fetchPinnedMessages()。
您还可以使用 meeting.chat.unpin() 方法取消置顶已置顶的消息。
// Unpin the most recently pinned message.
const [latestPinned] = await meeting.chat.fetchPinnedMessages({
limit: 1,
direction: "before",
});
await meeting.chat.unpin(latestPinned.id);您可以监听事件以了解消息何时被置顶或取消置顶。
meeting.chat.on("pinMessage", ({ message }) => {
console.log("A message was pinned", JSON.stringify(message));
});
meeting.chat.on("unpinMessage", ({ message }) => {
console.log("A message was unpinned", JSON.stringify(message));
});您可以将多条消息置顶到聊天中。置顶消息时,消息对象将具有属性 pinned: true,您可以通过该属性识别消息是否已被置顶。
要置顶消息,请将其 ID 传给 meeting.chat.pin()。本地参与者必须已加入会议,否则该方法会抛出错误。
const messageId = "...";
await meeting.chat.pin(messageId);要获取置顶消息列表,请使用 meeting.chat.fetchPinnedMessages()。
您还可以使用 meeting.chat.unpin() 方法取消置顶已置顶的消息。
// Unpin the most recently pinned message.
const [latestPinned] = await meeting.chat.fetchPinnedMessages({
limit: 1,
direction: "before",
});
await meeting.chat.unpin(latestPinned.id);您可以监听事件以了解消息何时被置顶或取消置顶。
meeting.chat.on("pinMessage", ({ message }) => {
console.log("A message was pinned", JSON.stringify(message));
});
meeting.chat.on("unpinMessage", ({ message }) => {
console.log("A message was unpinned", JSON.stringify(message));
});您可以将多条消息置顶到聊天中。置顶消息时,消息对象将具有属性 pinned: true,您可以通过该属性识别消息是否已被置顶。
要置顶消息,请将其 ID 传给 meeting.chat.pin()。本地参与者必须已加入会议,否则该方法会抛出错误。
const messageId = "...";
await meeting.chat.pin(messageId);要获取置顶消息列表,请使用 meeting.chat.fetchPinnedMessages()。
您还可以使用 meeting.chat.unpin() 方法取消置顶已置顶的消息。
// Unpin the most recently pinned message.
const [latestPinned] = await meeting.chat.fetchPinnedMessages({
limit: 1,
direction: "before",
});
await meeting.chat.unpin(latestPinned.id);您可以监听事件以了解消息何时被置顶或取消置顶。
meeting.chat.on("pinMessage", ({ message }) => {
console.log("A message was pinned", JSON.stringify(message));
});
meeting.chat.on("unpinMessage", ({ message }) => {
console.log("A message was unpinned", JSON.stringify(message));
});meeting.chat 命名空间公开了一个名为 deleteMessage() 的方法。它接受类型为 string 的参数 messageId。
const messageId = "...";
await meeting.chat.deleteMessage(messageId);消息被删除后,参与者会收到 action 为 delete 的 chatUpdate 事件。
meeting.chat 命名空间公开了一个名为 deleteMessage() 的方法。它接受类型为 string 的参数 messageId。
const messageId = "...";
await meeting.chat.deleteMessage(messageId);消息被删除后,参与者会收到 action 为 delete 的 chatUpdate 事件。
meeting.chat 命名空间公开了一个名为 deleteMessage() 的方法。它接受类型为 string 的参数 messageId。
const messageId = "...";
await meeting.chat.deleteMessage(messageId);消息被删除后,参与者会收到 action 为 delete 的 chatUpdate 事件。
您可以通过以下方式以编程方式检索 RealtimeKit 会话的所有聊天消息:
- 使用 Chat Replay API
- 为
meeting.chatSynced事件设置 Webhook
要获取聊天下载 URL,请向 Chat Replay API 端点 发起 HTTP GET 请求。该 API 返回:
{
"success": true,
"data": {
"chat_download_url": "string",
"chat_download_url_expiry": "string"
}
}chat_download_url- 允许您从 AWS S3 下载 CSV 格式的会话完整聊天转储的 URLchat_download_url_expiry-chat_download_url的过期时间戳。如果该 URL 过期,请再次调用此端点以获取新的下载 URL
有关 Chat Replay API 端点的详细信息,请参阅 Realtime Kit API 文档。
您可以通过向在上一步中获取的 chat_download_url 发起 HTTP GET 请求,来下载 CSV 格式的聊天转储文件。
从 HTTP URL 下载文件的过程因您是在客户端还是在服务端下载而有所不同。
要在客户端下载:
- 向
chat_download_url发起GET请求 - 将响应转换为 Blob
- 创建一个带有
download属性的隐式<a>HTML 元素,并将 Blob 添加到其href中 - 以编程方式点击
<a>元素,以便浏览器自动开始下载,然后移除该<a>元素
要在服务器端使用 Node.js 流进行下载:
- 为本地文件创建可写流
- 向
chat_download_url发起GET请求 - 使用
res.body获取可读流,并将其管道传输到第一步中创建的可写流
CSV 文件包含所有聊天消息以及参与者信息和元数据。它包含以下列标题:
id- 唯一的聊天消息 IDparticipantId- 发送消息的参与者的 IDsessionId- 发送聊天消息的会话 IDmeetingId- 此会话所属会议的 IDdisplayName- 发送此消息的参与者的显示名称pinned- 指示当前消息是否被置顶的布尔值isEdited- 指示当前消息是否被编辑的布尔值payloadType- 一个指示聊天消息中发送的有效负载类型的枚举(ENUM)。它可以是TEXT_MESSAGE、IMAGE_MESSAGE、FILE_MESSAGE之一payload- 聊天消息中发送的实际有效负载createdAt- 发送此聊天消息的时间戳