KOOK Developer Documentation

repository·main·Indexed 42 days ago

https://github.com/kaiheila/api-docs

Documentation for building integrations on the KOOK gaming communication platform. Includes references for the KOOK Bot API (v3), authentication via Bot and OAuth2 tokens, rate limit management, and guides for implementing real-time notifications via Webhook or Websocket. Features detailed specifications for KMarkdown and structured Card messages, as well as a directory of community-maintained SDKs for PHP, JavaScript/TypeScript, Python, Ruby, Go, Java, and C#.

Tokens
9.7K
Snippets
30
Records
48
Agent score
53%

What's inside KOOK

  1. Understand role priority and permission limitations

    main

    Roles are ordered from top to bottom; this order determines their priority (the position field).

    Hierarchy Rules:

    • Even with Administrator permissions, you can only manage users or roles with a lower priority than your own.
    • You cannot manage, edit, or grant permissions to users or roles that have a priority equal to or higher than yours.

    When using APIs to grant or update permissions, ensure the performing entity (e.g., a bot) has a higher position than the target role/user, otherwise the operation will fail.

  2. Understand KOOK API Rate Limits and Restrictions

    main

    KOOK imposes usage limits on the API, which may include:

    • The number of API requests sent within a specific time unit.
    • The number of servers a bot can reside in.
    • The number of users a bot can serve.

    If you require access to APIs that exceed these limits, you must obtain written authorization from KOOK.

  3. Configure and decrypt Webhook messages

    main

    For higher security, you can enable message encryption using an Encrypt Key configured in the developer dashboard.

    Encryption Format: When enabled, the incoming request will contain an encrypt field instead of the raw event data:

    {
        "encrypt": "adfw232sdssdfadfas98XX......"
    }

    Decryption Logic (AES-256-CBC): Note: Even with encryption enabled, the payload is still zlib (deflate) compressed. Decompress first (or use ?compress=0 in the URL).

    1. Base64 Decode: Decode the encrypt string.
    2. Extract IV: The first 16 bytes of the decoded data is the iv.
    3. Extract Ciphertext: The remaining data is the new ciphertext.
    4. Base64 Decode Ciphertext: Decode the new ciphertext to get the raw encrypted bytes.
    5. Prepare Key: Take your encryptKey and pad it with null bytes (\0) until it is exactly 32 bytes long.
    6. Decrypt: Use aes-256-cbc with the extracted iv, the padded key, and the decoded ciphertext to retrieve the original JSON event.
  4. How to check permissions using bitwise operations

    main

    Permissions are represented as an unsigned int value where each bit corresponds to a specific permission. To determine if a user or entity possesses a specific permission, perform a bitwise AND operation between the total permissions value and the bitmask of the target permission.

    To check if a permission is present, use the following logic: permissions & (1 << bitValue) == (1 << bitValue)

    // permissions: the total permission value
    // bitValue: the index of the specific permission bit
    // 1 << bitValue: the bitmask for that permission
    
    if (permissions & (1 << bitValue) == (1 << bitValue)) {
        // User has the permission
    }
  5. How the KOOK API architecture works

    main

    The KOOK API is composed of two core layers that allow you to build bots or services:

    1. Standard HTTP Interfaces: Used for performing regular operations (GET/POST requests).
    2. Real-time Message Notifications: Used to subscribe to system messages and events via Webhook or Websocket.

    Both layers follow consistent specifications for message meaning and structure, though message pushes may use zlib (deflate) compression.

  6. How Card Messages work

    main

    Card messages are structured, JSON-based messages that provide a rich, interactive UI. A card message consists of a collection of card objects.

    Structure Hierarchy:

    • Card (card): The top-level container. A single message can contain up to 5 cards.
    • Modules: Contained within a card (e.g., section, header, context). A single message cannot exceed 50 modules in total.
    • Elements: Contained within modules (e.g., plain-text, image, button).
    • Fields: Contained within structural components (e.g., paragraph).

    General Object Schema: All elements follow a similar pattern:

    {
        "type": "category",
        "foo": "bar",
        "modules|elements|fields": []
    }
    [
      {
        "type": "card",
        "modules": [
          // ...
        ]
      }
    ]
  7. How to Resume a WebSocket Session

    main

    To prevent message loss during a disconnection, you can perform a session resumption. This requires appending specific parameters to the Gateway URL:

    • resume: Set to 1.
    • sn: The sequence number (sn) of the last successfully processed message. If no messages were received, use 0. You should persist this value (e.g., to a file) to allow recovery after a process restart.
    • session_id: The session_id obtained from the initial HELLO packet.

    Example URL structure: wss://[gateway_url]?resume=1&sn=[last_sn]&session_id=[session_id]

    wss://test.kookapp.com:8888/gateway?{compress/token parameters}&resume=1&sn=5&session_id=20****ae-1fa4-4d19-805f-6f0f****d534
  8. API Usage Restrictions and Prohibited Activities

    main

    To ensure a safe and legal environment, the KOOK API is subject to strict usage policies. Violations may result in penalties or bot suspension.

    Prohibited User Information Handling

    • Modifying user account information without explicit permission (e.g., forcing a user into a new server).
    • Impersonating users to send messages, upload files, or play audio.
    • Obtaining user passwords or web certificates.

    Prohibited Data Handling

    • Scraping KOOK data.
    • Using KOOK data for purposes other than operating a bot.
    • Sharing or disclosing user data without explicit permission.
    • Disclosing data to third-party advertisers or data service providers.
    • Retaining data longer than necessary for bot operations.
    • Commercializing KOOK data through sale or licensing.

    Prohibited Content and Behavior

    • Pushing illegal content (pornography, gambling, drugs, politics, personal attacks, fraud, etc.).
    • Activities that cause death, physical harm, or environmental damage.
    • Encouraging illegal activities or infringing on third-party rights.
    • Defamation, harassment, stalking, or threatening others.

    Prohibited API Abuse

    • Deleting, blurring, or changing KOOK's Terms of Service.
    • Encouraging users to violate KOOK's Terms of Service.
    • Sublicensing the API to third parties.
    • Introducing viruses, worms, or malicious software into KOOK services.
    • Reverse engineering the API or attempting to extract source code.
    • Interfering with or interrupting KOOK API servers or networks.
  9. Authenticate with the KOOK API

    main

    Authentication is performed by including a token in the Authorization HTTP header. The format is Authorization: <TOKEN_TYPE> <TOKEN>.

    Supported types:

    • Bot: Use Bot as the TOKEN_TYPE for bot-related operations.
    • OAuth2: Use Bearer as the TOKEN_TYPE for OAuth2 flows.
    Authorization: Bot BHsTZ4232tLatgV5AFyjoqZGAHHmpl9mTxYQ/u4/480=
  10. Receive and respond to Webhook events

    main

    Once configured, the platform sends event data via HTTP POST requests. To ensure a reliable integration, follow these requirements:

    1. Decompression: Data is compressed using zlib (deflate). You must decompress the payload before processing. Alternatively, append ?compress=0 to your callbackUrl to disable compression.
    2. Response Time: You must return an HTTP 200 response within 1 second. If you fail or timeout, the platform will retry with increasing intervals (2s, 4s, 8s, 16s, 32s, 64s) for up to 5 attempts.
    3. Idempotency: Check the sn field to ensure you do not process the same event multiple times.
    4. Security: Verify that the verify_token in the payload matches the verify_token in your developer dashboard to ensure the request originated from KOOK.

    Warning: If the failure rate exceeds a certain threshold, the platform will consider the bot faulty and take it offline. You must manually bring it back online in the developer dashboard, which will trigger the Challenge verification process again.

  11. Use community-provided SDKs for KOOK development

    main

    To avoid implementing the API from scratch, you can use various community-maintained SDKs. Below is a list of available SDKs for different programming languages:

    LanguageRepository NameRepository URL
    PHPkaiheila/php-botLink
    JavaScript/TypeScriptfi6/KBotify & shugen002/BotRootLink
    JavaScript/TypeScriptkookts/kook.tsLink
    PythonTWT233/khl.pyLink
    PythonTian-que/nonebot-adapter-kaiheilaLink
    PythonOlivOS-Team/OlivOSLink
    RubyDessertShop/KHLLink
    Golonelyevil/kookLink
    JavaDeeChael/Kaiheila.javaLink
    JavaEnaium/kook-spring-boot-starterLink
    C#gehongyan/Kook.NetLink