### Install WuKongIM SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Use npm or yarn to add the SDK to your project dependencies. ```bash npm install wukongimjssdk # 或 yarn add wukongimjssdk ``` -------------------------------- ### Install WukongIM JSSDK via npm or yarn Source: https://github.com/wukongim/wukongimjssdk/blob/main/README.md Use these commands to add the WukongIM JSSDK dependency to your project. ```js npm i wukongimjssdk ``` ```shell yarn add wukongimjssdk ``` -------------------------------- ### Get and Process Channel-Specific Reminders Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Retrieve pending reminders for a specific channel and process them based on their type. This example shows how to filter for mentions and join requests. ```typescript // 获取指定频道的待处理提醒 const channel = new Channel('group123', 2); const channelReminders = sdk.reminderManager.getWaitDoneReminders(channel); channelReminders.forEach(reminder => { if (reminder.reminderType === ReminderType.ReminderTypeMentionMe) { console.log('有人@我:', reminder.text); } else if (reminder.reminderType === ReminderType.ReminderTypeApplyJoinGroup) { console.log('入群申请:', reminder.data); } }); ``` -------------------------------- ### Get Channel Subscribers List Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Retrieve the list of subscribers for a given channel from the SDK's cache. This provides access to member details like UID, name, and role. ```typescript const subscribers = sdk.channelManager.getSubscribes(channel); subscribers.forEach(sub => { console.log('成员:', sub.uid, sub.name, '角色:', sub.role); }); ``` -------------------------------- ### Fetch and Get Channel Information Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Retrieve channel information from the cache. If not found, it triggers an asynchronous fetch operation. Ensure the channel object is correctly instantiated with its ID and type. ```typescript const channel = new Channel('group123', ChannelTypeGroup); let channelInfo = sdk.channelManager.getChannelInfo(channel); if (!channelInfo) { // 触发异步获取 await sdk.channelManager.fetchChannelInfo(channel); channelInfo = sdk.channelManager.getChannelInfo(channel); } ``` -------------------------------- ### Get Own Subscriber Information Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Retrieve your own information within a specific channel, including your role. Returns null if you are not a member of the channel. ```typescript const myInfo = sdk.channelManager.getSubscribeOfMe(channel); if (myInfo) { console.log('我的角色:', myInfo.role); } ``` -------------------------------- ### Initialize and Configure SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Configure the singleton instance with server addresses, authentication tokens, and data provider callbacks for channel info and message synchronization. ```typescript import { WKSDK, ChannelTypePerson, ChannelTypeGroup, ChannelInfo, Channel, SyncOptions, Conversation, Message } from 'wukongimjssdk'; // 获取 SDK 单例 const sdk = WKSDK.shared(); // 基础配置 sdk.config.addr = 'ws://your-wukongim-server:5200/ws'; // IM 服务器地址 sdk.config.uid = 'user123'; // 当前用户 UID sdk.config.token = 'your-auth-token'; // 认证 token sdk.config.deviceFlag = 1; // 设备标识: 0-app, 1-web, 2-pc sdk.config.heartbeatInterval = 60000; // 心跳间隔(毫秒) sdk.config.debug = true; // 开启调试模式 // 配置动态获取连接地址(可选) sdk.config.provider.connectAddrCallback = (callback) => { // 从业务服务器获取 IM 连接地址 fetch('/api/im/address').then(res => res.json()).then(data => { callback(data.wsAddr); }); }; // 配置频道信息获取回调 sdk.config.provider.channelInfoCallback = async (channel: Channel): Promise => { const channelInfo = new ChannelInfo(); channelInfo.channel = channel; if (channel.channelType === ChannelTypePerson) { // 获取个人信息 const userInfo = await fetch(`/api/users/${channel.channelID}`).then(r => r.json()); channelInfo.title = userInfo.name; channelInfo.logo = userInfo.avatar; channelInfo.online = userInfo.online; channelInfo.lastOffline = userInfo.lastOfflineTime; } else if (channel.channelType === ChannelTypeGroup) { // 获取群组信息 const groupInfo = await fetch(`/api/groups/${channel.channelID}`).then(r => r.json()); channelInfo.title = groupInfo.name; channelInfo.logo = groupInfo.avatar; } channelInfo.mute = false; // 是否免打扰 channelInfo.top = false; // 是否置顶 channelInfo.orgData = {}; // 自定义业务数据 return channelInfo; }; // 配置消息同步回调 sdk.config.provider.syncMessagesCallback = async (channel: Channel, opts: SyncOptions): Promise => { const resp = await fetch('/api/messages/sync', { method: 'POST', body: JSON.stringify({ channel_id: channel.channelID, channel_type: channel.channelType, start_message_seq: opts.startMessageSeq, end_message_seq: opts.endMessageSeq, limit: opts.limit, pull_mode: opts.pullMode // 0: 向下拉取, 1: 向上拉取 }) }).then(r => r.json()); return resp.messages.map(convertToMessage); // 转换为 Message 对象 }; // 配置会话同步回调 sdk.config.provider.syncConversationsCallback = async (): Promise => { const resp = await fetch('/api/conversations/sync', { method: 'POST', body: JSON.stringify({ uid: sdk.config.uid }) }).then(r => r.json()); return resp.map(convertToConversation); // 转换为 Conversation 对象 }; ``` -------------------------------- ### Initialize and Connect WukongIM SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Initializes the SDK with configuration, sets up data providers and listeners, and establishes a connection. It waits for the connection to be established before synchronizing data. ```typescript import { WKSDK, ConnectStatus, Channel, ChannelTypePerson, ChannelTypeGroup, ChannelInfo, Conversation, ConversationAction, Message, MessageText, MessageContentType, SyncOptions, PullMode, Subscriber } from 'wukongimjssdk'; class IMService { private sdk = WKSDK.shared(); // 初始化 SDK async init(config: { apiUrl: string; wsUrl: string; uid: string; token: string }) { // 基础配置 this.sdk.config.addr = config.wsUrl; this.sdk.config.uid = config.uid; this.sdk.config.token = config.token; // 配置数据源 this.setupProviders(config.apiUrl); // 设置监听器 this.setupListeners(); // 建立连接 this.sdk.connect(); // 等待连接成功后同步数据 return new Promise((resolve) => { const listener = async (status: ConnectStatus) => { if (status === ConnectStatus.Connected) { await this.sdk.conversationManager.sync(); this.sdk.connectManager.removeConnectStatusListener(listener); resolve(); } }; this.sdk.connectManager.addConnectStatusListener(listener); }); } private setupProviders(apiUrl: string) { // 频道信息 this.sdk.config.provider.channelInfoCallback = async (channel) => { const info = new ChannelInfo(); info.channel = channel; const resp = await fetch(`${apiUrl}/channels/${channel.channelID}?type=${channel.channelType}`) .then(r => r.json()); info.title = resp.name; info.logo = resp.avatar; info.mute = resp.mute; info.top = resp.top; info.online = resp.online; return info; }; // 会话同步 this.sdk.config.provider.syncConversationsCallback = async () => { const resp = await fetch(`${apiUrl}/conversations?uid=${this.sdk.config.uid}`) .then(r => r.json()); return resp.map(this.convertConversation.bind(this)); }; // 消息同步 this.sdk.config.provider.syncMessagesCallback = async (channel, opts) => { const resp = await fetch(`${apiUrl}/messages/sync`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ channel_id: channel.channelID, channel_type: channel.channelType, start_message_seq: opts.startMessageSeq, end_message_seq: opts.endMessageSeq, limit: opts.limit, pull_mode: opts.pullMode }) }).then(r => r.json()); return resp.messages.map(this.convertMessage.bind(this)); }; // 订阅者同步 this.sdk.config.provider.syncSubscribersCallback = async (channel, version) => { const resp = await fetch(`${apiUrl}/channels/${channel.channelID}/members?version=${version}`) .then(r => r.json()); return resp.map((item: any) => { const sub = new Subscriber(); sub.uid = item.uid; sub.name = item.name; sub.avatar = item.avatar; sub.role = item.role; sub.version = item.version; sub.channel = channel; return sub; }); }; } private setupListeners() { // 连接状态 this.sdk.connectManager.addConnectStatusListener((status, code) => { console.log('连接状态:', ConnectStatus[status], code); if (status === ConnectStatus.ConnectKick) { this.onKicked(); } }); // 新消息 this.sdk.chatManager.addMessageListener((message) => { this.onNewMessage(message); }); // 会话变更 this.sdk.conversationManager.addConversationListener((conv, action) => { this.onConversationChange(conv, action); }); } // 发送文本消息 async sendTextMessage(channelId: string, channelType: number, text: string) { const channel = new Channel(channelId, channelType); const content = new MessageText(text); return this.sdk.chatManager.send(content, channel); } // 获取历史消息 async getHistoryMessages(channel: Channel, startSeq: number = 0) { const opts = new SyncOptions(); opts.startMessageSeq = startSeq; opts.limit = 30; opts.pullMode = PullMode.Down; return this.sdk.chatManager.syncMessages(channel, opts); } // 获取会话列表 getConversations(): Conversation[] { return this.sdk.conversationManager.conversations; } // 获取总未读数 getTotalUnread(): number { return this.sdk.conversationManager.getAllUnreadCount(); } // 断开连接 } ``` -------------------------------- ### Initialize and Use IMService Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Demonstrates the initialization of the IMService with connection parameters and basic usage for sending messages and retrieving conversation data. ```typescript const imService = new IMService(); await imService.init({ apiUrl: 'https://api.example.com', wsUrl: 'wss://im.example.com/ws', uid: 'user123', token: 'auth_token_xxx' }); // 发送消息 await imService.sendTextMessage('friend456', ChannelTypePerson, '你好!'); // 获取会话列表 const conversations = imService.getConversations(); console.log('会话数:', conversations.length); console.log('总未读:', imService.getTotalUnread()); ``` -------------------------------- ### Send Messages with WukongIM JS SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Demonstrates how to initialize the SDK, create channels, and send different types of messages including text, mentions, replies, and images. Also shows how to use advanced sending options. ```typescript import { WKSDK, Channel, ChannelTypePerson, ChannelTypeGroup, MessageText, MessageImage, Setting, Mention, Reply } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 创建频道 const personChannel = new Channel('user456', ChannelTypePerson); // 个人频道 const groupChannel = new Channel('group123', ChannelTypeGroup); // 群组频道 // 发送文本消息 const textContent = new MessageText('你好,这是一条测试消息'); const message = await sdk.chatManager.send(textContent, personChannel); console.log('消息已发送,clientSeq:', message.clientSeq); // 发送带 @提及 的消息 const mentionContent = new MessageText('大家好,请注意查看'); mentionContent.mention = new Mention(); mentionContent.mention.all = true; // @所有人 // 或指定 @某些人 // mentionContent.mention.uids = ['user1', 'user2']; await sdk.chatManager.send(mentionContent, groupChannel); // 发送带回复的消息 const replyContent = new MessageText('这是我的回复'); replyContent.reply = new Reply(); replyContent.reply.messageID = 'original_msg_id'; replyContent.reply.messageSeq = 100; replyContent.reply.fromUID = 'user789'; replyContent.reply.fromName = '张三'; replyContent.reply.rootMessageID = 'root_msg_id'; // 根消息ID(用于多层回复) await sdk.chatManager.send(replyContent, personChannel); // 发送图片消息 const imageFile = document.getElementById('fileInput').files[0]; const imageContent = new MessageImage(imageFile, 800, 600); // 文件, 宽度, 高度 await sdk.chatManager.send(imageContent, personChannel); // 使用高级发送选项 import { SendOptions, Setting } from 'wukongimjssdk'; const opts = new SendOptions(); opts.setting = new Setting(); opts.noPersist = false; // 是否不存储消息 opts.reddot = true; // 是否显示红点 const advMessage = await sdk.chatManager.sendWithOptions(textContent, personChannel, opts); ``` -------------------------------- ### Build and Publish Commands Source: https://github.com/wukongim/wukongimjssdk/blob/main/README.md Commands for building the project and publishing the package to npm. ```shell yarn build ``` ```shell npm publish ``` -------------------------------- ### Receive and Listen to Messages with WukongIM JS SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Covers setting up listeners for incoming messages, command messages, and delivery status updates, as well as synchronizing historical messages. ```typescript import { WKSDK, Message, MessageContentType } from 'wukongimjssdk'; import { SendackPacket } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 添加消息监听器(接收所有消息) const messageListener = (message: Message) => { console.log('收到消息:', message); console.log('发送者:', message.fromUID); console.log('频道:', message.channel.channelID, message.channel.channelType); console.log('消息ID:', message.messageID); console.log('消息序号:', message.messageSeq); console.log('时间戳:', message.timestamp); console.log('是否自己发送:', message.send); // 根据消息类型处理 switch (message.contentType) { case MessageContentType.text: console.log('文本内容:', message.content.text); break; case MessageContentType.image: console.log('图片地址:', message.content.remoteUrl); console.log('图片尺寸:', message.content.width, 'x', message.content.height); break; default: console.log('其他消息类型:', message.contentType); } // 检查 @提及 if (message.content.mention) { if (message.content.mention.all) { console.log('这是一条 @所有人 的消息'); } if (message.content.mention.uids?.includes(sdk.config.uid)) { console.log('这条消息 @了我'); } } // 检查回复 if (message.content.reply) { console.log('这是一条回复消息,原消息ID:', message.content.reply.messageID); } }; sdk.chatManager.addMessageListener(messageListener); // 添加命令消息监听器(用于同步指令,如清除未读等) const cmdListener = (message: Message) => { const cmd = message.content.cmd; const param = message.content.param; switch (cmd) { case 'clearUnread': console.log('收到清除未读指令:', param); break; case 'userStatusChanged': console.log('用户状态变更:', param); break; } }; sdk.chatManager.addCMDListener(cmdListener); // 添加消息发送状态监听器 const statusListener = (sendack: SendackPacket) => { console.log('消息发送回执:', sendack.clientSeq); console.log('服务端消息ID:', sendack.messageID); console.log('消息序号:', sendack.messageSeq); console.log('原因码:', sendack.reasonCode); // 1-成功 }; sdk.chatManager.addMessageStatusListener(statusListener); // 同步历史消息 import { SyncOptions, PullMode } from 'wukongimjssdk'; const syncOpts = new SyncOptions(); syncOpts.startMessageSeq = 0; // 起始消息序号 syncOpts.endMessageSeq = 0; // 结束消息序号(0表示不限制) syncOpts.limit = 30; // 每次拉取数量 syncOpts.pullMode = PullMode.Down; // 向下拉取 const messages = await sdk.chatManager.syncMessages(personChannel, syncOpts); console.log('同步到消息数量:', messages.length); // 移除监听器 sdk.chatManager.removeMessageListener(messageListener); sdk.chatManager.removeCMDListener(cmdListener); sdk.chatManager.removeMessageStatusListener(statusListener); ``` -------------------------------- ### Manage Conversations with WukongIM JS SDK Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Demonstrates how to listen for conversation changes, sync lists, search for channels, and manage unread counts. ```typescript import { WKSDK, Channel, Conversation, ConversationAction } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 添加会话变更监听器 const conversationListener = (conversation: Conversation, action: ConversationAction) => { switch (action) { case ConversationAction.add: console.log('新增会话:', conversation.channel.channelID); break; case ConversationAction.update: console.log('会话更新:', conversation.channel.channelID); break; case ConversationAction.remove: console.log('会话删除:', conversation.channel.channelID); break; } console.log('未读数:', conversation.unread); console.log('最后一条消息:', conversation.lastMessage?.content); console.log('时间戳:', conversation.timestamp); console.log('是否有人@我:', conversation.isMentionMe); console.log('频道信息:', conversation.channelInfo); // 自动获取缓存 }; sdk.conversationManager.addConversationListener(conversationListener); // 同步会话列表 const conversations = await sdk.conversationManager.sync(); console.log('会话数量:', conversations.length); // 获取所有会话 const allConversations = sdk.conversationManager.conversations; // 查找特定会话 const targetChannel = new Channel('user456', 1); const conversation = sdk.conversationManager.findConversation(targetChannel); if (conversation) { console.log('找到会话,未读数:', conversation.unread); } // 查找多个会话 const channels = [new Channel('user1', 1), new Channel('user2', 1)]; const foundConversations = sdk.conversationManager.findConversations(channels); // 创建空会话(用于主动发起聊天) const newConversation = sdk.conversationManager.createEmptyConversation( new Channel('newUser', 1) ); // 设置当前打开的会话(收到该会话消息时不增加未读数) sdk.conversationManager.openConversation = conversation; // 删除会话 sdk.conversationManager.removeConversation(targetChannel); // 获取所有未读总数 const totalUnread = sdk.conversationManager.getAllUnreadCount(); console.log('总未读数:', totalUnread); // 同步会话扩展信息(如草稿、浏览进度等) const extras = await sdk.conversationManager.syncExtra(); // 设置不更新会话的消息类型(如系统消息) sdk.conversationManager.addNoUpdateContentType(1000); // 系统消息类型 sdk.conversationManager.removeNoUpdateContentType(1000); // 移除监听器 sdk.conversationManager.removeConversationListener(conversationListener); ``` -------------------------------- ### Configure Reminder Synchronization Callback Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Set up a callback to synchronize reminders from a server. This function fetches reminder data based on a version number and maps it to Reminder objects. Ensure your API endpoint `/api/reminders/sync` is correctly implemented. ```typescript import { WKSDK, Channel, Reminder, ReminderType } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 配置提醒同步回调 sdk.config.provider.syncRemindersCallback = async (version: number): Promise => { const resp = await fetch(`/api/reminders/sync?version=${version}`).then(r => r.json()); return resp.map(item => { const reminder = new Reminder(); reminder.reminderID = item.reminder_id; reminder.channel = new Channel(item.channel_id, item.channel_type); reminder.messageID = item.message_id; reminder.messageSeq = item.message_seq; reminder.reminderType = item.type; // 1-@我, 2-入群申请 reminder.text = item.text; reminder.data = item.data; reminder.isLocate = item.is_locate; // 是否需要定位到消息 reminder.version = item.version; reminder.done = item.done; return reminder; }); }; ``` -------------------------------- ### Configure Reminder Done Callback Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Implement a callback to mark reminders as completed on the server. This function sends a POST request with an array of reminder IDs to the `/api/reminders/done` endpoint. ```typescript // 配置提醒完成回调 sdk.config.provider.reminderDoneCallback = async (ids: number[]): Promise => { await fetch('/api/reminders/done', { method: 'POST', body: JSON.stringify({ reminder_ids: ids }) }); }; ``` -------------------------------- ### Subscribe to Channel via String URL Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Subscribe to a channel using its string representation, which can include URL parameters. This is an alternative way to initiate a subscription. ```typescript sdk.onSubscribe('channel123?param1=value1¶m2=value2', (msg, reasonCode) => { console.log('订阅回调:', reasonCode); }); ``` -------------------------------- ### Configure Subscriber Sync Callback Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Set up a callback to synchronize channel subscribers. This function is invoked when subscriber data needs to be updated, fetching the latest subscriber information from an API. ```typescript sdk.config.provider.syncSubscribersCallback = async (channel: Channel, version: number): Promise => { const resp = await fetch(`/api/channels/${channel.channelID}/subscribers?version=${version}`) .then(r => r.json()); return resp.map(item => { const subscriber = new Subscriber(); subscriber.uid = item.uid; subscriber.name = item.name; subscriber.avatar = item.avatar; subscriber.role = item.role; // 角色:0-普通成员, 1-管理员, 2-群主 subscriber.version = item.version; subscriber.isDeleted = item.is_deleted; subscriber.channel = channel; return subscriber; }); }; ``` -------------------------------- ### Manage WebSocket Connections Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Handle connection lifecycle events, monitor network latency, and control connection state using the connectManager. ```typescript import { WKSDK, ConnectStatus } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 添加连接状态监听器 const statusListener = (status: ConnectStatus, reasonCode?: number) => { switch (status) { case ConnectStatus.Connected: console.log('连接成功'); break; case ConnectStatus.Connecting: console.log('连接中...'); break; case ConnectStatus.Disconnect: console.log('连接断开'); break; case ConnectStatus.ConnectFail: console.log('连接失败,错误码:', reasonCode); // reasonCode: 2-认证失败, 3-订阅者不存在 等 break; case ConnectStatus.ConnectKick: console.log('被踢下线(账号在其他地方登录)'); break; } }; sdk.connectManager.addConnectStatusListener(statusListener); // 添加连接延迟监听(监控网络质量) const delayListener = (delay: number) => { if (delay > 1000) { console.log('网络延迟较高:', delay, 'ms'); } if (delay === 9999) { console.log('连接超时'); } }; sdk.connectManager.addConnectDelayListener(delayListener); // 建立连接 sdk.connect(); // 判断是否已连接 if (sdk.connectManager.connected()) { console.log('当前已连接'); } // 断开连接(不再自动重连) sdk.disconnect(); // 移除监听器 sdk.connectManager.removeConnectStatusListener(statusListener); sdk.connectManager.removeConnectDelayListener(delayListener); ``` -------------------------------- ### Add Channel Info Change Listener Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Register a listener to receive updates on channel information changes, such as title, logo, mute status, and online presence. ```typescript const channelInfoListener = (channelInfo: ChannelInfo) => { console.log('频道信息更新:', channelInfo.channel.channelID); console.log('标题:', channelInfo.title); console.log('头像:', channelInfo.logo); console.log('免打扰:', channelInfo.mute); console.log('置顶:', channelInfo.top); console.log('在线状态:', channelInfo.online); }; sdk.channelManager.addListener(channelInfoListener); ``` -------------------------------- ### Configure and Manage Message Read Receipts in TypeScript Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Utilize the receiptManager to handle message read receipts efficiently. Configure callbacks for read status, add listeners for receipt events, and manage messages that require read receipts. The SDK automatically batches and sends receipts at configured intervals. ```typescript import { WKSDK, Channel, Message } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 配置消息已读回调 sdk.config.provider.messageReadedCallback = async (channel: Channel, messages: Message[]): Promise => { const messageIds = messages.map(m => m.messageID); await fetch('/api/messages/read', { method: 'POST', body: JSON.stringify({ channel_id: channel.channelID, channel_type: channel.channelType, message_ids: messageIds }) }); }; // 添加已读回执监听 const receiptListener = (channel: Channel, messages: Message[]) => { console.log('已读回执发送成功:', channel.channelID, '消息数:', messages.length); messages.forEach(msg => { msg.remoteExtra.readed = true; msg.remoteExtra.readedAt = new Date(); }); }; sdk.receiptManager.addListener(receiptListener); // 添加需要发送已读回执的消息 const channel = new Channel('user123', 1); const unreadMessages = getUnreadMessages(); // 获取未读消息列表 sdk.receiptManager.addReceiptMessages(channel, unreadMessages); // SDK 会自动定时批量发送已读回执 // 配置回执发送间隔(在初始化时设置) sdk.config.receiptFlushInterval = 2000; // 2秒间隔 // 移除监听器 sdk.receiptManager.removeListener(receiptListener); ``` -------------------------------- ### Mark Reminders as Done Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Mark a list of reminders as completed by calling the `done` method on the reminder manager with an array of reminder IDs. ```typescript // 标记提醒为已完成 const reminderIds = [1, 2, 3]; await sdk.reminderManager.done(reminderIds); ``` -------------------------------- ### Sync and Retrieve Reminders Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Manually trigger a reminder synchronization and access all available reminders. The `sync()` method should typically be called after session synchronization. Retrieved reminders are stored in `sdk.reminderManager.reminders`. ```typescript // 同步提醒(通常在会话同步后自动调用) await sdk.reminderManager.sync(); // 获取所有提醒 const allReminders = sdk.reminderManager.reminders; console.log('提醒数量:', allReminders.length); ``` -------------------------------- ### Subscribe to Channel Real-time Data Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Subscribe to a channel to receive real-time messages and updates. Allows passing custom parameters via subscribeConfig. ```typescript sdk.onSubscribe(channel, (msg, reasonCode) => { if (reasonCode === ReasonCode.success) { console.log('订阅成功'); } if (msg) { console.log('收到订阅消息:', msg); } }, subscribeConfig.withParam({ key: 'value' })); ``` -------------------------------- ### Manually Set Channel Information Cache Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Manually update the channel information cache with new details like title and logo. This is useful for immediate updates before the SDK fetches them. ```typescript const newInfo = new ChannelInfo(); newInfo.channel = channel; newInfo.title = '新群名称'; newInfo.logo = 'https://example.com/avatar.png'; sdk.channelManager.setChannleInfoForCache(newInfo); ``` -------------------------------- ### Synchronize Channel Subscribers Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Manually trigger the synchronization of channel subscribers. This ensures the local cache has the latest member list. ```typescript await sdk.channelManager.syncSubscribes(channel); ``` -------------------------------- ### Access Reminders via Conversation Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Retrieve reminders associated with a specific conversation. This includes accessing simplified reminders (deduplicated by type) and all reminders for that conversation. ```typescript // 通过会话获取提醒 const conversation = sdk.conversationManager.findConversation(channel); if (conversation) { // 获取去重后的提醒(按类型去重) const simpleReminders = conversation.simpleReminders; // 获取所有提醒 const allConvReminders = conversation.reminders; } ``` -------------------------------- ### Define Custom Message Types in TypeScript Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Extend MessageContent or MediaMessageContent to create custom message types. Define content types, conversation digests, and methods for encoding/decoding JSON data. Ensure custom content types are registered with the SDK. ```typescript import { WKSDK, MessageContent, MediaMessageContent, MessageContentType } from 'wukongimjssdk'; // 定义自定义消息类型常量 const CustomContentType = { location: 3, // 位置消息 voice: 4, // 语音消息 video: 5, // 视频消息 card: 6, // 名片消息 redPacket: 100, // 红包消息 }; // 自定义位置消息 class LocationContent extends MessageContent { latitude: number = 0; longitude: number = 0; address: string = ''; get contentType(): number { return CustomContentType.location; } get conversationDigest(): string { return '[位置]'; } // 解码服务端返回的数据 decodeJSON(content: any): void { this.latitude = content.latitude || 0; this.longitude = content.longitude || 0; this.address = content.address || ''; } // 编码发送给服务端的数据 encodeJSON(): any { return { latitude: this.latitude, longitude: this.longitude, address: this.address }; } } // 自定义语音消息(带附件) class VoiceContent extends MediaMessageContent { duration: number = 0; // 时长(秒) waveform: number[] = []; // 波形数据 constructor(file?: File, duration?: number) { super(); this.file = file; this.duration = duration || 0; } get contentType(): number { return CustomContentType.voice; } get conversationDigest(): string { return `[语音] ${this.duration}秒`; } decodeJSON(content: any): void { this.duration = content.duration || 0; this.remoteUrl = content.url || ''; this.waveform = content.waveform || []; } encodeJSON(): any { return { duration: this.duration, url: this.remoteUrl, waveform: this.waveform }; } } // 注册自定义消息类型 const sdk = WKSDK.shared(); sdk.register(CustomContentType.location, () => new LocationContent()); sdk.register(CustomContentType.voice, () => new VoiceContent()); // 注册消息类型工厂(处理一类消息) sdk.registerFactor((contentType: number) => { // 处理 1000-2000 范围的系统消息 if (contentType >= 1000 && contentType <= 2000) { return new SystemNoticeContent(); // 自定义系统通知类 } return undefined; }); // 发送位置消息 const location = new LocationContent(); location.latitude = 39.9042; location.longitude = 116.4074; location.address = '北京市天安门广场'; await sdk.chatManager.send(location, channel); // 发送语音消息 const audioFile = getAudioFile(); // 获取音频文件 const voice = new VoiceContent(audioFile, 10); // 10秒语音 await sdk.chatManager.send(voice, channel); // 获取消息内容实例 const content = sdk.getMessageContent(CustomContentType.location); ``` -------------------------------- ### Unsubscribe from Channel Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Cancel the subscription to a channel, stopping real-time message delivery. The callback provides the reason code for the unsubscribe operation. ```typescript sdk.onUnsubscribe(channel, (reasonCode) => { console.log('取消订阅结果:', reasonCode); }); ``` -------------------------------- ### Add and Remove Event Listeners Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Register a listener function to receive real-time events from the SDK and unregister it when no longer needed. The listener processes various event types, including streaming messages. ```typescript import { WKSDK, WKEvent, EventType } from 'wukongimjssdk'; const sdk = WKSDK.shared(); // 添加事件监听器 const eventListener = (event: WKEvent) => { console.log('收到事件:', event.type); console.log('事件ID:', event.id); console.log('时间戳:', event.timestamp); console.log('数据:', event.dataJson); // 处理流式文本消息事件 switch (event.type) { case EventType.TextMessageStart: console.log('流式消息开始'); break; case EventType.TextMessageContent: console.log('流式消息追加:', event.dataJson.content); break; case EventType.TextMessageEnd: console.log('流式消息结束'); break; default: // 处理自定义事件 handleCustomEvent(event); } }; sdk.eventManager.addEventListener(eventListener); // 移除事件监听器 sdk.eventManager.removeEventListener(eventListener); ``` -------------------------------- ### Handle Custom Server-Sent Events Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Process custom events pushed from the server, such as user typing indicators, online/offline status changes, or other application-specific notifications. This function demonstrates a switch statement for different custom event types. ```typescript // 自定义事件处理示例 function handleCustomEvent(event: WKEvent) { const data = event.dataJson; switch (event.type) { case 'user_typing': console.log('用户正在输入:', data.uid); break; case 'user_online': console.log('用户上线:', data.uid); break; case 'user_offline': console.log('用户离线:', data.uid); break; } } ``` -------------------------------- ### Add Channel Member Change Listener Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Add a listener to be notified when the members of a channel change. This callback logs the channel ID and the current number of members. ```typescript const subscriberListener = (channel: Channel) => { console.log('频道成员变更:', channel.channelID); const members = sdk.channelManager.getSubscribes(channel); console.log('当前成员数:', members.length); }; sdk.channelManager.addSubscriberChangeListener(subscriberListener); ``` -------------------------------- ### Delete Channel Information from Cache Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Remove a specific channel's information from the SDK's cache. This can be useful for clearing outdated data. ```typescript const deletedInfo = sdk.channelManager.deleteChannelInfo(channel); ``` -------------------------------- ### Remove Listeners Source: https://context7.com/wukongim/wukongimjssdk/llms.txt Deregister previously added listeners for channel information changes and subscriber changes to stop receiving updates. ```typescript sdk.channelManager.removeListener(channelInfoListener); sdk.channelManager.removeSubscriberChangeListener(subscriberListener); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.