KlangDocs

    Open Klang

    Bots

    View as Markdown

    Connect your library

    The exact settings that point discord.js, discord.py and JDA at Klang, and a bot that answers “pong” to “!ping” in each. Your bot’s logic doesn’t change.

    What changes

    A library written for Discord’s API needs to know three addresses. On Klang they are:

    What Klang
    REST API https://api.klang.gg/api/v10 (/api/v9 works too)
    Gateway wss://bot-gateway.klang.gg, also returned by GET /api/v10/gateway/bot
    Images https://media.klangcdn.com (see Images)

    Some libraries ask the REST API where the gateway is, and don’t need the second address. Others have the gateway written in their code, and need it set too. Besides the addresses, use your Klang bot token, and that’s all: commands, event handlers and the rest of your code stay as they are. Slash commands and their interactions go through the same addresses, with nothing more to set: see Slash commands.

    We checked these settings against the source code of discord.js 14.28.1 (@discordjs/rest 2.6.3 and @discordjs/ws 1.2.3), discord.py 2.7.1 and JDA 6.7.0, the latest releases on 15 November 2026. Other versions of the same major line should work the same way.

    The examples below answer pong when someone writes !ping, so they need the Message content intent switched on in the portal (see Intents). Each reads the token from the KLANG_BOT_TOKEN environment variable.

    discord.js

    discord.js asks the REST API for the gateway, so it only needs the rest option: api, without the version (the library adds /v10 itself), and cdn for images. mediaProxy is where it loads animated stickers from.

    JavaScript
    import { Client, Events, GatewayIntentBits } from 'discord.js';
    
    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
      ],
      // The only Klang-specific lines.
      rest: {
        api: 'https://api.klang.gg/api',
        cdn: 'https://media.klangcdn.com',
        mediaProxy: 'https://media.klangcdn.com',
      },
    });
    
    client.once(Events.ClientReady, (ready) => {
      console.log(`Signed in as ${ready.user.tag}`);
    });
    
    client.on(Events.MessageCreate, async (message) => {
      if (message.author.bot) return;
      if (message.content === '!ping') {
        await message.reply('pong');
      }
    });
    
    client.login(process.env.KLANG_BOT_TOKEN);

    Notes for discord.js:

    • Compression. discord.js uses zlib-stream when the optional zlib-sync package is installed, and plain JSON when it isn’t. Klang takes both.

    • Install links. client.generateInvite() builds its link on the rest.api address. Klang forwards it to the app, so the link works.

    • Webhooks. WebhookClient only accepts a URL on Discord’s domain. Pass the ID and the token instead, with the same rest.api option:

      JavaScript
      import { WebhookClient } from 'discord.js';
      
      const webhook = new WebhookClient(
        { id: process.env.KLANG_WEBHOOK_ID, token: process.env.KLANG_WEBHOOK_TOKEN },
        { rest: { api: 'https://api.klang.gg/api' } },
      );
      
      await webhook.send('Deploy finished.');

    discord.py

    discord.py keeps its addresses in class attributes. A regular discord.Client connects to the gateway written in its code instead of asking the API, so the REST API, the gateway and the images need setting. Set them once, before you create the client:

    Python
    import os
    
    import discord
    import yarl
    
    # The Klang-specific lines.
    discord.http.Route.BASE = "https://api.klang.gg/api/v10"
    discord.gateway.DiscordWebSocket.DEFAULT_GATEWAY = yarl.URL("wss://bot-gateway.klang.gg/")
    discord.asset.Asset.BASE = "https://media.klangcdn.com"
    
    intents = discord.Intents.default()
    intents.message_content = True
    
    client = discord.Client(intents=intents)
    
    
    @client.event
    async def on_ready():
        print(f"Signed in as {client.user}")
    
    
    @client.event
    async def on_message(message):
        if message.author.bot:
            return
        if message.content == "!ping":
            await message.reply("pong")
    
    
    client.run(os.environ["KLANG_BOT_TOKEN"])

    Notes for discord.py:

    • yarl comes with discord.py (through aiohttp), so there’s nothing else to install.
    • Commands. commands.Bot from discord.ext.commands is a Client, so the same three lines work for it, and for the slash commands of its app_commands tree.
    • Compression. discord.py always compresses the gateway: with zstd-stream when Python has zstd (built in from Python 3.14, or with the zstandard package) and with zlib-stream otherwise. Klang supports both.
    • Animated stickers. discord.py writes their address on Discord’s servers in its code, so the url of a GIF sticker doesn’t load. The other images do: see Images.

    JDA

    JDA takes the REST API from RestConfig. The gateway comes from its SessionController, which returns Discord’s address unless you override getGateway(). Extending ConcurrentSessionController, the one JDA uses by default, keeps everything else as it is:

    Java
    import net.dv8tion.jda.api.JDABuilder;
    import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
    import net.dv8tion.jda.api.hooks.ListenerAdapter;
    import net.dv8tion.jda.api.requests.GatewayIntent;
    import net.dv8tion.jda.api.requests.RestConfig;
    import net.dv8tion.jda.api.utils.ConcurrentSessionController;
    
    public class PingBot extends ListenerAdapter {
        public static void main(String[] args) {
            JDABuilder.createDefault(System.getenv("KLANG_BOT_TOKEN"))
                .enableIntents(GatewayIntent.MESSAGE_CONTENT)
                // The Klang-specific lines.
                .setRestConfig(new RestConfig().setBaseUrl("https://api.klang.gg/api/v10/"))
                .setSessionController(new ConcurrentSessionController() {
                    @Override
                    public String getGateway() {
                        return "wss://bot-gateway.klang.gg/";
                    }
                })
                .addEventListeners(new PingBot())
                .build();
        }
    
        @Override
        public void onMessageReceived(MessageReceivedEvent event) {
            if (event.getAuthor().isBot()) return;
            if (event.getMessage().getContentRaw().equals("!ping")) {
                event.getMessage().reply("pong").queue();
            }
        }
    }

    Notes for JDA:

    • Compression. JDA uses zlib-stream by default. Klang supports it.
    • Sharding. A DefaultShardManager asks the REST API for the gateway and gets Klang’s. Klang runs one shard per bot for now, so a single JDA is the simplest choice.
    • Images. JDA writes Discord’s image addresses in its code (User.getAvatarUrl() and similar), and they can’t be changed. See Images.
    • Links. Message.getJumpUrl() points to Discord’s domain. See Links to messages.

    Images

    Avatars, server icons, banners and emojis arrive as a hash, as in Discord’s API, and libraries build the image’s address from it. Klang serves them at https://media.klangcdn.com, in the same shape as Discord’s CDN, once the library’s image setting points there (rest.cdn in discord.js, discord.asset.Asset.BASE in discord.py). Then user.displayAvatarURL(), guild.iconURL() or an emoji’s URL load the image. Attachments keep their own full url.

    What it serves:

    Image Address
    A person’s, a bot’s or a webhook’s avatar /avatars/{user_id}/{hash}.{ext}
    Someone without an avatar (defaultAvatarURL) /embed/avatars/{0-5}.png
    A server’s icon /icons/{guild_id}/{hash}.{ext}
    A person’s or a server’s banner /banners/{id}/{hash}.{ext}
    An application’s icon /app-icons/{application_id}/{hash}.{ext}
    A custom emoji /emojis/{emoji_id}.{ext}
    A sticker /stickers/{sticker_id}.{ext}

    How it differs from Discord’s:

    • One file per image. Klang serves the image as it was uploaded, in its own format and size: the extension and the ?size= you ask for are accepted and ignored. The Content-Type says the real format, and browsers and image libraries read it from there.
    • Hashes look like 1234567890123456789_png, with a_ in front when the image moves, and not like 32 hex characters. Treat them as opaque: compare them, don’t parse them.
    • Default avatars are a flat colour, without a logo.
    • Not served: members’ per-server avatars (Klang sends null), role icons, splashes, group DM icons and avatar decorations.

    Images on Discord’s servers (cdn.discordapp.com, media.discordapp.net) never load in Klang. So don’t leave a library on its default image address: an image or an icon there is left out of an embed, and the rest of the embed still shows. With the setting above, displayAvatarURL() and the rest work in embeds too.

    Other libraries

    Any library can work with Klang if it lets you change the REST API’s base address and, when it doesn’t ask GET /gateway/bot, the gateway’s. Check that it:

    • sends Authorization: Bot <token> and speaks version 10 (or 9) of the API;
    • uses JSON on the gateway. Klang doesn’t speak ETF, and a connection that asks for it is closed with 4002;
    • uses one shard, or asks GET /gateway/bot how many to use (Klang says 1).

    If a library doesn’t let you change its addresses, it can’t reach Klang without a patch.