### Start Single-Node WuKongIM (Go) Source: https://docs.githubim.com/en/getting-started/learning/plugin-development This command starts a single-node instance of WuKongIM using a specified configuration file. Requires Go to be installed and the WuKongIM source code to be present. ```go go run main.go --config exampleconfig/single.yaml ``` -------------------------------- ### Docker Compose Setup for Development Source: https://docs.githubim.com/en/installation/overview Quickly set up WuKongIM for local development and testing using Docker Compose. This method provides a fast way to get started. It requires Docker and Docker Compose to be installed. ```bash # Get started in minutes curl -O https://raw.githubusercontent.com/WuKongIM/WuKongIM/main/docker-compose.yml docker-compose up -d ``` -------------------------------- ### Initialize and Configure WuKongIM SDK Source: https://docs.githubim.com/en/sdk/wukongim/javascript/integration Get an instance of the SDK and configure it with essential connection details like server addresses, user ID, and authentication token. This setup is crucial for establishing a connection. ```javascript // Get SDK instance const sdk = WKSDK.shared(); // Configure SDK sdk.config({ addr: "ws://your-server.com:5200", // WebSocket server address apiURL: "http://your-api-server.com", // API server address uploadURL: "http://your-upload-server.com", // File upload server address uid: "user123", // User ID token: "user-auth-token" // User authentication token }); ``` -------------------------------- ### Complete WuKongIM Helm Installation Example Source: https://docs.githubim.com/en/installation/k8s/multi-node Provides a comprehensive example of `helm install` for WuKongIM, showcasing various configuration parameters such as image tag, service type, persistence, resource requests, and replica count. ```bash helm install wkim wukongim/wukongim \ -n wukongim \ --create-namespace \ --version 0.1.0 \ --set replicaCount=3 \ --set image.tag=v2.0.0 \ --set service.type=LoadBalancer \ --set persistence.enabled=true \ --set persistence.size=50Gi \ --set resources.requests.memory=4Gi \ --set resources.requests.cpu=2000m ``` -------------------------------- ### Complete WuKongIM Configuration Example Source: https://docs.githubim.com/en/installation/linux/monitoring A comprehensive example of the `wk.yaml` configuration for WuKongIM, including cluster settings, external network configurations, monitoring setup with Prometheus, and logging preferences. This serves as a template for a typical deployment. ```yaml mode: "release" rootDir: "./wukongim_data" # Cluster configuration (for multi-node) cluster: nodeId: 1001 serverAddr: "10.206.0.13:11110" apiUrl: "http://10.206.0.13:5001" initNodes: - "1001@10.206.0.13:11110" - "1002@10.206.0.14:11110" - "1003@10.206.0.8:11110" # External configuration external: ip: "119.45.229.172" tcpAddr: "119.45.229.172:15100" wsAddr: "ws://119.45.229.172:15200" # Monitoring configuration trace: prometheusApiUrl: "http://10.206.0.13:9090" # Logging configuration logger: level: "info" dir: "./logs" ``` -------------------------------- ### Start and Enable Grafana Server Source: https://docs.githubim.com/en/installation/linux/monitoring Commands to enable the Grafana server to start on boot and to start the service immediately. These are essential for setting up the monitoring dashboard. ```bash sudo systemctl enable grafana-server sudo systemctl start grafana-server ``` -------------------------------- ### Complete Helm Installation Example Source: https://docs.githubim.com/en/installation/k8s/single-node A comprehensive Helm install command demonstrating various configuration options for WuKongIM, including image tag, service type, persistence settings, and resource requests. ```bash helm install wkim wukongim/wukongim \ -n wukongim \ --create-namespace \ --version 0.1.0 \ --set replicaCount=1 \ --set image.tag=v2.0.0 \ --set service.type=LoadBalancer \ --set persistence.enabled=true \ --set persistence.size=20Gi \ --set resources.requests.memory=2Gi \ --set resources.requests.cpu=1000m ``` -------------------------------- ### Download WuKongIM Source Code (Bash) Source: https://docs.githubim.com/en/getting-started/learning/plugin-development This command clones the WuKongIM repository from GitHub to your local machine. Ensure you have Git installed. ```bash git clone https://github.com/WuKongIM/WuKongIM.git cd WuKongIM ``` -------------------------------- ### Install WuKongIM HarmonyOS SDK using ohpm Source: https://docs.githubim.com/en/sdk/wukongim/harmonyos/integration This command installs the WuKongIM SDK package for HarmonyOS using the ohpm package manager. Ensure you have ohpm configured and available in your environment. ```bash ohpm install @wukong/wkim ``` -------------------------------- ### Install WuKongIM JavaScript SDK Source: https://docs.githubim.com/en/sdk/wukongim/javascript/integration Install the WuKongIM JavaScript SDK using various package managers like npm, yarn, pnpm, or bun. This is the first step to using the SDK in your project. ```bash npm i wukongimjssdk ``` ```bash yarn add wukongimjssdk ``` ```bash pnpm add wukongimjssdk ``` ```bash bun add wukongimjssdk ``` -------------------------------- ### Initialize WuKongIM iOS SDK (Basic) Source: https://docs.githubim.com/en/sdk/wukongim/ios/integration Initialize the WuKongIM SDK in your AppDelegate's didFinishLaunchingWithOptions method using the shared instance and its setup method. ```swift // Swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Initialize WuKongIM SDK WKSDK.shared.setup() return true } ``` ```objc // Objective-C - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Initialize WuKongIM SDK [WKSDK.shared setup]; return YES; } ``` -------------------------------- ### Troubleshoot WuKongIM Service Start Failure Source: https://docs.githubim.com/en/installation/linux/upgrade Provides commands to diagnose why the WuKongIM service might fail to start after an upgrade. It includes checking logs, verifying executable permissions, and inspecting configuration files. ```bash # Check logs tail -f ./wukongim_data/logs/wukongim.log # Check if executable has proper permissions ls -la wukongim # Verify configuration file cat wk.yaml ``` -------------------------------- ### Install Prometheus on Ubuntu/Debian Source: https://docs.githubim.com/en/installation/linux/monitoring Installs Prometheus on Ubuntu/Debian systems by downloading the binary, extracting it, creating necessary user and directories, and copying binaries to the system's PATH. Requires root privileges for certain operations. ```bash # Download Prometheus wget https://github.com/prometheus/prometheus/releases/download/v2.45.0/prometheus-2.45.0.linux-amd64.tar.gz # Extract tar xvfz prometheus-2.45.0.linux-amd64.tar.gz cd prometheus-2.45.0.linux-amd64 # Create user and directories sudo useradd --no-create-home --shell /bin/false prometheus sudo mkdir /etc/prometheus sudo mkdir /var/lib/prometheus sudo chown prometheus:prometheus /etc/prometheus sudo chown prometheus:prometheus /var/lib/prometheus # Copy binaries sudo cp prometheus /usr/local/bin/ sudo cp promtool /usr/local/bin/ sudo chown prometheus:prometheus /usr/local/bin/prometheus sudo chown prometheus:prometheus /usr/local/bin/promtool ``` -------------------------------- ### Create Installation Directory Bash Command Source: https://docs.githubim.com/en/installation/docker/scaling This bash command creates a new directory named 'wukongim' in the user's home directory, which will be used to store WuKongIM installation files. ```bash mkdir ~/wukongim ``` -------------------------------- ### Install WuKongIM Flutter EasySDK Dependency Source: https://docs.githubim.com/en/sdk/easy/flutter/getting-started Add the WuKongIM Flutter EasySDK dependency to your project's pubspec.yaml file and then run flutter pub get to install it. Ensure you are using Flutter 3.0.0 or higher and Dart 2.17.0 or higher. ```yaml dependencies: flutter: sdk: flutter wukong_easy_sdk: ^1.0.0 ``` -------------------------------- ### Import WuKongIM SDK via CDN Source: https://docs.githubim.com/en/sdk/wukongim/javascript/intro This snippet shows how to include the WuKongIM JavaScript SDK in your project using a Content Delivery Network (CDN). This is a simple way to get started without module bundlers. ```html ``` -------------------------------- ### Install WuKongIM Flutter SDK Source: https://docs.githubim.com/en/sdk/wukongim/flutter/integration Add the WuKongIM Flutter SDK as a dependency in your project's pubspec.yaml file. Ensure you use the latest version available. ```yaml dependencies: wukongimfluttersdk: ^version # Check version number above ``` -------------------------------- ### Setup WuKongIM for Development and Production Source: https://docs.githubim.com/en/sdk/wukongim/flutter/integration Implement environment-specific configurations for the WuKongIM SDK. This involves setting debug mode, server addresses, and log levels differently for development and production environments. ```dart class EnvironmentConfig { static void setupForEnvironment() { if (kDebugMode) { // Development environment _setupDevelopment(); } else { // Production environment _setupProduction(); } } static void _setupDevelopment() { WKIM.shared.setDebugMode(true); WKIM.shared.connectionManager.setServerAddress('dev-server.com', 5100); WKIM.shared.setLogLevel(WKLogLevel.debug); } static void _setupProduction() { WKIM.shared.setDebugMode(false); WKIM.shared.connectionManager.setServerAddress('prod-server.com', 5100); WKIM.shared.setLogLevel(WKLogLevel.error); } } ``` -------------------------------- ### React Integration for WuKongIM SDK Source: https://docs.githubim.com/en/sdk/wukongim/javascript/integration Integrate the WuKongIM JavaScript SDK into a React application. This example shows how to initialize the SDK, listen for connection and message events, and manage the connection state within a React component. ```jsx import React, { useEffect, useState } from 'react'; import WKSDK from 'wukongimjssdk'; function ChatApp() { const [sdk, setSdk] = useState(null); const [connected, setConnected] = useState(false); useEffect(() => { const sdkInstance = WKSDK.shared(); // Configure SDK sdkInstance.config({ addr: "ws://your-server.com:5200", uid: "user123", token: "user-auth-token" }); // Listen for connection events sdkInstance.connectionManager.addConnectStatusListener((status) => { setConnected(status === 'connected'); }); // Listen for messages sdkInstance.chatManager.addMessageListener((message) => { console.log('New message:', message); }); setSdk(sdkInstance); // Connect sdkInstance.connectionManager.connect(); // Cleanup return () => { sdkInstance.connectionManager.disconnect(); }; }, []); return (

