discord

    An experimental Discord library for MoonBit: native/JS/Wasm REST, interactions, and gateway bots. Voice is in gaato/discord_voice.

    discord
    bot
    gateway
    api
    interactions
    Download zip
    Author
    Version
    0.19.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    1K

    #gaato/discord

    Build Discord bots and interaction endpoints in MoonBit. Declare a slash command once: the same declaration registers it with Discord and decodes its arguments into your type in the handler. A Gateway bot and a signed HTTP endpoint, such as one on Cloudflare Workers or Deno, can serve the same App. A REST-only tool can import the HTTP client on its own.

    Runs on native, JavaScript and Wasm under moonrun. Voice is a separate module, gaato/discord_voice.

    Unofficial, and not affiliated with Discord. A minor release can change the API; the changelog lists each change with a migration note.

    #Install

    moon add gaato/discord

    A bot's main is an async fn main, so its package imports moonbitlang/core/async (part of the standard library, so there is nothing to moon add) and lists it under allow-experimental-packages. The bot template has the whole setup, including token loading and shutdown.

    #Quickstart

    Build the interaction App, then hand it to the Gateway Bot. This bot registers and answers /echo in the scope it is given, such as Guild(test_guild_id) while you develop:

    ///|
    struct QuickstartEchoArgs {
    text : String
    times : Int32
    }

    ///|
    async fn run_echo_bot(token : String, scope : @discord.CommandScope) -> Unit {
    let args : @discord.Args[QuickstartEchoArgs] = @discord.Args::map2(
    @discord.arg_string(name="text", description="What to echo"),
    @discord.arg_int32(
    name="times",
    description="How many times (1-5)",
    min=1,
    max=5,
    ).with_default(1),
    (text, times) => { text, times, },
    )
    let echo = @discord.slash(
    name="echo",
    description="Echo your text back",
    args~,
    handler=Immediate((_ctx, value) => {
    @discord.CommandReply::message(
    content=Array::make(value.times, value.text).join("\n"),
    )
    }),
    )
    let app = @discord.AppBuilder()
    app.command(echo)
    let bot = @discord.BotBuilder(app.build(), token~, sync=scope)
    bot.on(@discord.Events::ready(), (_ctx, ready) => {
    println("ready as \{ready.user.username}")
    })
    bot.build().run()
    }

    ///|
    test "the quickstart bot compiles" {
    ignore(run_echo_bot)
    }

    Args drives both the registration payload and the decoding of each invocation, so the two cannot drift apart.

    Command sync replaces what is registered. With sync=, the bot overwrites the commands in that scope in bulk after its first READY, and by default deletes commands your app does not declare. During development, sync to a test guild with Guild(id) rather than Global. Pass sync_unowned=Keep to leave other commands alone. Without sync=, nothing is synchronized. When a bot runs in several processes, enable sync in exactly one of them.

    #Choose the packages

    Import only what the program needs:

    ApplicationPackages under gaato/discord
    Gateway bot with commands and eventsThe root facade: AppBuilder, BotBuilder, typed Events.
    REST-only tool or background jobhttp (routes, pagination, uploads, rate limiting), which brings model.
    Serverless HTTP interactions (Cloudflare Workers, Deno, Bun, Node.js)app and verify.
    Native or moonrun Wasm HTTP interactions serverendpoint_http.
    Tests without Discordtestkit for fixtures. http.Client::offline answers REST calls from your function.

    #All packages and their targets

    PackageWhat it isNativeJSWasm¹
    gaato/discordFacade: the names a typical application uses directlyYesYes²Yes²
    gaato/discord/modelPure data: API entities and gateway payloads, no I/OYesYesYes
    gaato/discord/httpREST Client, routes, rate limiting, multipart uploadsYesYesYes
    gaato/discord/gatewayShard: connection state machine, heartbeat, resumeYesYesYes
    gaato/discord/interactionCommand and component builders, typed args, autocomplete dataYesYesYes
    gaato/discord/frameworkInteraction routing, response gates, low-level response contextsYesYesYes
    gaato/discord/appGateway-free typed commands, components and modals, HTTP endpoint, sync and policyYesYesYes
    gaato/discord/botGateway executor and typed gateway event descriptorsYesYesYes
    gaato/discord/endpoint_httpSigned-interactions HTTP server (serve_interactions)YesNoYes
    gaato/discord/cacheOpt-in, gateway-driven in-memory cacheYesYesYes
    gaato/discord/utilPermissions, mentions, timestamps, CDN URLsYesYesYes
    gaato/discord/verifyPure MoonBit Ed25519 request verificationYesYesYes
    gaato/discord/ratelimitIn-memory Discord rate limiterYesYesYes
    gaato/discord/cooldownCommand cooldown store and in-memory fixed windowsYesYesYes
    gaato/discord/queueIdentify queue and in-memory implementationYesYesYes
    gaato/discord/coordinatorExperimental TCP coordinator for multi-process Identify, REST limits and cooldownsYesNoYes
    gaato/discord/telemetryStructured REST, gateway and dispatch observability valuesYesYesYes
    gaato/discord/testkitDeterministic interaction and model fixturesYesYesYes

    ¹ Linear-memory Wasm run by moonrun. Generic WASI runtimes, browsers and wasm-gc are not targets. ² The HTTP-server exports exist on native and Wasm only.

    #Gateway connections

    Gateway connections use gaato/mttp/ws. On JavaScript, the host must provide a WebSocket API (Node.js 22 and later include it); see mttp's host support. A message may be up to 64 MiB by default, in either direction (max_message_bytes=). Past the limit, the connection closes with code 1009.

    #Guides

    The guides cover each part in depth, and their code compiles and runs in the test suite:

    1. Getting started: a minimal slash-command bot and command synchronization
    2. Commands: typed arguments, autocomplete, subcommands, context menus, and Discord's three-second deadline
    3. Components and modals
    4. Events and intents: typed subscriptions, intents, sharding, sessions, compression and the cache
    5. REST: endpoints, rate limits, uploads and pagination
    6. HTTP interactions: gateway-free dispatch, the native server and JavaScript hosts
    7. Structuring bots
    8. Scaling across processes
    9. Middleware
    10. Voice
    11. The framework layer: handler tests without a network
    12. Models and utilities

    Exact types and methods are documented in doc comments, many with examples: browse them on mooncakes, or run moon ide doc "@discord".

    The repository's examples include Gateway bots, HTTP interaction servers, JavaScript host adapters, a Durable Object bot and voice players. Run one from the repository root with moon run --target native examples/slash_echo.

    #License

    Apache-2.0