### Webhook Event Receiver Setup (Python/Flask) Source: https://context7.com/kaiheila/api-docs/llms.txt Sets up a basic Flask application to receive webhook events from Kaiheila. This example includes necessary imports for request handling, security, and data processing, and requires libraries like Flask and PyCryptodome. ```python from flask import Flask, request, jsonify import hashlib import json import base64 import zlib from Crypto.Cipher import AES from Crypto.Util.Padding import unpad app = Flask(__name__) ``` -------------------------------- ### WebSocket Resume Connection URL Example Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/websocket.md This example demonstrates how to construct a WebSocket connection URL for resuming a session. It includes parameters like `compress/token`, `resume`, `sn` (sequence number of the last processed message), and `session_id` for re-establishing a connection and synchronizing offline messages. ```url wss://test.kookapp.com:8888/gateway?{compress/token parameters}&resume=1&sn=5&session_id=20****ae-1fa4-4d19-805f-6f0f****d534 ``` -------------------------------- ### Webhook Event Handling (Python) Source: https://context7.com/kaiheila/api-docs/llms.txt Setup for receiving webhook events using Flask. ```APIDOC ## Webhook Event Handling (Python) ### Description Configure a Flask application to receive event pushes via Webhook, as an alternative to WebSocket connections. ### Setup Requires Flask and cryptographic libraries for decryption. ### Request Example (Python) ```python from flask import Flask, request, jsonify import hashlib import json import base64 import zlib from Crypto.Cipher import AES from Crypto.Util.Padding import unpad app = Flask(__name__) # Add your webhook event handling logic here @app.route('/webhook', methods=['POST']) def handle_webhook(): # Process incoming event data return jsonify({"message": "Event received"}) if __name__ == '__main__': app.run(port=5000) ``` ``` -------------------------------- ### Get Server Details and Members using Python Source: https://context7.com/kaiheila/api-docs/llms.txt Demonstrates how to retrieve detailed information about a server and its members using the Kaiheila API in Python. It shows how to fetch server name, user count, and individual member usernames and identifiers. Requires a manager object initialized with appropriate credentials. ```python guild_detail = manager.get_guild_detail('guild_id') print(f"服务器名称: {guild_detail['data']['name']}") print(f"成员数量: {guild_detail['data']['user_count']}") members = manager.get_guild_members('guild_id') for member in members['data']['items']: print(f"成员: {member['username']}#{member['identify_num']}") result = manager.update_nickname('guild_id', '管理助手') print('昵称修改结果:', result) ``` -------------------------------- ### Exchange OAuth2 Token using curl Source: https://context7.com/kaiheila/api-docs/llms.txt This example shows how to exchange an authorization code for an access token using `curl`. It requires your client ID, client secret, the authorization code, and redirect URI. The response includes the access token, its expiration time, and granted scopes. ```bash # 使用 curl 直接交换令牌 curl -X POST https://www.kookapp.cn/api/oauth2/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=authorization_code" \ -d "client_id=YOUR_CLIENT_ID" \ -d "client_secret=YOUR_CLIENT_SECRET" \ -d "code=AUTHORIZATION_CODE" \ -d "redirect_uri=https://yourdomain.com/callback" # 响应示例 { "access_token": "7d3012xxxxxxxxxxxxxxdc8f1", "expires_in": 2678400, "token_type": "Bearer", "scope": "get_user_info get_user_guilds" } ``` -------------------------------- ### Implement OAuth2 Authorization Code Flow in Node.js Source: https://context7.com/kaiheila/api-docs/llms.txt This Node.js Express example demonstrates the OAuth2 authorization code flow to obtain user access tokens. It handles user redirection for authorization, callback processing, token exchange, and fetching user information. Dependencies include `express` and `axios`. ```javascript const express = require('express'); const axios = require('axios'); const app = express(); const config = { client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', redirect_uri: 'https://yourdomain.com/oauth/callback' }; // 步骤 1: 引导用户授权 app.get('/oauth/authorize', (req, res) => { const authUrl = 'https://www.kookapp.cn/app/oauth2/authorize?' + new URLSearchParams({ client_id: config.client_id, redirect_uri: config.redirect_uri, response_type: 'code', scope: 'get_user_info get_user_guilds' }); res.redirect(authUrl); }); // 步骤 2: 处理回调并交换令牌 app.get('/oauth/callback', async (req, res) => { const { code } = req.query; if (!code) { return res.status(400).send('授权失败: 缺少 code 参数'); } try { // 交换访问令牌 const tokenResponse = await axios.post( 'https://www.kookapp.cn/api/oauth2/token', new URLSearchParams({ grant_type: 'authorization_code', client_id: config.client_id, client_secret: config.client_secret, code: code, redirect_uri: config.redirect_uri }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ); const { access_token, expires_in, scope } = tokenResponse.data; console.log('访问令牌:', access_token); console.log('有效期:', expires_in, '秒'); console.log('授权范围:', scope); // 步骤 3: 使用访问令牌获取用户信息 const userResponse = await axios.get( 'https://www.kookapp.cn/api/v3/user/me', { headers: { 'Authorization': `Bearer ${access_token}` } } ); const user = userResponse.data.data; res.json({ success: true, user: { id: user.id, username: user.username, avatar: user.avatar, identify_num: user.identify_num } }); } catch (error) { console.error('OAuth 错误:', error.response?.data || error.message); res.status(500).json({ success: false, error: error.response?.data || error.message }); } }); app.listen(3000, () => { console.log('OAuth 服务器运行在 http://localhost:3000'); }); ``` -------------------------------- ### KMarkdown Syntax Examples Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/kmarkdown-card.md Examples of KMarkdown syntax, including standard markdown features like bold, italics, strikethrough, links, and code blocks, as well as custom KMarkdown syntax for underlines, spoilers, emojis, mentions, and more. Custom syntax often follows the pattern (tagName)value(tagName)[attributes]. ```plaintext **加粗文字** *斜体文字* ***加粗斜体*** ~~删除线~~ [链接文字](链接地址) --- > hello world (ins)下划线内容(ins) (spl)剧透(spl) :emoji: (emj)服务器表情名(emj)[服务器表情id] (chn)频道ID(chn) (met)用户id/here/all(met) (rol)角色ID(rol) `行内代码` ```language ``` \特殊字符 ``` -------------------------------- ### Get Authorized User Info with OAuth2 Token (cURL) Source: https://context7.com/kaiheila/api-docs/llms.txt Demonstrates how to fetch authorized user information using an OAuth2 access token via a cURL GET request. Requires a valid OAUTH2_ACCESS_TOKEN. ```bash curl -X GET https://www.kookapp.cn/api/v3/user/me \ -H "Authorization: Bearer OAUTH2_ACCESS_TOKEN" ``` -------------------------------- ### Get Channel Message List (Bash) Source: https://context7.com/kaiheila/api-docs/llms.txt Retrieves a list of messages from a specified channel. Supports fetching recent messages, messages before a reference message, or messages around a reference message. Requires bot token and channel ID. ```bash # 获取频道最新消息 curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&page_size=50" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` ```bash # 查询参考消息之前的消息 curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&msg_id=reference_msg_id&flag=before&page_size=20" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` ```bash # 查询参考消息前后的消息(around 模式) curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&msg_id=reference_msg_id&flag=around&page_size=30" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` -------------------------------- ### Get KOOK User Information (Bash) Source: https://context7.com/kaiheila/api-docs/llms.txt This bash script demonstrates how to retrieve user information from the KOOK API using `curl`. It shows how to fetch the current bot's information and view specific user details within a guild. Requires a valid bot token and user/guild IDs. ```bash # 获取机器人自身信息 curl -X GET https://www.kookapp.cn/api/v3/user/me \ -H "Authorization: Bot YOUR_BOT_TOKEN" # 获取指定用户信息 curl -X GET "https://www.kookapp.cn/api/v3/user/view?user_id=target_user_id&guild_id=guild_id" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` -------------------------------- ### Webhook Configuration and Handling Source: https://context7.com/kaiheila/api-docs/llms.txt This section details the process of setting up a webhook endpoint, verifying incoming requests, and processing event data received from KOOK. ```APIDOC ## POST /webhook ### Description Receives and processes webhook events from KOOK, including challenge verification, signature validation, data decryption/decompression, and event handling. ### Method POST ### Endpoint /webhook ### Parameters #### Headers - **X-Kook-Signature** (string) - Required - The signature of the request for verification. #### Request Body - **challenge** (string) - Optional - Used for initial challenge verification. - **compress** (integer) - Optional - If 1, indicates the data is compressed. - **d** (string) - Optional - The compressed data payload. - **encrypt** (string) - Optional - The encrypted data payload. - **s** (integer) - Required - Status code, 0 indicates an event message. - **d** (object) - Required - The actual event data payload. - **channel_type** (string) - The type of channel (e.g., 'GROUP'). - **type** (integer) - The type of message or event. - **target_id** (string) - The ID of the target channel. - **content** (string) - The message content (for message events). - **extra** (object) - Additional event-specific information. ### Request Example ```json { "s": 0, "d": { "channel_type": "GROUP", "type": 1, "target_id": "channel_id", "author_id": "user_id", "content": "你好", "msg_id": "msg_id", "msg_timestamp": 1607072537177, "nonce": "", "extra": { "type": 1, "guild_id": "guild_id", "channel_name": "频道名", "author": { "id": "user_id", "username": "用户名", "avatar": "avatar_url" } } } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the webhook was processed successfully. #### Error Response (403) - **error** (string) - "Invalid signature" if the signature verification fails. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### GET /api/v3/message/list Source: https://context7.com/kaiheila/api-docs/llms.txt 获取指定频道的消息历史记录,支持相对于参考消息的前后查询模式。 ```APIDOC ## GET /api/v3/message/list ### Description 获取指定频道的消息历史记录,支持相对于参考消息的前后查询模式。 ### Method GET ### Endpoint /api/v3/message/list ### Parameters #### Query Parameters - **target_id** (string) - Required - 频道 ID。 - **page_size** (integer) - Optional - 每页返回的消息数量,默认为 50。 - **msg_id** (string) - Optional - 参考消息 ID,用于前后查询。 - **flag** (string) - Optional - 查询标志: 'before' (之前), 'after' (之后), 'around' (前后)。默认为 'before'。 ### Request Example ```bash # 获取频道最新消息 curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&page_size=50" \ -H "Authorization: Bot YOUR_BOT_TOKEN" # 查询参考消息之前的消息 curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&msg_id=reference_msg_id&flag=before&page_size=20" \ -H "Authorization: Bot YOUR_BOT_TOKEN" # 查询参考消息前后的消息(around 模式) curl -X GET "https://www.kookapp.cn/api/v3/message/list?target_id=channel_id&msg_id=reference_msg_id&flag=around&page_size=30" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` ### Response #### Success Response (200) - **code** (integer) - 操作状态码。 - **message** (string) - 操作信息。 - **data** (object) - 返回数据。 - **items** (array) - 消息列表。 - **id** (string) - 消息 ID。 - **type** (integer) - 消息类型。 - **content** (string) - 消息内容。 - **mention** (array) - 被提及的用户 ID 列表。 - **mention_all** (boolean) - 是否提及所有人。 - **mention_roles** (array) - 被提及的角色 ID 列表。 - **mention_here** (boolean) - 是否提及在线用户。 - **create_at** (integer) - 创建时间戳。 - **updated_at** (integer) - 更新时间戳。 - **reactions** (array) - 消息的反应。 - **author** (object) - 消息作者信息。 - **id** (string) - 用户 ID。 - **username** (string) - 用户名。 - **online** (boolean) - 用户是否在线。 - **avatar** (string) - 用户头像 URL。 - **quote** (object) - 引用的消息信息 (如果存在)。 - **mention_info** (object) - 提及信息。 #### Response Example ```json { "code": 0, "message": "操作成功", "data": { "items": [ { "id": "bac34958-2c73-45c8", "type": 1, "content": "消息内容", "mention": ["user_id"], "mention_all": false, "mention_roles": [], "mention_here": false, "create_at": 1612685332518, "updated_at": 0, "reactions": [ { "emoji": {"id": "[#129315;]", "name": "[#129315;]"}, "count": 1, "me": true } ], "author": { "id": "1780328444", "username": "用户名", "online": false, "avatar": "https://example.com/avatar.jpg" }, "quote": null, "mention_info": { "mention_part": [], "mention_role_part": [] } } ] } } ``` ``` -------------------------------- ### Manage Kaiheila Server Roles with Go Source: https://context7.com/kaiheila/api-docs/llms.txt This Go package provides a client for managing server roles and permissions in Kaiheila. It allows creating, updating, deleting roles, and granting or revoking roles from users. It handles HTTP requests to the Kaiheila API and expects a bot token for authentication. The output of API calls is returned as a map. ```go package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" ) type KOOKRoleManager struct { botToken string baseURL string } func NewRoleManager(botToken string) *KOOKRoleManager { return &KOOKRoleManager{ botToken: botToken, baseURL: "https://www.kookapp.cn/api/v3", } } // 创建角色 func (m *KOOKRoleManager) CreateRole(guildID, name string) (map[string]interface{}, error) { data := map[string]interface{}{ "guild_id": guildID, "name": name, } return m.request("POST", "/guild-role/create", data) } // 更新角色 func (m *KOOKRoleManager) UpdateRole(guildID string, roleID int, updates map[string]interface{}) (map[string]interface{}, error) { data := map[string]interface{}{ "guild_id": guildID, "role_id": roleID, } for k, v := range updates { data[k] = v } return m.request("POST", "/guild-role/update", data) } // 删除角色 func (m *KOOKRoleManager) DeleteRole(guildID string, roleID int) (map[string]interface{}, error) { data := map[string]interface{}{ "guild_id": guildID, "role_id": roleID, } return m.request("POST", "/guild-role/delete", data) } // 赋予用户角色 func (m *KOOKRoleManager) GrantRole(guildID, userID string, roleID int) (map[string]interface{}, error) { data := map[string]interface{}{ "guild_id": guildID, "user_id": userID, "role_id": roleID, } return m.request("POST", "/guild-role/grant", data) } // 撤销用户角色 func (m *KOOKRoleManager) RevokeRole(guildID, userID string, roleID int) (map[string]interface{}, error) { data := map[string]interface{}{ "guild_id": guildID, "user_id": userID, "role_id": roleID, } return m.request("POST", "/guild-role/revoke", data) } // 发送请求 func (m *KOOKRoleManager) request(method, endpoint string, data map[string]interface{}) (map[string]interface{}, error) { jsonData, _ := json.Marshal(data) req, err := http.NewRequest(method, m.baseURL+endpoint, bytes.NewBuffer(jsonData)) if err != nil { return nil, err } req.Header.Set("Authorization", "Bot "+m.botToken) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) return result, nil } // 使用示例 func main() { manager := NewRoleManager("YOUR_BOT_TOKEN") // 创建新角色 role, _ := manager.CreateRole("guild_id", "VIP会员") roleID := int(role["data"].(map[string]interface{})["role_id"].(float64)) fmt.Println("角色已创建, ID:", roleID) // 更新角色属性 updates := map[string]interface{}{ "color": 0xFF5733, // 橙红色 "hoist": 1, // 在成员列表单独显示 "mentionable": 1, // 允许被提及 "permissions": 142924849, // 权限位掩码 } manager.UpdateRole("guild_id", roleID, updates) fmt.Println("角色已更新") // 赋予用户角色 manager.GrantRole("guild_id", "user_id", roleID) fmt.Println("角色已赋予用户") // 撤销用户角色 manager.RevokeRole("guild_id", "user_id", roleID) fmt.Println("角色已撤销") // 删除角色 manager.DeleteRole("guild_id", roleID) fmt.Println("角色已删除") } ``` -------------------------------- ### Webhook Configuration and Challenge Handling Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/webhook.md This section details how to configure your callback URL and handle the initial challenge request sent by KOOK to verify your webhook endpoint. ```APIDOC ## POST /callbackUrl (Challenge Request) ### Description When configuring a webhook or bringing a bot online, KOOK sends a challenge request to verify your callback URL. You must respond with the provided `challenge` value within 1 second. ### Method POST ### Endpoint `YOUR_CALLBACK_URL` ### Request Body KOOK sends a JSON payload with the challenge details. The payload may be compressed using zlib (deflate) unless `compress=0` is appended to the callback URL. #### Challenge Payload Example (Uncompressed) ```json { "s": 0, "d": { "type": 255, "channel_type": "WEBHOOK_CHALLENGE", "challenge" : "bkes654x09XY", "verify_token": "your_verify_token" } } ``` #### Challenge Payload Example (With Encryption Enabled) ```json { "encrypt": "encrypted_challenge_data..." } ``` ### Response #### Success Response (200) Respond with a JSON object containing the `challenge` value received in the request. #### Response Example ```javascript { "challenge": "bkes654x09XY" } ``` ### Notes - Respond within 1 second. - If message encryption is enabled, you will receive an `encrypt` field. Decryption is required before processing the challenge. - The `verify_token` in the request should match your bot's token configured in the developer backend. ``` -------------------------------- ### GET /api/v3/user/me Source: https://context7.com/kaiheila/api-docs/llms.txt Retrieves the authorized user's information using an OAuth2 access token. ```APIDOC ## GET /api/v3/user/me ### Description Retrieves the authorized user's information. ### Method GET ### Endpoint /api/v3/user/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer OAUTH2_ACCESS_TOKEN ### Request Example ```bash curl -X GET https://www.kookapp.cn/api/v3/user/me \ -H "Authorization: Bearer OAUTH2_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **data** (object) - User information object. - **id** (string) - User ID. - **username** (string) - Username. - **online** (boolean) - Online status. #### Response Example ```json { "data": { "id": "12345", "username": "example_user", "online": true } } ``` ``` -------------------------------- ### File Upload API Source: https://context7.com/kaiheila/api-docs/llms.txt Upload images, audio, video, and other files to get a KOOK hosted URL. This endpoint facilitates asset management within the KOOK platform. ```APIDOC ## POST /api/v3/asset/create ### Description Upload images, audio, video, etc., to obtain a KOOK hosted URL. ### Method POST ### Endpoint https://www.kookapp.cn/api/v3/asset/create ### Parameters #### Request Body - **file** (File) - Required - The file to be uploaded. ### Request Example (See JavaScript code examples in the original documentation for detailed usage with different file sources like browser File objects, local paths, or URLs.) ### Response #### Success Response (200) - **code** (integer) - Indicates the success of the operation. - **message** (string) - A message describing the outcome of the operation. - **data** (object) - Contains the URL of the uploaded asset. - **url** (string) - The KOOK hosted URL of the uploaded file. #### Response Example ```json { "code": 0, "message": "操作成功", "data": { "url": "https://img.kookapp.cn/assets/2021-01/xxx.jpg" } } ``` ``` -------------------------------- ### Direct Messaging using Bash (curl) Source: https://context7.com/kaiheila/api-docs/llms.txt Illustrates how to manage direct messages using bash commands with curl. It covers creating a direct message conversation and sending a message, retrieving a list of direct message conversations, and fetching message history for a specific conversation. Requires a bot token and target user/chat IDs. ```bash # 创建私信会话并发送消息 curl -X POST https://www.kookapp.cn/api/v3/direct-message/create \ -H "Authorization: Bot YOUR_BOT_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "type": 9, "target_id": "user_id", "content": "你好!这是一条私信消息" }' # 获取私信会话列表 curl -X GET "https://www.kookapp.cn/api/v3/user-chat/list" \ -H "Authorization: Bot YOUR_BOT_TOKEN" # 获取私信消息历史 curl -X GET "https://www.kookapp.cn/api/v3/direct-message/list?chat_code=chat_code&page=1" \ -H "Authorization: Bot YOUR_BOT_TOKEN" ``` -------------------------------- ### WebSocket Connection and Event Subscription with Python Source: https://context7.com/kaiheila/api-docs/llms.txt This Python code establishes a WebSocket connection to the Kaiheila Gateway to receive real-time events. It includes functions to fetch the gateway URL, handle different event signals (messages, hello, ping, reconnect), and send messages back to channels. The bot automatically attempts to resume sessions if disconnected. Dependencies include `websocket-client`, `json`, `time`, and `requests`. ```python import websocket import json import time import requests # 1. 获取 Gateway 连接地址 def get_gateway_url(bot_token): headers = {'Authorization': f'Bot {bot_token}'} response = requests.get( 'https://www.kookapp.cn/api/v3/gateway/index?compress=0', headers=headers ) return response.json()['data']['url'] # 2. WebSocket 事件处理 class KOOKBot: def __init__(self, bot_token): self.bot_token = bot_token self.session_id = None self.sn = 0 def on_message(self, ws, message): data = json.loads(message) signal = data['s'] # Signal 0: 事件消息 if signal == 0: event_data = data['d'] self.sn = data.get('sn', self.sn) # 处理文字消息 if event_data['channel_type'] == 'GROUP': print(f"收到频道消息: {event_data['content']}") print(f"发送者: {event_data['extra']['author']['username']}") # 回复消息 if event_data['type'] == 1 and '你好' in event_data['content']: self.send_message( event_data['target_id'], f"你好! (met){event_data['author_id']}(met)" ) # Signal 1: HELLO (握手确认) elif signal == 1: self.session_id = data['d']['session_id'] print(f"连接成功! Session ID: {self.session_id}") # Signal 2: PING (心跳) elif signal == 2: print("收到心跳 PING") # Signal 3: PONG (心跳响应) elif signal == 3: print("发送心跳 PONG") ws.send(json.dumps({"s": 2})) # Signal 5: RECONNECT (服务器请求重连) elif signal == 5: print("服务器请求重连") ws.close() self.connect() # Signal 6: RESUME ACK (恢复成功) elif signal == 6: print("会话恢复成功") def on_error(self, ws, error): print(f"WebSocket 错误: {error}") def on_close(self, ws, close_status_code, close_msg): print(f"WebSocket 连接关闭: {close_status_code} - {close_msg}") def on_open(self, ws): print("WebSocket 连接已建立") def send_message(self, channel_id, content): """发送消息到频道""" url = 'https://www.kookapp.cn/api/v3/message/create' headers = { 'Authorization': f'Bot {self.bot_token}', 'Content-Type': 'application/json' } data = { 'type': 9, 'target_id': channel_id, 'content': content } response = requests.post(url, headers=headers, json=data) return response.json() def connect(self): gateway_url = get_gateway_url(self.bot_token) # 如果有 session_id,添加恢复参数 if self.session_id: gateway_url += f"&resume=1&sn={self.sn}&session_id={self.session_id}" ws = websocket.WebSocketApp( gateway_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) ws.run_forever() # 使用示例 if __name__ == '__main__': BOT_TOKEN = 'YOUR_BOT_TOKEN' bot = KOOKBot(BOT_TOKEN) bot.connect() ``` -------------------------------- ### Card Message Structure (JSON) Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/kmarkdown-card.md The basic JSON structure for a Kaiheila Card Message. A card message can contain multiple cards, each with a 'card' type and a list of 'modules'. This example shows the top-level array structure for a message containing one or more cards. ```javascript [ { "type": "card", "modules": [ // ... ], }, // 其它card ]; ``` -------------------------------- ### Server Management APIs Source: https://context7.com/kaiheila/api-docs/llms.txt APIs for managing servers, including fetching server lists, details, and members. Also includes functionality for kicking members and updating nicknames. ```APIDOC ## Server Management APIs ### Description Provides endpoints for bots to manage servers, retrieve server information, manage members, and modify server-specific settings like nicknames. ### Method GET /guild/list GET /guild/view GET /guild/user-list POST /guild/kickout POST /guild/nickname ### Endpoints - `/guild/list`: Retrieves a list of servers the bot is a member of. - `/guild/view`: Fetches detailed information about a specific server, including channels and roles. - `/guild/user-list`: Lists members of a specific server. - `/guild/kickout`: Kicks a specified member from a server. - `/guild/nickname`: Updates a user's nickname within a specific server. ### Parameters #### Guild List (`/guild/list`) - `page` (integer) - Optional - The page number for pagination (default: 1). - `page_size` (integer) - Optional - The number of items per page (default: 100). #### Guild View (`/guild/view`) - `guild_id` (string) - Required - The ID of the server to view. #### Guild User List (`/guild/user-list`) - `guild_id` (string) - Required - The ID of the server. - `page` (integer) - Optional - The page number for pagination (default: 1). - `page_size` (integer) - Optional - The number of members per page (default: 50). #### Kickout Member (`/guild/kickout`) - `guild_id` (string) - Required - The ID of the server. - `target_id` (string) - Required - The ID of the member to kick. #### Update Nickname (`/guild/nickname`) - `guild_id` (string) - Required - The ID of the server. - `nickname` (string) - Required - The new nickname for the user. - `user_id` (string) - Optional - The ID of the user whose nickname to change. If not provided, the bot's nickname is changed. ### Request Example (Get Guild List) ```python import requests headers = { 'Authorization': 'Bot YOUR_BOT_TOKEN', 'Content-Type': 'application/json' } response = requests.get( 'https://www.kookapp.cn/api/v3/guild/list', headers=headers, params={'page': 1, 'page_size': 100} ) print(response.json()) ``` ### Request Example (Kickout Member) ```python import requests headers = { 'Authorization': 'Bot YOUR_BOT_TOKEN', 'Content-Type': 'application/json' } data = { 'guild_id': 'SERVER_ID', 'target_id': 'USER_ID_TO_KICK' } response = requests.post( 'https://www.kookapp.cn/api/v3/guild/kickout', headers=headers, json=data ) print(response.json()) ``` ### Response #### Success Response (e.g., Guild List - 200 OK) - `data` (object) - Response data payload. - `items` (array) - List of guilds. - Each item contains guild information like `id`, `name`, `icon`, etc. #### Response Example (Guild List) ```json { "data": { "total_count": 10, "items": [ { "id": "guild_id_1", "name": "Example Server 1", "icon": "url_to_icon" }, { "id": "guild_id_2", "name": "Example Server 2", "icon": "url_to_icon" } ] } } ``` #### Success Response (e.g., Kickout Member - 200 OK) - `message` (string) - Confirmation message. #### Response Example (Kickout Member) ```json { "message": "success" } ``` ``` -------------------------------- ### KOOK API Authentication with Bot Token Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/intro.md Demonstrates how to authenticate API requests using a bot token. The token must be included in the `Authorization` header with the `Bot` token type. This is crucial for identifying and authorizing bot actions. ```http Authorization: Bot BHsTZ4232tLatgV5AFyjoqZGAHHmpl9mTxYQ/u4/80= ``` -------------------------------- ### Bash cURL 测试 Webhook 接收 Source: https://context7.com/kaiheila/api-docs/llms.txt 这是一个 Bash 脚本,使用 cURL 命令向本地运行的 Flask Webhook 服务器发送一个模拟的 POST 请求。该请求包含了 KOOK Webhook 消息的典型结构,用于测试服务器是否能正确接收和解析数据。 ```bash # 测试 Webhook 接收 curl -X POST http://localhost:5000/webhook \ -H "Content-Type: application/json" \ -H "X-Kook-Signature: signature_here" \ -d '{ "s": 0, "d": { "channel_type": "GROUP", "type": 1, "target_id": "channel_id", "author_id": "user_id", "content": "测试消息", "msg_id": "msg_id", "msg_timestamp": 1607072537177, "nonce": "", "extra": { "type": 1, "guild_id": "guild_id", "channel_name": "频道名", "mention": [], "mention_all": false, "mention_roles": [], "mention_here": false, "author": { "id": "user_id", "username": "用户名", "avatar": "avatar_url" } } } }' ``` -------------------------------- ### KOOK API General Guidelines Source: https://github.com/kaiheila/api-docs/blob/main/oas/descriptions/intro.md This section details general API usage policies, including prohibited actions related to user accounts, data handling, legal compliance, and API abuse. ```APIDOC ## KOOK API Usage Guidelines ### Prohibited Uses: * Modifying KOOK user account information without explicit user permission. * Sending messages, uploading files, or playing audio on behalf of KOOK users. * Obtaining user passwords or web certificates without explicit user permission. * Scraping any KOOK data. * Using KOOK data for purposes other than operating a bot. * Sharing or disclosing user data without explicit permission. * Disclosing KOOK data to third-party advertisers, data service providers, or for profit. * Retaining data beyond what's necessary for bot operation. * Violating KOOK's User Privacy Policy. * Accessing KOOK with user passwords. * Selling, licensing, or commercializing KOOK data. * Processing KOOK data in a way that violates common sense or user expectations. * Pushing information that violates laws (e.g., pornography, gambling, drugs, politics, personal attacks, fraud). * Engaging in activities that cause death, personal injury, or environmental damage. * Encouraging or facilitating illegal activities or infringement of third-party rights. * Defaming, harassing, tracking, threatening others, or violating KOOK User Community Guidelines. ### Allowed Uses: * Requiring end-users to comply with laws and regulations (non-intentional violations). * Accessing KOOK's API only in ways specified in the developer platform documentation. ### Prohibited Actions: * Deleting, obscuring, or altering KOOK's Terms of Service or related notices/content. * Encouraging or creating features that violate KOOK's Terms of Service. * Sub-licensing the API to third parties. * Introducing viruses, worms, defects, trojans, malware, or any destructive content into KOOK products/services. * Reverse engineering or attempting to extract source code from the API or related software. * Registering or logging into KOOK developer accounts with false identities. * Encouraging or allowing third parties to violate KOOK's Developer Privacy Policy. * Interfering with or disrupting KOOK's API servers or network. ### API Limitations: KOOK imposes usage limits on API calls (e.g., requests per unit time, number of servers, number of users served). Written authorization from KOOK is required for exceeding these limits. ``` -------------------------------- ### WebSocket Connection and Event Subscription Source: https://context7.com/kaiheila/api-docs/llms.txt Establish a WebSocket connection to receive real-time event pushes, including messages, user status updates, and server changes. ```APIDOC ## WebSocket Connection and Event Subscription ### Description Establish a WebSocket long connection to receive real-time event pushes, including messages, user status, and server changes. ### Method WebSocket ### Endpoint Obtained via `GET /api/v3/gateway/index` ### Parameters #### Request Body (for initial connection) - **compress** (integer) - Optional - Whether to enable compression. 0 for no compression, 1 for zlib compression. ### Request Example (Python using `websocket-client`) ```python import websocket import json import requests # 1. Get Gateway Connection URL def get_gateway_url(bot_token): headers = {'Authorization': f'Bot {bot_token}'} response = requests.get( 'https://www.kookapp.cn/api/v3/gateway/index?compress=0', headers=headers ) return response.json()['data']['url'] # 2. WebSocket Event Handling Class class KOOKBot: def __init__(self, bot_token): self.bot_token = bot_token self.session_id = None self.sn = 0 def on_message(self, ws, message): data = json.loads(message) signal = data['s'] # Signal 0: Event Message if signal == 0: event_data = data['d'] self.sn = data.get('sn', self.sn) # Handle text messages if event_data['channel_type'] == 'GROUP': print(f"Received channel message: {event_data['content']}") print(f"Sender: {event_data['extra']['author']['username']}") # Reply to message if event_data['type'] == 1 and '你好' in event_data['content']: self.send_message( event_data['target_id'], f"Hello! (met){event_data['author_id']}(met)" ) # Signal 1: HELLO (Handshake Confirmation) elif signal == 1: self.session_id = data['d']['session_id'] print(f"Connection successful! Session ID: {self.session_id}") # Signal 2: PING (Heartbeat) elif signal == 2: print("Received heartbeat PING") # Signal 3: PONG (Heartbeat Response) elif signal == 3: print("Sending heartbeat PONG") ws.send(json.dumps({"s": 2})) # Signal 5: RECONNECT (Server Request Reconnection) elif signal == 5: print("Server requested reconnection") ws.close() self.connect() # Signal 6: RESUME ACK (Session Resumption Successful) elif signal == 6: print("Session resumed successfully") def on_error(self, ws, error): print(f"WebSocket Error: {error}") def on_close(self, ws, close_status_code, close_msg): print(f"WebSocket Connection Closed: {close_status_code} - {close_msg}") def on_open(self, ws): print("WebSocket connection established") def send_message(self, channel_id, content): """Send a message to a channel.""" url = 'https://www.kookapp.cn/api/v3/message/create' headers = { 'Authorization': f'Bot {self.bot_token}', 'Content-Type': 'application/json' } data = { 'type': 9, # Text message type 'target_id': channel_id, 'content': content } response = requests.post(url, headers=headers, json=data) return response.json() def connect(self): gateway_url = get_gateway_url(self.bot_token) # Add resume parameters if session_id exists if self.session_id: gateway_url += f"&resume=1&sn={self.sn}&session_id={self.session_id}" ws = websocket.WebSocketApp( gateway_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) ws.run_forever() # Usage Example if __name__ == '__main__': BOT_TOKEN = 'YOUR_BOT_TOKEN' bot = KOOKBot(BOT_TOKEN) bot.connect() ``` ### Response Messages received via WebSocket will have a `signal` field indicating the type of message. Common signals include: - `0`: Event message - `1`: HELLO (initial handshake) - `2`: PING (heartbeat request) - `3`: PONG (heartbeat response) - `5`: RECONNECT (server requests reconnection) - `6`: RESUME ACK (session resumption acknowledgment) ```