Chat App

Status: {connected ? 'Connected' : 'Disconnected'}

); } ``` -------------------------------- ### Quick Start: Initialize, Configure, and Send Message with WuKongIM SDK Source: https://docs.githubim.com/en/sdk/wukongim/javascript/intro This example demonstrates the basic usage of the WuKongIM JavaScript SDK. It covers initializing the SDK, configuring connection parameters, setting up a message listener, connecting to the server, and sending a chat message. ```javascript // Initialize SDK const sdk = WKSDK.shared(); // Configure connection sdk.config({ addr: "ws://your-server.com:5200", apiURL: "http://your-api-server.com", uid: "user123", token: "user-token" }); // Listen for messages sdk.chatManager.addMessageListener((message) => { console.log('New message:', message); }); // Connect to server await sdk.connectionManager.connect(); // Send message await sdk.chatManager.send({ channel_id: "friend_user_id", channel_type: 1, content: "Hello from JavaScript SDK!" }); ``` -------------------------------- ### Create New Plugin Project (Bash & Go) Source: https://docs.githubim.com/en/getting-started/learning/plugin-development These commands set up a new directory for your WuKongIM plugin, initialize a Go module, and fetch the necessary WuKongIM plugin development library (go-pdk). Ensure you are in the desired parent directory before running. ```bash mkdir my-plugin cd my-plugin go mod init my-plugin go get github.com/WuKongIM/go-pdk ``` -------------------------------- ### Configure and Start Prometheus Service Source: https://docs.githubim.com/en/installation/linux/monitoring This section details how to create a systemd service file for Prometheus, enabling it to run as a background service. It specifies the user, group, and executable path, along with configuration and storage directories. After creating the service file, it guides through enabling and starting the Prometheus service, followed by a status check. ```bash sudo nano /etc/systemd/system/prometheus.service ``` ```ini [Unit] Description=Prometheus Wants=network-online.target After=network-online.target [Service] User=prometheus Group=prometheus Type=simple ExecStart=/usr/local/bin/prometheus \ --config.file /etc/prometheus/prometheus.yml \ --storage.tsdb.path /var/lib/prometheus/ \ --web.console.templates=/etc/prometheus/consoles \ --web.console.libraries=/etc/prometheus/console_libraries \ --web.listen-address=0.0.0.0:9090 \ --web.external-url= [Install] WantedBy=multi-user.target ``` ```bash sudo systemctl daemon-reload sudo systemctl enable prometheus sudo systemctl start prometheus sudo systemctl status prometheus ``` -------------------------------- ### Install WuKongIM Web EasySDK using npm, yarn, or CDN Source: https://docs.githubim.com/en/sdk/easy/javascript/getting-started Provides commands and script tags for installing the WuKongIM Web EasySDK. Choose the method that best suits your project's package management system. Ensure you are using a supported modern browser. ```bash npm install easyjssdk ``` ```bash yarn add easyjssdk ``` ```html ``` -------------------------------- ### Get IM Address using Python Source: https://docs.githubim.com/en/api/route/get-address Example of how to retrieve the IM connection address using the Python requests library. This demonstrates making a GET request and handling the JSON response. ```python import requests response = requests.get('http://localhost:5001/route', params={'intranet': 0}) data = response.json() print(data) ``` -------------------------------- ### Get Channel Whitelist using Go HTTP Client Source: https://docs.githubim.com/en/api/channel/get-whitelist Illustrates how to get the channel whitelist using Go's built-in `net/http` package. This example constructs the full URL with query parameters and makes a GET request, then decodes the JSON response into a string slice. ```go package main import ( "encoding/json" "fmt" "net/http" "net/url" ) func main() { baseURL := "http://localhost:5001/channel/whitelist" params := url.Values{} params.Add("channel_id", "group123") params.Add("channel_type", "2") fullURL := baseURL + "?" + params.Encode() resp, err := http.Get(fullURL) if err != nil { panic(err) } defer resp.Body.Close() var result []string json.NewDecoder(resp.Body).Decode(&result) fmt.Printf("%+v\n", result) } ``` -------------------------------- ### Initialize WuKongIM iOS EasySDK Source: https://docs.githubim.com/en/sdk/easy/ios/getting-started Demonstrates the initialization of the WuKongEasySDK with configuration details including the server URL, user ID, and authentication token. This is a prerequisite for establishing a connection and using SDK functionalities. ```swift // 1. Initialize SDK let config = WuKongConfig( serverUrl: "ws://your-wukongim-server.com:5200", uid: "your_user_id", // Your user ID token: "your_auth_token" // Your authentication token // deviceId: "optional_device_id", // Optional: Device ID // deviceFlag: .APP // Optional: Device flag, default is .APP ) let easySDK = WuKongEasySDK(config: config) ``` -------------------------------- ### Initialize, Connect, and Send Message (Web/JavaScript) Source: https://docs.githubim.com/en/sdk/easy/overview Demonstrates the basic integration steps for WuKongEasySDK in a Web/JavaScript environment. This includes initializing the SDK with server details and authentication, setting up an event listener for incoming messages, connecting to the server, and sending a message to another user. Dependencies include the 'easyjssdk' library. ```javascript import { WKIM, WKIMChannelType, WKIMEvent } from 'easyjssdk'; // 1. Initialize SDK const im = WKIM.init("ws://your-server.com:5200", { uid: "your_user_id", token: "your_auth_token" }); // 2. Listen for messages im.on(WKIMEvent.Message, (message) => { console.log("New message received:", message); }); // 3. Connect to server await im.connect(); // 4. Send message const result = await im.send("friend_user_id", WKIMChannelType.Person, { type: 1, content: "Hello from Web!" }); ``` -------------------------------- ### Start WuKongIM Service Source: https://docs.githubim.com/en/installation/linux/multi-node This command starts the WuKongIM service in detached mode. It requires a configuration file specified by the --config flag. ```bash ./wukongim --config wk.yaml -d ``` -------------------------------- ### Get Migration Result Status (Go) Source: https://docs.githubim.com/en/api/system/migrate This Go example shows how to retrieve the migration result status using the `net/http` package. It performs a GET request, decodes the JSON response into a map, and prints the migration details. ```go package main import ( "encoding/json" "fmt" "net/http" ) func main() { resp, err := http.Get("http://localhost:5001/migrate/result") 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) } ``` -------------------------------- ### Get Migration Result Status (JavaScript) Source: https://docs.githubim.com/en/api/system/migrate This JavaScript example demonstrates fetching the migration result status using the `fetch` API. It makes a GET request to the endpoint and parses the JSON response to log the migration data. ```javascript const response = await fetch('http://localhost:5001/migrate/result'); const data = await response.json(); console.log(data); ``` -------------------------------- ### Initialize WuKongIM Android EasySDK Source: https://docs.githubim.com/en/sdk/easy/android/getting-started Initialize the WuKongIM Android EasySDK with a configuration object. This involves setting the server URL, user ID, and authentication token. The SDK instance is obtained using a singleton pattern. ```kotlin // 1. Initialize SDK val config = WuKongConfig.Builder() .serverUrl("ws://your-wukongim-server.com:5200") .uid("your_user_id") // Your user ID .token("your_auth_token") // Your authentication token // .deviceId("optional_device_id") // Optional: Device ID // .deviceFlag(WuKongDeviceFlag.APP) // Optional: Device flag, default is APP .build() val easySDK = WuKongEasySDK.getInstance() easySDK.init(this, config) // this is Application or Activity context ``` -------------------------------- ### Install WuKongIM JavaScript SDK via NPM Source: https://docs.githubim.com/en/sdk/wukongim/javascript/intro This command installs the WuKongIM JavaScript SDK using the Node Package Manager (NPM). Ensure you have Node.js and NPM installed on your system before running this command. This is the primary method for integrating the SDK into your project. ```bash npm install wukongim-js-sdk ``` -------------------------------- ### Get Channel Whitelist using cURL Source: https://docs.githubim.com/en/api/channel/get-whitelist Example of how to fetch the channel whitelist using cURL. This command-line tool is useful for testing API endpoints directly from the terminal. It sends a GET request to the specified URL with the required query parameters. ```bash curl -X GET "http://localhost:5001/channel/whitelist?channel_id=group123&channel_type=2" ``` -------------------------------- ### Starting WuKongIM Cluster Nodes Source: https://docs.githubim.com/en/server/configuration/cluster Command-line instructions to initiate each WuKongIM cluster node using its respective configuration file. This process involves running the `wukongim` executable with the `--config` flag pointing to the node's YAML configuration. ```bash # Start on node 1 ./wukongim --config wk-node1.yaml # Start on node 2 ./wukongim --config wk-node2.yaml # Start on node 3 ./wukongim --config wk-node3.yaml ``` -------------------------------- ### Get IM Address using cURL Source: https://docs.githubim.com/en/api/route/get-address Example of how to retrieve the IM connection address using cURL. This command fetches the external network address by default. ```bash curl -X GET "http://localhost:5001/route?intranet=0" ``` -------------------------------- ### Start WuKongIM Service Source: https://docs.githubim.com/en/installation/linux/scaling This command starts the WuKongIM service in detached mode using the specified configuration file. The `-d` flag ensures the process runs in the background. ```bash ./wukongim --config wk.yaml -d ``` -------------------------------- ### Get Channel Whitelist using Python Requests Source: https://docs.githubim.com/en/api/channel/get-whitelist Provides a Python example for retrieving the channel whitelist using the `requests` library. This library simplifies making HTTP requests in Python. The code sets up parameters and sends a GET request, then parses the JSON response. ```python import requests params = { 'channel_id': 'group123', 'channel_type': 2 } response = requests.get('http://localhost:5001/channel/whitelist', params=params) data = response.json() print(data) ``` -------------------------------- ### EasySDK Initialization Across Platforms Source: https://docs.githubim.com/en/getting-started/concepts/device Code examples for initializing the EasySDK for WuKongIM across different platforms: Web (JavaScript), iOS (Swift), Android (Kotlin), and Flutter (Dart). These examples demonstrate setting up the SDK with server details, user credentials, and optionally a custom device ID, with automatic device type detection. ```javascript import { WKIM } from 'easyjssdk'; // Device type is automatically set to Web (1) during initialization const im = WKIM.init("ws://your-server.com:5200", { uid: "user123", token: "your_token", deviceId: "web_device_001" // Optional: custom device ID }); // EasySDK automatically handles device type, Web platform defaults to device type 1 console.log('Current platform: Web'); console.log('Device type: 1 (Web)'); ``` ```swift import WuKongEasySDK // Device type is automatically set to APP (0) during initialization let config = WuKongConfig( serverUrl: "ws://your-server.com:5200", uid: "user123", token: "your_token", deviceId: "ios_device_001" // Optional: custom device ID ) let easySDK = WuKongEasySDK(config: config) // EasySDK automatically handles device type, iOS platform defaults to device type 0 (APP) print("Current platform: APP") print("Device type: 0 (APP)") ``` ```kotlin import com.githubim.easysdk.WuKongEasySDK import com.githubim.easysdk.WuKongConfig // Device type is automatically set to APP (0) during initialization val config = WuKongConfig.Builder() .serverUrl("ws://your-server.com:5200") .uid("user123") .token("your_token") .deviceId("android_device_001") // Optional: custom device ID .build() val easySDK = WuKongEasySDK.getInstance() easySDK.init(this, config) // EasySDK automatically handles device type, Android platform defaults to device type 0 Log.d("WuKong", "Current platform: APP") Log.d("WuKong", "Device type: 0 (APP)") ``` ```dart import 'package:wukong_easy_sdk/wukong_easy_sdk.dart'; // Device type is automatically set during initialization final config = WuKongConfig( serverUrl: "ws://your-server.com:5200", uid: "user123", token: "your_token", deviceId: "flutter_device_001", // Optional: custom device ID ); final easySDK = WuKongEasySDK.getInstance(); await easySDK.init(config); // EasySDK automatically handles device type print('Current platform: Flutter'); print('Device type: Auto-detected'); ``` -------------------------------- ### Get Connection Info with JavaScript Source: https://docs.githubim.com/en/api/monitoring/connections This example shows how to retrieve server connection statistics using JavaScript's fetch API. It makes a GET request to the /connz endpoint with specified query parameters and parses the JSON response. Ensure the environment supports async/await. ```javascript const response = await fetch('http://localhost:5001/connz?offset=0&limit=50&subs=1'); const data = await response.json(); console.log(data); ``` -------------------------------- ### Install Grafana Source: https://docs.githubim.com/en/installation/linux/monitoring These bash commands outline the process for installing Grafana on a Debian-based system (like Ubuntu). It involves adding the Grafana package repository, importing the GPG key for verification, updating the package list, and finally installing the Grafana package itself. ```bash # Add Grafana repository sudo apt-get install -y software-properties-common sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main" wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add - # Install Grafana sudo apt-get update sudo apt-get install grafana ``` -------------------------------- ### Initialize WuKongIM Web EasySDK with Server and Auth Details Source: https://docs.githubim.com/en/sdk/easy/javascript/getting-started Initializes the WuKongIM SDK by providing the server WebSocket address and authentication credentials (user ID and token). Optional parameters like device ID and device flag can also be configured. ```javascript // 1. Initialize SDK const im = WKIM.init("ws://your-wukongim-server.com:5200", { uid: "your_user_id", // Your user ID token: "your_auth_token" // Your authentication token // deviceId: "optional_device_id", // Optional: Device ID // deviceFlag: 2 // Optional: Device flag (1:APP, 2:WEB, default is 2) }); ``` -------------------------------- ### Initialize WuKongIM iOS SDK (With Options) Source: https://docs.githubim.com/en/sdk/wukongim/ios/integration Configure and initialize the WuKongIM SDK with custom options such as connection address, API URL, and upload URL. ```swift // Swift let options = WKOptions() options.connectAddr = "ws://your-server.com:5200" options.apiURL = "http://your-api-server.com" options.uploadURL = "http://your-upload-server.com" WKSDK.shared.setup(options: options) ``` ```objc // Objective-C WKOptions *options = [[WKOptions alloc] init]; options.connectAddr = @"ws://your-server.com:5200"; options.apiURL = @"http://your-api-server.com"; options.uploadURL = @"http://your-upload-server.com"; [WKSDK.shared setupWithOptions:options]; ``` -------------------------------- ### Logging in WuKongIM Plugin SDK Source: https://docs.githubim.com/en/getting-started/learning/plugin-development Demonstrates how to use the `pdk.Log` object for logging messages at different levels (Info, Warn, Error) within a WuKongIM plugin. It shows how to include key-value pairs for structured logging. ```go pdk.Log.Info("Info message", pdk.String("key", "value")) pdk.Log.Warn("Warning message", pdk.Int("count", 10)) pdk.Log.Error("Error message", pdk.Any("data", obj)) ``` -------------------------------- ### Connect to Server using WKIM SDK (JavaScript) Source: https://docs.githubim.com/en/sdk/easy/javascript/getting-started This snippet shows the asynchronous process of connecting to the server using the 'connect' method provided by the WKIM SDK. It includes basic error handling using a try-catch block to log success or failure messages to the console. This is a fundamental step after initializing the SDK. ```javascript // 4. Connect to server try { await im.connect(); console.log("Connection successful!"); } catch (error) { console.error("Connection failed:", error); } ``` -------------------------------- ### Get Channel Max Message Sequence - Bash cURL Source: https://docs.githubim.com/en/api/message/max-message-seq Example of fetching the maximum message sequence for a channel using cURL. It requires channel ID and channel type as query parameters. ```bash curl -X GET "http://localhost:5001/channel/max_message_seq?channel_id=group123&channel_type=2" ``` -------------------------------- ### Install TypeScript Definitions for WuKongIM SDK Source: https://docs.githubim.com/en/sdk/wukongim/javascript/integration If using TypeScript, install the corresponding type definitions package to enable type checking and autocompletion for the SDK. This improves developer experience and code safety. ```bash npm install --save-dev @types/wukongimjssdk ``` -------------------------------- ### Initialize and Connect WuKongIM in HarmonyOS App Source: https://docs.githubim.com/en/sdk/wukongim/harmonyos/integration This TypeScript code demonstrates the initialization of the WuKongIM SDK, including setting up user options, configuring the server address, and establishing a connection. It also includes listeners for connection status and new messages. ```typescript import { WKIM, WKOptions, WKConnectStatus, WKMsg } from '@wukong/wkim'; @Entry @Component struct WuKongIMApp { @State private isInitialized: boolean = false; @State private connectionStatus: string = 'Initializing...'; @State private messages: WKMsg[] = []; aboutToAppear(): void { this.initializeApp(); } aboutToDisappear(): void { this.cleanup(); } private async initializeApp(): Promise { try { await this.initializeWuKongIM(); this.setupGlobalListeners(); this.connectToServer(); this.isInitialized = true; } catch (error) { console.error('Failed to initialize app:', error); this.connectionStatus = 'Initialization Failed'; } } private async initializeWuKongIM(): Promise { const options = new WKOptions(); options.uid = await this.getUserId(); options.token = await this.getAuthToken(); options.debugMode = true; await WKIM.shared.setup(options); // Configure server WKIM.shared.connectionManager().setServerAddress( this.getServerAddress(), this.getServerPort() ); } private setupGlobalListeners(): void { // Connection status listener WKIM.shared.connectionManager().addConnectStatusListener((status, reasonCode, connInfo) => { this.handleConnectionStatus(status, reasonCode, connInfo); }); // Global message listener WKIM.shared.messageManager().addNewMsgListener((msgs) => { this.handleNewMessages(msgs); }); // Conversation update listener WKIM.shared.conversationManager().addRefreshMsgListener((conversation, isEnd) => { if (isEnd) { this.handleConversationUpdate(conversation); } }); } private handleConnectionStatus(status: number, reasonCode?: number, connInfo?: any): void { switch (status) { case WKConnectStatus.success: this.connectionStatus = 'Connected'; break; case WKConnectStatus.connecting: this.connectionStatus = 'Connecting...'; break; case WKConnectStatus.disconnect: this.connectionStatus = 'Disconnected'; break; case WKConnectStatus.kicked: this.connectionStatus = 'Kicked Offline'; this.handleKickedOffline(); break; case WKConnectStatus.fail: this.connectionStatus = 'Connection Failed'; break; case WKConnectStatus.syncMsg: this.connectionStatus = 'Syncing...'; break; case WKConnectStatus.syncCompleted: this.connectionStatus = 'Connected'; break; } } private handleNewMessages(messages: WKMsg[]): void { this.messages = [...this.messages, ...messages]; // Show notifications, update badges, etc. } private handleConversationUpdate(conversation: any): void { // Update conversation list, unread counts, etc. } private handleKickedOffline(): void { // Handle being kicked offline console.log('User kicked offline, clearing session...'); } private connectToServer(): void { WKIM.shared.connectionManager().connection(); } private cleanup(): void { // Remove all listeners WKIM.shared.connectionManager().removeConnectStatusListener(); WKIM.shared.messageManager().removeNewMsgListener(); WKIM.shared.conversationManager().removeRefreshMsgListener(); } // Helper methods private async getUserId(): Promise { // Get from secure storage or user preferences return 'user123'; } private async getAuthToken(): Promise { // Get from secure storage return 'auth_token_here'; } private getServerAddress(): string { return 'your-server.com'; } private getServerPort(): number { return 5100; } build() { Column() { if (this.isInitialized) { Text('WuKongIM HarmonyOS') .fontSize(24) .fontWeight(FontWeight.Bold) .margin({ bottom: 20 }) Text(`Status: ${this.connectionStatus}`) .fontSize(16) .margin({ bottom: 20 }) Text(`Messages: ${this.messages.length}`) .fontSize(14) .margin({ bottom: 20 }) Button('Go to Chat') .onClick(() => { // Navigate to chat page }) } else { Text('Initializing WuKongIM...') .fontSize(18) } } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .padding(20) } } ``` -------------------------------- ### Build WuKongIM Plugin using Go Source: https://docs.githubim.com/en/getting-started/learning/plugin-development Command to compile a Go program into a plugin shared object (`.so`) file. This is the primary step for packaging a plugin for deployment. ```bash go build -buildmode=plugin -o ai_example.so main.go ``` -------------------------------- ### Get IM Address using Go Source: https://docs.githubim.com/en/api/route/get-address Example of how to retrieve the IM connection address using Go's net/http package. This code fetches the external network address and decodes the JSON response. ```go package main import ( "encoding/json" "fmt" "net/http" ) func main() { resp, err := http.Get("http://localhost:5001/route?intranet=0") 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) } ``` -------------------------------- ### Import WuKongIM Web EasySDK using ES6, CommonJS, or CDN Source: https://docs.githubim.com/en/sdk/easy/javascript/getting-started Demonstrates how to import the necessary components (WKIM, WKIMChannelType, WKIMEvent) from the WuKongIM Web EasySDK. The method of import depends on your module system or if you are using the SDK via a CDN. ```javascript import { WKIM, WKIMChannelType, WKIMEvent } from 'easyjssdk'; ``` ```javascript const { WKIM, WKIMChannelType, WKIMEvent } = require('easyjssdk'); ``` ```javascript const { WKIM, WKIMChannelType, WKIMEvent } = window.EasyJSSDK; ``` -------------------------------- ### Get Connection Info with cURL Source: https://docs.githubim.com/en/api/monitoring/connections This example demonstrates how to fetch current server connection statistics using a cURL command. It utilizes query parameters for pagination and to include subscription information. The output is typically in JSON format. ```bash curl -X GET "http://localhost:5001/connz?offset=0&limit=50&subs=1" ``` -------------------------------- ### Connect to Server using Swift Source: https://docs.githubim.com/en/sdk/easy/ios/getting-started Shows how to establish a connection to the server using the `connect()` method within a Task. It includes basic error handling for connection failures. This function is asynchronous and requires Swift 5.5+ for Task/await. ```swift // 4. Connect to server Task { do { try await easySDK.connect() print("Connection successful!") } catch { print("Connection failed:", error) } } ``` -------------------------------- ### Install EasySDK for Web/JavaScript Source: https://docs.githubim.com/en/sdk/source-code Installs the EasySDK JavaScript package using npm. This is the first step for integrating EasySDK into web applications. ```bash # JavaScript/Web npm install @wukongim/easysdk-js ``` -------------------------------- ### JavaScript Time Range Search Example Source: https://docs.githubim.com/en/api/message/user-search An example of performing a time range search using JavaScript. This code snippet shows how to construct a search query object that includes user ID, content payload, start and end timestamps, and a limit for the results. ```javascript const timeRangeSearch = { uid: "user123", payload: { content: "project" }, start_time: 1640995200, // 2022-01-01 end_time: 1672531200, // 2023-01-01 limit: 20 }; ``` -------------------------------- ### WuKongIM Health Check Request Examples Source: https://docs.githubim.com/en/api/system/health Demonstrates how to check the health status of the WuKongIM server using cURL, JavaScript, Python, and Go. These examples show making a GET request to the /health endpoint and processing the JSON response. ```bash curl -X GET "http://localhost:5001/health" ``` ```javascript const response = await fetch('http://localhost:5001/health'); const data = await response.json(); console.log(data); ``` ```python import requests response = requests.get('http://localhost:5001/health') data = response.json() print(data) ``` ```go package main import ( "fmt" "io" "net/http" ) func main() { resp, err := http.Get("http://localhost:5001/health") if err != nil { panic(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(body)) } ``` -------------------------------- ### Install WuKongIM Android EasySDK via Gradle Source: https://docs.githubim.com/en/sdk/easy/android/getting-started Add the WuKongIM Android EasySDK dependency to your app's build.gradle file using the Gradle build system. This is the recommended method for integration. ```kotlin dependencies { implementation 'com.githubim:easysdk-android:1.0.0' } ``` -------------------------------- ### Get Channel Max Message Sequence - Go HTTP Client Source: https://docs.githubim.com/en/api/message/max-message-seq Example of fetching the maximum message sequence for a channel using Go's standard HTTP client. The JSON response is decoded into a map. ```go package main import ( "encoding/json" "fmt" "net/http" ) func main() { resp, err := http.Get("http://localhost:5001/channel/max_message_seq?channel_id=group123&channel_type=2") 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) } ``` -------------------------------- ### Install WuKongIM iOS EasySDK with CocoaPods Source: https://docs.githubim.com/en/sdk/easy/ios/getting-started This snippet shows how to add the WuKongIM iOS EasySDK to your project's Podfile for installation using CocoaPods. Ensure you run `pod install` after updating the Podfile. ```ruby pod 'WuKongEasySDK', '~> 1.0.0' ``` -------------------------------- ### Reminder Management Class Example (Dart) Source: https://docs.githubim.com/en/sdk/wukongim/flutter/reminder Provides a comprehensive example of a `ReminderManager` class in Dart, demonstrating various functionalities for managing reminders. This includes getting channel reminders, retrieving all pending reminders, filtering reminders by type (@mention, join request, system notice, unread voice), counting reminders, and checking for unread reminders. It also includes a utility to get display text for reminders. ```dart class ReminderManager { // Get reminders for specific channel static List getChannelReminders(String channelId, int channelType) { try { final reminders = WKIM.shared.reminderManager.getWithChannel(channelId, channelType); print('Retrieved ${reminders.length} reminders'); return reminders; } catch (error) { print('Failed to get reminders: $error'); return []; } } // Get all pending reminders static List getAllPendingReminders() { // Here we need to iterate through all channels to get reminders // Actual implementation may need SDK to provide corresponding API final List allReminders = []; // Example: Get reminders for all conversations final conversations = WKIM.shared.conversationManager.getAll(); for (final conv in conversations) { final reminders = getChannelReminders(conv.channelID, conv.channelType); final pendingReminders = reminders.where((r) => r.done == 0).toList(); allReminders.addAll(pendingReminders); } return allReminders; } // Get reminders by type static List getRemindersByType(String channelId, int channelType, int type) { final allReminders = getChannelReminders(channelId, channelType); return allReminders.where((reminder) => reminder.type == type).toList(); } // Get @mention reminders static List getMentionReminders(String channelId, int channelType) { return getRemindersByType(channelId, channelType, ReminderType.mention); } // Get join request reminders static List getJoinRequestReminders(String channelId, int channelType) { return getRemindersByType(channelId, channelType, ReminderType.joinRequest); } // Get system notice reminders static List getSystemNoticeReminders(String channelId, int channelType) { return getRemindersByType(channelId, channelType, ReminderType.systemNotice); } // Get unread voice reminders static List getUnreadVoiceReminders(String channelId, int channelType) { return getRemindersByType(channelId, channelType, ReminderType.unreadVoice); } // Count total reminders static int getTotalReminderCount() { final allReminders = getAllPendingReminders(); return allReminders.length; } // Count reminders by type static Map getReminderCountByType() { final allReminders = getAllPendingReminders(); final Map countMap = {}; for (final reminder in allReminders) { countMap[reminder.type] = (countMap[reminder.type] ?? 0) + 1; } return countMap; } // Check if has unread reminders static bool hasUnreadReminders(String channelId, int channelType) { final reminders = getChannelReminders(channelId, channelType); return reminders.any((reminder) => reminder.done == 0); } // Get reminder display text static String getReminderDisplayText(WKReminder reminder) { if (reminder.text.isNotEmpty) { return reminder.text; } // Return default text based on type switch (reminder.type) { case ReminderType.mention: return 'Someone mentioned me'; case ReminderType.joinRequest: return 'Join request'; case ReminderType.systemNotice: return 'System notice'; case ReminderType.unreadVoice: return 'Unread voice'; default: return 'New reminder'; } } } // Reminder type constants class ReminderType { static const int mention = 1; // @mention static const int joinRequest = 2; // Join request static const int systemNotice = 3; // System notice static const int unreadVoice = 4; // Unread voice static const int custom = 99; // Custom reminder } ```