### Create Installation Directory Source: https://docs.githubim.com/zh/installation/docker/single-node Creates the directory for WuKongIM installation. ```bash mkdir ~/wukongim ``` -------------------------------- ### Create Installation Directory Source: https://docs.githubim.com/zh/installation/docker/scaling Use these commands to create and navigate to the WuKongIM installation directory on a new node. ```bash mkdir ~/wukongim ``` ```bash cd ~/wukongim ``` -------------------------------- ### Install WuKongIM JavaScript SDK Source: https://docs.githubim.com/zh/sdk/wukongim/javascript/integration Install the SDK using npm, yarn, pnpm, or bun. ```bash npm i wukongimjssdk ``` ```bash yarn add wukongimjssdk ``` ```bash pnpm add wukongimjssdk ``` ```bash bun add wukongimjssdk ``` -------------------------------- ### Navigate to Installation Directory Source: https://docs.githubim.com/zh/installation/docker/single-node Changes the current directory to the WuKongIM installation path. ```bash cd ~/wukongim ``` -------------------------------- ### Create WuKongIM Installation Directory Source: https://docs.githubim.com/zh/installation/docker/multi-node Creates the necessary directory structure for installing WuKongIM nodes and navigates into it. ```bash mkdir ~/wukongim cd ~/wukongim ``` -------------------------------- ### Send Message Example Source: https://docs.githubim.com/zh/sdk/wukongim/ios/chat Example demonstrating how to send a text message 'hello' to a user or a group. It shows the initialization of WKChannel and WKTextContent. ```objc // 给用户A发送消息hello WKChannel *channel = [[WKChannel alloc] initWith:@"A" channelType:WK_PERSON]; // 发送给群组 g1 // WKChannel *channel = [[WKChannel alloc] initWith:@"g1" channelType:WK_GROUP]; // 构建一个文本消息对象 WKTextContent *content = [[WKTextContent alloc] initWithContent:@"hello"]; // 发送此文本消息给指定频道 [[WKSDK shared].chatManager sendMessage:content channel:channel]; ``` -------------------------------- ### 插件 Setup 函数 Source: https://docs.githubim.com/zh/getting-started/learning/plugin-development 插件启动时调用的函数,用于初始化插件资源,如建立数据库连接。在此处实现插件的启动逻辑。 ```go func (a *AIExample) Setup() { // 插件初始化逻辑 fmt.Println("插件启动") } ``` -------------------------------- ### Check Configuration on Startup Source: https://docs.githubim.com/zh/server/configuration Command to perform a configuration check when WukongIM starts. ```bash # 启动时检查配置 ./wukongim --config wukongim.yaml --check-config ``` -------------------------------- ### Starting WuKongIM Cluster Nodes Source: https://docs.githubim.com/zh/server/configuration/cluster Commands to start each WuKongIM cluster node using its respective configuration file. The order of startup is not critical as the cluster will auto-elect a leader. ```bash # 在节点 1 上启动 ./wukongim --config wk-node1.yaml # 在节点 2 上启动 ./wukongim --config wk-node2.yaml # 在节点 3 上启动 ./wukongim --config wk-node3.yaml ``` -------------------------------- ### Complete Channel Information Usage Example (Java) Source: https://docs.githubim.com/zh/sdk/wukongim/android/channel An example demonstrating how to load, display, and listen for updates to channel information within an Android Activity. It includes handling local and remote data fetching, UI updates, and listener management. ```java public class ChatActivity extends AppCompatActivity { private String channelID; private byte channelType; private WKChannel currentChannel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); // 添加频道刷新监听 WKIM.getInstance().getChannelManager().addOnRefreshChannelInfo("ChatActivity", new IRefreshChannel() { @Override public void onRefreshChannel(WKChannel channel, boolean isEnd) { if (channel.channelID.equals(channelID) && channel.channelType == channelType) { runOnUiThread(() -> { currentChannel = channel; updateChannelUI(); }); } } }); // 加载频道信息 loadChannelInfo(); } private void loadChannelInfo() { // 先从本地获取 currentChannel = WKIM.getInstance().getChannelManager().getChannel(channelID, channelType); if (currentChannel != null) { // 本地有数据,直接使用 updateChannelUI(); } else { // 本地没有数据,从服务器获取 WKIM.getInstance().getChannelManager().fetchChannelInfo(channelID, channelType); showLoadingState(); } } private void updateChannelUI() { // 更新标题 setTitle(currentChannel.channelRemark != null ? currentChannel.channelRemark : currentChannel.channelName); // 更新头像 loadAvatar(currentChannel.avatar); // 更新置顶状态 updateTopStatus(currentChannel.top == 1); // 更新免打扰状态 updateMuteStatus(currentChannel.mute == 1); hideLoadingState(); } @Override protected void onDestroy() { super.onDestroy(); // 移除监听器 WKIM.getInstance().getChannelManager().removeRefreshChannelInfo("ChatActivity"); } } ``` -------------------------------- ### 故障排除 - 检查服务状态和端点 Source: https://docs.githubim.com/zh/installation/k8s/multi-node 当服务无法访问时,首先使用 `kubectl get svc` 检查 Service 状态,然后使用 `kubectl get endpoints` 确认是否有可用的后端 Pod。 ```bash # 检查服务状态 kubectl get svc -n wukongim # 检查端点 kubectl get endpoints -n wukongim ``` -------------------------------- ### Install WuKongIM SDK using ohpm Source: https://docs.githubim.com/zh/sdk/wukongim/harmonyos/integration Use this command to install the WuKongIM SDK package via ohpm. Ensure you have ohpm configured in your project. ```bash ohpm install @wukong/wkim ``` -------------------------------- ### Comprehensive Channel Member Management Example Source: https://docs.githubim.com/zh/sdk/wukongim/flutter/channel_member A complete example class demonstrating various channel member operations including fetching, filtering by role, searching, and checking member status. Assumes specific role IDs (1 for admin, 2 for blacklist) and requires proper initialization of WKIM. ```dart class ChannelMemberManager { // 获取所有成员 static List getAllMembers(String channelId) { try { final members = WKIM.shared.channelMemberManager.getMembers(channelId: channelId); print('获取到 ${members.length} 个成员'); return members; } catch (error) { print('获取成员列表失败: $error'); return []; } } // 获取指定成员信息 static WKChannelMember? getMemberInfo(String channelId, String uid) { try { final member = WKIM.shared.channelMemberManager.getMember(channelId: channelId, uid: uid); if (member != null) { print('获取成员信息成功: ${member.memberName}'); } return member; } catch (error) { print('获取成员信息失败: $error'); return null; } } // 按角色筛选成员 static List getMembersByRole(String channelId, int role) { final allMembers = getAllMembers(channelId); return allMembers.where((member) => member.role == role).toList(); } // 获取管理员列表 static List getAdminMembers(String channelId) { return getMembersByRole(channelId, 1); // 假设1为管理员角色 } // 获取普通成员列表 static List getNormalMembers(String channelId) { return getMembersByRole(channelId, 0); // 假设0为普通成员角色 } // 搜索成员 static List searchMembers(String channelId, String keyword) { if (keyword.trim().isEmpty) { return []; } final allMembers = getAllMembers(channelId); return allMembers.where((member) { final name = member.memberName.toLowerCase(); final remark = member.memberRemark.toLowerCase(); final uid = member.memberUID.toLowerCase(); final searchKey = keyword.toLowerCase(); return name.contains(searchKey) || remark.contains(searchKey) || uid.contains(searchKey); }).toList(); } // 获取在线成员(需要结合频道信息) static List getOnlineMembers(String channelId) { final allMembers = getAllMembers(channelId); // 这里需要结合频道管理器获取在线状态 return allMembers.where((member) { final channel = WKIM.shared.channelManager.getChannel(member.memberUID, WKChannelType.personal); return channel?.online == 1; }).toList(); } // 获取成员显示名称 static String getMemberDisplayName(WKChannelMember member) { if (member.memberRemark.isNotEmpty) { return member.memberRemark; } if (member.memberName.isNotEmpty) { return member.memberName; } return member.memberUID; } // 检查成员是否为管理员 static bool isAdmin(WKChannelMember member) { return member.role == 1; // 假设1为管理员角色 } // 检查成员是否被禁言 static bool isMuted(WKChannelMember member) { if (member.forbiddenExpirationTime == 0) { return false; } final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; return member.forbiddenExpirationTime > now; } // 检查成员是否在黑名单 static bool isBlacklisted(WKChannelMember member) { return member.status == 2; // 2表示黑名单状态 } } ``` -------------------------------- ### Full Example: Group Members Activity (Java) Source: https://docs.githubim.com/zh/sdk/wukongim/android/channel-member A comprehensive example demonstrating how to load and display channel members within an Android Activity. It handles fetching members, updating the UI, and showing member profiles. ```java public class GroupMembersActivity extends AppCompatActivity { private String channelId; private byte channelType; private List memberList = new ArrayList<>(); private MemberAdapter memberAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_members); setupRecyclerView(); loadMembers(); } private void loadMembers() { // 获取频道所有成员 List members = WKIM.getInstance().getChannelMembersManager() .getMembers(channelId, channelType); if (members != null && !members.isEmpty()) { memberList.clear(); memberList.addAll(members); memberAdapter.notifyDataSetChanged(); updateMemberCount(members.size()); } else { // 本地没有数据,可能需要从服务器同步 showEmptyState(); } } private void getMemberInfo(String uid) { WKChannelMember member = WKIM.getInstance().getChannelMembersManager() .getMember(channelId, channelType, uid); if (member != null) { showMemberProfile(member); } else { showToast("成员信息不存在"); } } private void updateMemberCount(int count) { setTitle("群成员 (" + count + ")"); } } ``` -------------------------------- ### 检查 Pod 和服务状态 Source: https://docs.githubim.com/zh/installation/k8s/single-node 部署后,使用 `kubectl get pods` 和 `kubectl get svc` 命令检查 WuKongIM 的 Pod 和 Service 是否正常运行。 ```bash kubectl get pods -n wukongim ``` ```bash kubectl get svc -n wukongim ``` ```bash kubectl logs -l app.kubernetes.io/name=wukongim -n wukongim ``` -------------------------------- ### 验证扩容 - 检查 Pod 数量 Source: https://docs.githubim.com/zh/installation/k8s/multi-node 扩容操作后,使用 `kubectl get pods` 命令检查 Pod 的数量是否已更新为目标副本数,以验证扩容是否成功。 ```bash # 检查 Pod 数量 kubectl get pods -n wukongim ``` -------------------------------- ### Run Flutter Pub Get Source: https://docs.githubim.com/zh/sdk/easy/flutter/getting-started After adding the dependency, run this command in your terminal to fetch the package. ```bash flutter pub get ``` -------------------------------- ### CocoaPods 集成 Source: https://docs.githubim.com/zh/sdk/easy/ios/getting-started 在 Podfile 中添加 WuKongEasySDK 依赖,然后运行 pod install 来集成 SDK。 ```ruby pod 'WuKongEasySDK', '~> 1.0.0' ``` ```bash pod install ``` -------------------------------- ### 验证扩容 Source: https://docs.githubim.com/zh/installation/k8s/single-node 扩容后,使用 `kubectl get pods` 检查 Pod 数量是否已更新,并使用 `curl` 命令检查集群节点状态。 ```bash kubectl get pods -n wukongim ``` ```bash kubectl port-forward svc/wkim-wukongim 5001:5001 -n wukongim & curl http://localhost:5001/cluster/nodes ``` -------------------------------- ### Python Example for Streaming Text Messages Source: https://docs.githubim.com/zh/api/event/send This Python code demonstrates sending streaming text messages using the `requests` library. It covers starting, sending content, and ending the stream. ```python import requests import time # 流式文本消息示例 stream_id = f"stream_{int(time.time() * 1000)}" base_url = "http://localhost:5001/event" # 1. 开始流 requests.post(base_url, json={ "client_msg_no": stream_id, "channel_id": "group_ai_chat", "channel_type": 2, "from_uid": "ai_assistant", "event": { "type": "___TextMessageStart", "data": "开始AI回复..." } }) # 2. 发送内容 requests.post(base_url, json={ "client_msg_no": stream_id, "channel_id": "group_ai_chat", "channel_type": 2, "from_uid": "ai_assistant", "event": { "type": "___TextMessageContent", "data": "你好!我可以为你做什么?" } }) # 3. 结束流 requests.post(base_url, json={ "client_msg_no": stream_id, "channel_id": "group_ai_chat", "channel_type": 2, "from_uid": "ai_assistant", "event": { "type": "___TextMessageEnd", "data": "" } }) ``` -------------------------------- ### Unified Entry Point Example in Java Source: https://docs.githubim.com/zh/sdk/wukongim/android/intro Illustrates the unified entry point for accessing all SDK functionalities in WuKongIM Android SDK. This pattern simplifies development by providing a single instance to manage various features. ```java WKIM.getInstance().getConnectionManager().connection() ``` -------------------------------- ### JavaScript Example for Streaming Text Messages Source: https://docs.githubim.com/zh/api/event/send This JavaScript code demonstrates how to send streaming text messages using the Fetch API. It includes starting, sending content, and ending the stream. ```javascript // 流式文本消息示例 const streamId = `stream_${Date.now()}`; // 1. 开始流 await fetch('http://localhost:5001/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_msg_no: streamId, channel_id: 'group_ai_chat', channel_type: 2, from_uid: 'ai_assistant', event: { type: '___TextMessageStart', data: '开始AI回复...' } }) }); // 2. 发送内容 await fetch('http://localhost:5001/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_msg_no: streamId, channel_id: 'group_ai_chat', channel_type: 2, from_uid: 'ai_assistant', event: { type: '___TextMessageContent', data: '你好!我可以为你做什么?' } }) }); // 3. 结束流 await fetch('http://localhost:5001/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_msg_no: streamId, channel_id: 'group_ai_chat', channel_type: 2, from_uid: 'ai_assistant', event: { type: '___TextMessageEnd', data: '' } }) }); ``` -------------------------------- ### Get Reminders Source: https://docs.githubim.com/zh/sdk/wukongim/android/reminder Retrieve reminder items for a specific session or by type. This includes fetching all reminders for a session, reminders of a specific type (e.g., mentions, group audits), and examples for processing and counting reminders. ```APIDOC ## Get Reminders ### Get Reminders for a Specific Session This method retrieves all reminder items associated with a given channel ID and channel type. **Method:** N/A (Client-side SDK method) **Endpoint:** N/A #### Parameters - **channelId** (String) - Required - The ID of the channel. - **channelType** (byte) - Required - The type of the channel. ### Request Example ```java // Java WKIM.getInstance().getReminderManager().getReminders(channelId, channelType); ``` ```kotlin // Kotlin WKIM.getInstance().reminderManager.getReminders(channelId, channelType) ``` ### Get Reminders for a Specific Type This method retrieves reminder items of a specific type for a given channel ID and channel type. **Method:** N/A (Client-side SDK method) **Endpoint:** N/A #### Parameters - **channelID** (String) - Required - The ID of the channel. - **channelType** (byte) - Required - The type of the channel. - **type** (int) - Required - The type of reminder to retrieve (e.g., 1 for mentions, 2 for group audits). ### Request Example ```java // Java WKIM.getInstance().getReminderManager().getRemindersWithType(channelID, channelType, type); ``` ```kotlin // Kotlin WKIM.getInstance().reminderManager.getRemindersWithType(channelID, channelType, type) ``` ### Full Example: Processing Reminders This section provides comprehensive examples for various reminder management tasks, including: - Getting all reminders mentioning the current user. - Retrieving group audit reminders. - Fetching all unfinished reminders. - Counting reminders by type. - Getting the latest reminder. **Method:** N/A (Client-side SDK methods) **Endpoint:** N/A #### Request Example (Java) ```java public class ReminderHelper { // Get all @mention reminders public List getMentionReminders(String channelId, byte channelType) { return WKIM.getInstance().getReminderManager().getRemindersWithType(channelId, channelType, 1); } // Get group audit reminders public List getAuditReminders(String channelId, byte channelType) { return WKIM.getInstance().getReminderManager().getRemindersWithType(channelId, channelType, 2); } // Get all unfinished reminders public List getUnfinishedReminders(String channelId, byte channelType) { List allReminders = WKIM.getInstance().getReminderManager().getReminders(channelId, channelType); List unfinishedReminders = new ArrayList<>(); if (allReminders != null) { for (WKReminder reminder : allReminders) { if (reminder.done == 0) { // 0 indicates unfinished unfinishedReminders.add(reminder); } } } return unfinishedReminders; } // Count reminders by type public Map getReminderCountByType(String channelId, byte channelType) { List allReminders = WKIM.getInstance().getReminderManager().getReminders(channelId, channelType); Map countMap = new HashMap<>(); if (allReminders != null) { for (WKReminder reminder : allReminders) { if (reminder.done == 0) { // Count only unfinished reminders countMap.put(reminder.type, countMap.getOrDefault(reminder.type, 0) + 1); } } } return countMap; } // Get the latest reminder public WKReminder getLatestReminder(String channelId, byte channelType) { List reminders = WKIM.getInstance().getReminderManager().getReminders(channelId, channelType); if (reminders == null || reminders.isEmpty()) { return null; } // Sort by version to get the latest WKReminder latestReminder = reminders.get(0); for (WKReminder reminder : reminders) { if (reminder.version > latestReminder.version) { latestReminder = reminder; } } return latestReminder; } } ``` -------------------------------- ### Pull Up Messages Source: https://docs.githubim.com/zh/sdk/wukongim/ios/chat Loads messages by pulling upwards in a channel. Specify `startOrderSeq` to fetch messages succeeding that sequence number. For example, to get 10 messages after sequence 100, `startOrderSeq` would be 100, and the result would be messages with sequence numbers 101-110. ```objc /** 上拉加载消息 @param startOrderSeq 起始的orderSeq 比如需要查询 100以下的10条消息 那么startOrderSeq就是100 查询出来的数据为 101 102 103 104 105 106 107 108 109 110 @param limit 消息数量限制 @param complete 查询回调 */ [[WKSDK shared].chatManager pullUp:(WKChannel*)channel startOrderSeq:(uint32_t)startOrderSeq limit:(int)limit complete:(void(^)(NSArray *messages, NSError *error))complete]; ``` -------------------------------- ### 启动插件 Source: https://docs.githubim.com/zh/getting-started/learning/plugin-development 使用 `pdk.RunServer` 函数启动插件,并配置插件的唯一标识符、版本号和优先级。这是插件运行的入口。 ```go func main() { pdk.RunServer(New, "wk.plugin.ai-example", pdk.WithVersion("0.0.1"), pdk.WithPriority(1)) } ``` -------------------------------- ### Pull Down Messages Source: https://docs.githubim.com/zh/sdk/wukongim/ios/chat Loads messages by pulling downwards in a channel. Specify `startOrderSeq` to fetch messages preceding that sequence number. For example, to get 10 messages before sequence 100, `startOrderSeq` would be 100, and the result would be messages with sequence numbers 90-99. ```objc /** 下拉加载消息 @param channel 频道 @param startOrderSeq 起始的orderSeq 比如需要查询 100以上的10条消息 那么startOrderSeq就是100 查询出来的数据为 90 91 92 93 94 95 96 97 98 99 @param limit 消息数量限制 @param complete 查询回调 */ [[WKSDK shared].chatManager pullDown:(WKChannel*)channel startOrderSeq:(uint32_t)startOrderSeq limit:(int)limit complete:(void(^)(NSArray *messages, NSError *error))complete]; ``` -------------------------------- ### Install Dependencies via CocoaPods Source: https://docs.githubim.com/zh/sdk/wukongim/ios/integration Execute the 'pod install' command in your project directory to install the dependencies specified in your Podfile, including WuKongIMSDK. ```bash pod install ``` -------------------------------- ### 插件 ConfigUpdate 函数 Source: https://docs.githubim.com/zh/getting-started/learning/plugin-development 当插件配置发生变化时调用。用于响应配置更新,重新加载配置或执行相关逻辑。 ```go func (a *AIExample) ConfigUpdate() { // 配置更新处理逻辑 fmt.Printf("配置已更新: %+v\n", a.Config) } ``` -------------------------------- ### Initialize and Connect SDK (Web) Source: https://docs.githubim.com/zh/getting-started/concepts/user Initializes the EasySDK for web applications, setting up user credentials and event listeners for connection status. ```javascript import { WKIM, WKIMEvent } from 'easyjssdk'; // 初始化 SDK const im = WKIM.init("ws://your-server.com:5200", { uid: "user123", // 用户唯一标识 token: "your_auth_token" // 用户认证令牌 }); // 监听连接状态 im.on(WKIMEvent.Connect, (result) => { console.log('用户已连接:', result); }); im.on(WKIMEvent.Disconnect, (disconnectInfo) => { console.log('用户已断开连接:', disconnectInfo); }); // 连接到服务器 try { await im.connect(); console.log("连接成功!"); } catch (error) { console.error("连接失败:", error); } ``` -------------------------------- ### Start WuKongIM Service Source: https://docs.githubim.com/zh/installation/docker/single-node Starts the WuKongIM services defined in the docker-compose.yml file in detached mode. ```bash sudo docker-compose up -d ``` -------------------------------- ### 启动插件进行本地调试 Source: https://docs.githubim.com/zh/getting-started/learning/plugin-development 在 WuKongIM 启动后,进入您的插件目录并运行插件的 `main.go` 文件来启动插件。 ```bash cd my-plugin go run main.go ``` -------------------------------- ### 端口转发访问 Demo 界面 Source: https://docs.githubim.com/zh/installation/k8s/multi-node 使用 `kubectl port-forward` 命令将本地端口映射到 WuKongIM 的 Demo 界面端口,以便在浏览器中访问。 ```bash # Demo 界面 kubectl port-forward svc/wkim-wukongim 5172:5172 -n wukongim ``` -------------------------------- ### Message Types Examples Source: https://docs.githubim.com/zh/api/message/send Examples of Payload structures for different message types according to WuKongIM protocol. ```APIDOC ### Regular Messages #### Text Message ```json { "type": 1, "content": "这是一条文本消息" } ``` #### Text Message (with @ mention) ```json { "type": 1, "content": "这是一条文本消息", "mention": { "all": 0, "uids": ["1223", "2323"] } } ``` * `mention.all`: Whether to mention everyone (0=mention users, 1=mention all) * `mention.uids`: If all=1, this field is empty #### Text Message (with reply) ```json { "type": 1, "content": "回复了某某", "reply": { "root_mid": "xxx", "message_id": "xxxx", "message_seq": 123, "from_uid": "xxxx", "from_name": "xxx", "payload": {} } } ``` #### Image Message ```json { "type": 2, "url": "http://xxxxx.com/xxx", "width": 200, "height": 320 } ``` #### GIF Message ```json { "type": 3, "url": "http://xxxxx.com/xxx", "width": 72, "height": 72 } ``` #### Voice Message ```json { "type": 4, "url": "http://xxxxx.com/xxx", "timeTrad": 10 } ``` `timeTrad`: Voice duration in seconds #### File Message ```json { "type": 8, "url": "http://xxxxx.com/xxx", "name": "xxxx.docx", "size": 238734 } ``` `size`: File size in bytes #### Command Message ```json { "type": 99, "cmd": "groupUpdate", "param": {} } ``` ``` ```APIDOC ### System Messages System message type must be greater than 1000 #### Create Group Chat Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1001, "creator": "xxx", "creator_name": "张三", "content": "{0}邀请{1}、{2}加入群聊", "extra": [ {"uid": "xxx", "name": "张三"}, {"uid": "xx01", "name": "李四"}, {"uid": "xx02", "name": "王五"} ] } ``` #### Add Group Member Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1002, "content": "{0}邀请{1}、{2}加入群聊", "extra": [ {"uid": "xxx", "name": "张三"}, {"uid": "xx01", "name": "李四"}, {"uid": "xx02", "name": "王五"} ] } ``` #### Remove Group Member Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1003, "content": "{0}将{1}移除群聊", "extra": [ {"uid": "xxx", "name": "张三"}, {"uid": "xx01", "name": "李四"} ] } ``` #### Group Member Kicked Message Settings: `NoPersist:0, RedDot:1, SyncOnce:0` ```json { "type": 1010, "content": "你被{0}移除群聊", "extra": [ {"uid": "xxx", "name": "张三"} ] } ``` #### Update Group Name Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1005, "content": "{0}修改群名为\"测试群\"", "extra": [ {"uid": "xxx", "name": "张三"} ] } ``` #### Update Group Announcement Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1005, "content": "{0}修改群公告为\"这是一个群公告\"", "extra": [ {"uid": "xxx", "name": "张三"} ] } ``` #### Recall Message Message Settings: `NoPersist:0, RedDot:0, SyncOnce:1` ```json { "type": 1006, "message_id": "234343435", "content": "{0}撤回了一条消息", "extra": [ {"uid": "xxx", "name": "张三"} ] } ``` ``` ```APIDOC ### Command Messages #### Basic Command Message Message Settings: `SyncOnce:1` ```json { "type": 99, "cmd": "cmd", "param": {} } ``` #### Group Member Information Update Upon receiving this message, the client should incrementally synchronize group member information. ```json { "type": 99, "cmd": "memberUpdate", "param": { "group_no": "xxxx" } } ``` #### Red Dot Elimination Upon receiving this command, the client should clear the red dot for the corresponding conversation. ```json { "type": 99, "cmd": "unreadClear", "param": { "channel_id": "xxxx", "channel_type": 2 } } ``` ``` -------------------------------- ### 创建插件项目 Source: https://docs.githubim.com/zh/getting-started/learning/plugin-development 创建一个新的插件项目目录,初始化 Go 模块并下载 go-pdk 依赖。这是插件开发的起点。 ```bash mkdir my-plugin cd my-plugin go mod init my-plugin go get github.com/WuKongIM/go-pdk ``` -------------------------------- ### Successful Response Example Source: https://docs.githubim.com/zh/api/user/system-uids This is an example of a successful JSON response containing a list of system user IDs. ```json [ "system", "admin", "bot", "notification", "webhook" ] ``` -------------------------------- ### Migration Historical Completion Response Example Source: https://docs.githubim.com/zh/api/system/migrate Example JSON response for a migration that has already been completed historically. ```json { "status": "migrated", "step": "channel", "last_err": null, "try_count": 1 } ``` -------------------------------- ### Migration Running Response Example Source: https://docs.githubim.com/zh/api/system/migrate Example JSON response showing that the migration process is currently in progress. ```json { "status": "running", "step": "user", "last_err": null, "try_count": 2 } ``` -------------------------------- ### 故障排除 - 查看 Pod 状态和详细信息 Source: https://docs.githubim.com/zh/installation/k8s/multi-node 当 Pod 启动失败时,首先使用 `kubectl get pods` 查看状态,然后使用 `kubectl describe pod` 获取详细事件和诊断信息。 ```bash # 查看 Pod 状态 kubectl get pods -n wukongim # 查看详细信息 kubectl describe pod -n wukongim ``` -------------------------------- ### Migration Completed Response Example Source: https://docs.githubim.com/zh/api/system/migrate Example JSON response indicating that the migration process has successfully completed. ```json { "status": "completed", "step": "message", "last_err": null, "try_count": 1 } ``` -------------------------------- ### 排查服务无法访问 Source: https://docs.githubim.com/zh/installation/k8s/single-node 当服务无法访问时,检查 `kubectl get svc` 和 `kubectl get endpoints` 确认服务和端点状态,并使用 `kubectl exec` 测试服务连通性。 ```bash kubectl get svc -n wukongim ``` ```bash kubectl get endpoints -n wukongim ``` ```bash kubectl exec -it -n wukongim -- wget -qO- http://localhost:5001/health ``` -------------------------------- ### Initialize WuKongIM SDK Source: https://docs.githubim.com/zh/sdk/easy/flutter/getting-started Initialize the SDK with your server URL, user ID, and authentication token. Ensure the server URL is correct and the token is valid for authentication. ```dart // 1. Initialize SDK final config = WuKongConfig( serverUrl: "ws://your-wukongim-server.com:5200", uid: "your_user_id", // 您的用户 ID token: "your_auth_token", // 您的认证 Token // deviceId: "optional_device_id", // 可选:设备 ID // deviceFlag: WuKongDeviceFlag.app, // 可选:设备标识,默认为 app ); final easySDK = WuKongEasySDK.getInstance(); await easySDK.init(config); ``` -------------------------------- ### Start and Stop WuKongIM Service Source: https://docs.githubim.com/zh/installation/linux/single-node.md Commands to start and stop the WuKongIM service. Use the `-d` flag for background execution. ```bash # 启动 (-d表示后台运行,否则是前台运行) ./wukongim --config wk.yaml -d # 停止 ./wukongim stop ``` -------------------------------- ### Initialize WuKongIM SDK Source: https://docs.githubim.com/zh/sdk/wukongim/harmonyos/base Call this method to initialize the SDK with user credentials. Ensure you have the correct uid and token from your business server. ```typescript await WKIM.shared.init(uid, token) ``` -------------------------------- ### Send Text Message Example Source: https://docs.githubim.com/zh/sdk/wukongim/javascript/chat Example of sending a text message to a user or a group channel. Ensure you import the necessary classes. ```javascript // 导入 对应的包 import { MessageText,Channel,WKSDK,ChannelTypePerson,ChannelTypeGroup } from "wukongimjssdk"; // 例如发送文本消息hello给用户u10001 const text = new MessageText("hello") // 文本消息 WKSDK.shared().chatManager.send(text,new Channel("u10001",ChannelTypePerson)) // 例如发送文本消息hello给群频道g10001 WKSDK.shared().chatManager.send(text,new Channel("g10001",ChannelTypeGroup)) ``` -------------------------------- ### 扩容到多节点 Source: https://docs.githubim.com/zh/installation/k8s/single-node 使用 `helm upgrade` 命令将 WuKongIM 的副本数从 1 扩容到 3,以增加可用性和处理能力。 ```bash helm upgrade wkim wukongim/wukongim \ -n wukongim \ --version 0.1.0 \ --set replicaCount=3 ``` -------------------------------- ### Initialize and Connect SDK (Android) Source: https://docs.githubim.com/zh/getting-started/concepts/user Initializes the EasySDK for Android applications, setting up user authentication and connection event listeners. ```kotlin import com.githubim.easysdk.WuKongEasySDK import com.githubim.easysdk.WuKongConfig import com.githubim.easysdk.WuKongEvent import com.githubim.easysdk.listener.WuKongEventListener // 配置用户信息 val config = WuKongConfig.Builder() .serverUrl("ws://your-server.com:5200") .uid("user123") // 用户唯一标识 .token("your_auth_token") // 用户认证令牌 .build() // 初始化 SDK val easySDK = WuKongEasySDK.getInstance() easySDK.init(this, config) // 监听连接状态 easySDK.addEventListener(WuKongEvent.CONNECT, object : WuKongEventListener { override fun onEvent(result: ConnectResult) { Log.d("WuKong", "用户已连接: $result") } }) easySDK.addEventListener(WuKongEvent.DISCONNECT, object : WuKongEventListener { override fun onEvent(disconnectInfo: DisconnectInfo) { Log.d("WuKong", "用户已断开连接: $disconnectInfo") } }) // 连接到服务器 lifecycleScope.launch { try { easySDK.connect() Log.d("WuKong", "连接成功!") } catch (e: Exception) { Log.e("WuKong", "连接失败: $e") } } ``` -------------------------------- ### Conversation Deletion Operation Examples Source: https://docs.githubim.com/zh/sdk/wukongim/android/conversation Provides examples for deleting a single conversation with user confirmation and for batch deleting multiple conversations. ```java public class ConversationOperationHelper { // 删除会话 public void deleteConversation(String channelId, byte channelType) { // 显示确认对话框 new AlertDialog.Builder(context) .setTitle("删除会话") .setMessage("确定要删除这个会话吗?") .setPositiveButton("删除", (dialog, which) -> { // 执行删除操作 WKIM.getInstance().getConversationManager().deleteWitchChannel(channelId, channelType); // 同时调用服务器API ApiManager.deleteConversation(channelId, channelType, new ApiCallback() { @Override public void onSuccess(Void result) { // 删除成功 showToast("会话已删除"); } @Override public void onError(int code, String message) { // 删除失败,可能需要恢复会话 showToast("删除失败: " + message); } }); }) .setNegativeButton("取消", null) .show(); } // 批量删除会话 public void deleteMultipleConversations(List conversations) { for (WKUIConversationMsg conversation : conversations) { WKIM.getInstance().getConversationManager().deleteWitchChannel( conversation.getWkChannel().channelID, conversation.getWkChannel().channelType ); } showToast("已删除 " + conversations.size() + " 个会话"); } } ``` -------------------------------- ### Receive Acknowledgment Request Example Source: https://docs.githubim.com/zh/getting-started/learning/jsonrpc Example of a client request to acknowledge receipt of a specific message. This is crucial for reliable message delivery. ```json { "method": "recvack", "params": { "messageId": "serverMsgId2", "messageSeq": 50 } } ``` -------------------------------- ### Plugin Configuration (YAML) Source: https://docs.githubim.com/zh/server/configuration Configure WukongIM plugins using YAML. Specify the socket path for communication and a list of plugins to install on startup. ```yaml # 插件配置 plugin: socketPath: "./wukongimdata/1/wukongim.sock" # 插件的unix socket地址,用于与插件通讯 install: # 默认安装的插件列表,启动时会自动安装这些插件 - "https://gitee.com/WuKongDev/plugins/releases/download/latest/wk.plugin.ai-example-${os}-${arch}.wkp" - "https://gitee.com/WuKongDev/plugins/releases/download/latest/wk.plugin.ai-volcengine-${os}-${arch}.wkp" ``` -------------------------------- ### Start WuKongIM Service Source: https://docs.githubim.com/zh/installation/linux/scaling Launch the WuKongIM service in release mode using the specified configuration file. The `-d` flag runs the process in the background. ```bash ./wukongim --config wk.yaml -d ``` -------------------------------- ### Start WuKongIM Service Source: https://docs.githubim.com/zh/installation/linux/multi-node Command to start the WuKongIM service in detached mode. Ensure Nginx is restarted for configuration changes to take effect. ```bash ./wukongim --config wk.yaml -d # 停止 # ./wukongim stop ``` -------------------------------- ### Event Notification Example Source: https://docs.githubim.com/zh/getting-started/learning/jsonrpc Example of a server-sent event notification. This is used for system status changes or user actions, distinct from regular messages. ```json { "method": "event", "params": { "type": "user_online", "timestamp": 1678886400000, "payload": { "uid": "user123", "deviceId": "device456", "status": "online" } } } ``` -------------------------------- ### Synchronize User Sessions (Go) Source: https://docs.githubim.com/zh/api/conversation/sync Synchronize user sessions in Go by making an HTTP POST request. This example includes setting up the request body and handling the response. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { data := map[string]interface{}{ "uid": "user123", "version": 1640995200000000000, "last_msg_seqs": "user1:1:100|group1:2:200", "msg_count": 10, "only_unread": 0, "exclude_channel_types": []int{3, 4}, } jsonData, _ := json.Marshal(data) resp, err := http.Post( "http://localhost:5001/conversation/sync", "application/json", bytes.NewBuffer(jsonData), ) if err != nil { panic(err) } defer resp.Body.Close() var result []map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) fmt.Printf("%+v\n", result) } ``` -------------------------------- ### Receive Notification Example Source: https://docs.githubim.com/zh/getting-started/learning/jsonrpc Example of a server push notification received by the client. It contains message details like sender, channel, and payload. ```json { "method": "recv", "params": { "messageId": "serverMsgId2", "messageSeq": 50, "timestamp": 1678886400, "channelId": "senderUser", "channelType": 1, "fromUid": "senderUser", "payload": {"content": "How are you?","type":1} } } ``` -------------------------------- ### 备份数据 - 复制备份文件到本地 Source: https://docs.githubim.com/zh/installation/k8s/multi-node 使用 `kubectl cp` 命令将备份服务器上的压缩文件复制到本地目录,以便进行本地存储或传输。 ```bash # 复制备份文件到本地 kubectl cp wukongim/:/tmp/backup-$(date +%Y%m%d).tar.gz \ ./wukongim-backup-$(date +%Y%m%d).tar.gz ``` -------------------------------- ### Initialize and Connect SDK (iOS) Source: https://docs.githubim.com/zh/getting-started/concepts/user Initializes the EasySDK for iOS applications, configuring user details and handling connection events. ```swift import WuKongEasySDK // 配置用户信息 let config = WuKongConfig( serverUrl: "ws://your-server.com:5200", uid: "user123", // 用户唯一标识 token: "your_auth_token" // 用户认证令牌 ) // 初始化 SDK let easySDK = WuKongEasySDK(config: config) // 监听连接状态 easySDK.onConnect { result in print("用户已连接:", result) } easySDK.onDisconnect { disconnectInfo in print("用户已断开连接:", disconnectInfo) } // 连接到服务器 Task { do { try await easySDK.connect() print("连接成功!") } catch { print("连接失败:", error) } } ``` -------------------------------- ### Start WuKongIM Nodes Source: https://docs.githubim.com/zh/installation/docker/multi-node Command to start all deployed WuKongIM nodes using Docker Compose in detached mode. This should be run after the load balancer and monitoring are up. ```bash # 在每个 WuKongIM 节点 cd ~/wukongim docker-compose up -d ```