Skip to content

Plugins

A plugin is a self-contained bundle of commands, event handlers and middleware that a bot loads without being edited. The music bot is itself a plugin. Plugins are trusted operator code: they run unsandboxed in the bot's process, with the bot's permissions. Only load plugins you have read. The framework never downloads a plugin or executes remote code; a plugin exists because the operator put it in config.

The plugin contract is provisional. It is at PLUGIN_API_VERSION 1, and it may change before the framework reaches 1.0. Known candidates for change before 1.0:

  • the PluginContext surface itself, under the versioning rules at the end of this page;
  • a narrow handler context: the handler Context given to a plugin's command and event handlers may be narrowed so plugin code no longer receives the raw Bot (see the PluginContext section below).

The versioning rules at the end of this page say what kind of change bumps the number and what a plugin author has to do when it does.

Writing a plugin

A plugin is an object with five attributes and two async methods:

from rootbot import PLUGIN_API_VERSION


class DicePlugin:
    name = "dice"                    # a slug: lowercase, digits, - and _
    version = "1.0.0"                # the plugin's own version
    api_version = PLUGIN_API_VERSION # required, must match the framework
    requires_framework = ">=0.2,<0.3"  # required, a PEP 440 specifier
    dependencies = ()                # names of plugins that load first

    async def setup(self, ctx):
        @ctx.command("roll")
        async def roll(c):
            await c.reply("4")

    async def teardown(self, ctx):
        pass

setup and teardown are async-only and receive a PluginContext, not the Bot. A sync setup, a missing api_version, an empty requires_framework, or a name that is not a slug all fail the load with a typed error, before anything is registered.

The PluginContext

The context is a narrow facade over the bot's public API. Through it a plugin can:

  • register commands, event handlers, before/after dispatch hooks and middleware (ctx.command, ctx.event, ctx.on, ctx.before_dispatch, ctx.after_dispatch, ctx.use), with the same signatures as the Bot's own registration methods;
  • send messages (await ctx.send(container_id, text)), through the bot's normal send path;
  • edit its own sent messages (await ctx.edit(container_id, message_id, text)), scoped to the messages it owns (see Message ownership below). The record of owned ids is bounded (the last 100 per container) and in memory only: it does not persist across restarts. Rapid successive edits to one message coalesce into a single edit carrying the latest text;
  • pin its own messages (await ctx.pin(container_id, message_id)), under the same ownership scoping as edit;
  • recover its own earlier messages (await ctx.adopt_recent_messages(container_id, limit=50)), which returns the bot's own recent messages in a container and adopts their ids so edit and pin accept them: the restart case, covered in Message ownership below;
  • use voice through ctx.voice (see Voice below);
  • read the bot account's own user id (ctx.self_id, valid once the bot's session is established; accessing it earlier raises RuntimeError) and a community's channels (ctx.channels( community_id), a read-only tuple snapshot; voice channels carry type 4);
  • read per-community settings (ctx.settings(community_id));
  • keep private state in ctx.storage, a key-value namespace that belongs to this plugin alone. Storage is non-persistent: it lives in memory only, is dropped when the plugin unloads, and does not survive a bot restart. A plugin that needs persistence must use its own storage through its own code;
  • read the bot's clock (ctx.clock) and log through ctx.logger;
  • start tracked background work with ctx.spawn(coro).

The context deliberately has no Bot, no Root adapter or client, no access to other plugins, and no load, unload or shutdown controls.

The context is not a security boundary. It exists so the framework can attribute a plugin's registrations and tasks to it and clean them up on unload, and so well-behaved plugins do not depend on framework internals. It is not isolation. Setup and teardown receive the narrow PluginContext, but a plugin's command and event handlers receive the framework's regular handler Context, which carries a public bot attribute: handler code can reach the full Bot, and through it the Root adapter, no matter what setup was handed. Plugin code also runs in the bot's process with the bot's permissions regardless. Only load plugins you trust, exactly as the trust model above says.

Everything registered or spawned through the context is attributed to the plugin. On unload, the framework removes exactly those registrations and cancels exactly those tasks, including work a handler started later through a context it kept from setup. Cancellation is bounded by BotConfig.plugin_task_cancel_timeout (default 5 s): a task that swallows its cancellation and keeps running is warned about by name in the plugin's log and abandoned, so it cannot hang the unload. A spawned task that raises has the exception logged through ctx.logger.

Rules the loader enforces

  • Collisions fail the load. If a plugin registers a command name or alias that the bot or another plugin already owns, setup fails with PluginConflictError naming the command and both plugins, and the plugin is rolled back, never half-registered. The owner command names status, shutdown and reload are reserved outright. help is the one exception: the framework's own help defers to a plugin-provided one, as the music bot uses.
  • Dependencies load first and leave last. A plugin whose dependencies are not loaded fails with PluginDependencyError. Unloading or reloading a plugin that loaded plugins depend on is refused with the same error, listing the dependents; unload them first.
  • Purge sets may not overlap. A load is refused with PluginConflictError, naming both plugins and the overlapping module root, when the plugin's reload purge set (its configured module plus any declared purge_modules) overlaps a loaded plugin's purge set: reloading either one would purge the other's modules out from under it. The purge scope is defined under Reload below.
  • Timeouts bound the lifecycle. Setup must finish within BotConfig.plugin_setup_timeout (default 30 s) and teardown within BotConfig.plugin_teardown_timeout (default 10 s), or the operation fails with PluginTimeoutError. A timed-out teardown does not wedge the unload: registrations are still removed, tasks still cancelled, and the bot keeps running.
  • Failures stay visible. A plugin that fails validation or setup ends in bot.plugins_info() with state failed and the error message, and registered nothing.

Loading plugins

Module-based loading happens only through config. An entry in BotConfig.plugins is a dotted module path whose module defines PLUGIN (an instance) or Plugin (a class built with no arguments):

BotConfig(plugins=["myplugins.dice", "myplugins.modtools"])

An entry may instead be a dict with a module and a purge_modules list. purge_modules names extra modules a reload of this plugin also purges from sys.modules, each with its submodules (the reload scope is defined under Reload below). It exists for a plugin package that imports a top-level sibling helper module: the helper is outside the plugin's own package, so without the declaration a reload would keep the helper's old code and state.

BotConfig(plugins=[{"module": "myplugins.dice",
                    "purge_modules": ["dicehelpers"]}])

Plugins can also be handed to await bot.load_plugin(plugin) as objects, and batches to await bot.load_plugins([...]), which loads them in dependency order. A plugin that fails during startup loading is logged and marked failed; the bot still starts.

Reload

The owner command reload <plugin> (and bot.reload_plugin(name)) reloads a plugin at runtime, under strict rules:

  • Names resolve only against the configured list. The name is never treated as a path or imported. reload ../x, reload os and reload some.dotted.path are refused, and so is any name that did not come from BotConfig.plugins.
  • Object-loaded plugins cannot be reloaded. There is no module to re-import. Unload the object and load the new one instead.
  • Reload is a fresh import of a defined purge set. Before importing, the framework purges a sys.modules set defined exactly: the plugin's configured module itself and every submodule under it, plus any extra modules the plugin's config entry declared in purge_modules, each with its submodules. The package the module lives in is not purged: for a plugin loaded from myplugins.dice, the shared myplugins package keeps its code and state, and so does a sibling plugin loaded from myplugins.coin. Two plugins with disjoint subtrees of one package therefore load together and reload independently, and the loader refuses a plugin whose purge set would overlap another loaded plugin's (see the loader rules above). Matching is on package boundaries only (an exact name, or a name followed by a dot), so purging music can never remove musicbox. Nothing else is ever purged. Framework modules and shared libraries the entry did not declare keep their state, and any code that imported names from the plugin earlier keeps the objects it already has.
  • A failed reload leaves the plugin unloaded. If teardown times out or raises, the re-import fails, or the new setup fails, the old registrations stay removed, no new ones remain, the plugin shows as failed with the error, and the owner command replies with that error. The bot and every other plugin keep running, and a later reload retries.
  • Reloading the music plugin stops it first. A plugin's teardown runs before anything is re-imported, and the music plugin's teardown stops playback, leaves voice and clears its current track: a reload never leaves music playing under a half-removed plugin.

Per-community disable

An operator can disable a plugin in one community through the community's settings (disabled_plugins). A disabled plugin's commands refuse with a "disabled in this community" reply, its event handlers and middleware are skipped for that community, and its commands are hidden from that community's help. Other communities are unaffected. One exception: if the disabled plugin is the one providing help, the framework's own help answers in that community instead of the refusal, listing only the commands that run there.

Disable reaches voice too: a disabled plugin cannot join voice in that community, its ctx.edit calls there are refused, and if it holds the community's voice connection when it is disabled, the connection is left.

Voice

ctx.voice is a plugin's voice facade. It is bound to the plugin: connections are attributed to it, and unloading the plugin leaves every connection it owns. No player, session or transport object crosses the facade; a plugin sees plain values only.

conn = await ctx.voice.join(community_id, channel_id)
await conn.play_url(url)                 # returns once playing
reason = await conn.wait_finished()      # FinishReason
await conn.leave()
  • One connection per community, across all plugins. A join by another plugin, or by the owning plugin naming a different channel, raises VoiceBusyError. The owning plugin rejoining its own channel returns the existing connection.
  • Typed errors. Join and playback failures raise VoiceJoinError / VoicePlaybackError (both PluginError); no bare RuntimeError escapes a join or a playback start.
  • Timeouts. Join, play_url (until playback starts), seek and leave are bounded by BotConfig.plugin_voice_timeout (default 15 s) and raise PluginTimeoutError on expiry. wait_finished is deliberately not bounded: a track is as long as it is.
  • VoiceConnection members: community_id, channel_id, state (a PlaybackState: IDLE, PLAYING, PAUSED), position (seconds played), volume (0.0 to 2.0, where 1.0 is the normal, unscaled volume), current_url, dropped, connected; play_url(url, *, seek=0.0, refresh=None), pause(), resume(), stop() (all three idempotent), seek(position), set_volume(volume) (ValueError outside 0.0 to 2.0), wait_finished(), members(), leave(), and on_event(callback).
  • URLs are fetched, never handed to ffmpeg. play_url accepts http and https URLs only and validates the URL before anything is opened: a scheme other than http/https, userinfo, a port outside BotConfig.voice_url_ports (default 80 and 443), a playlist path (.m3u8 / .mpd), or a literal address that is not public raises VoiceUrlRejectedError (a VoicePlaybackError). The framework then fetches the bytes itself and pipes them into ffmpeg, whose only allowed protocol is pipe. ffmpeg is never given the URL because it cannot be restricted: it follows redirects internally and re-resolves hostnames when it connects, with no option to pin a checked address, so a checked URL could still land somewhere private inside ffmpeg. The fetcher resolves the host once per hop, requires every resolved address to be public (an explicit blocked-range list covering loopback, RFC1918, link-local including the cloud metadata address 169.254.169.254, CGNAT, and the embedded addresses of IPv4-mapped, 6to4 and NAT64 forms, on top of is_global), and connects to the pinned address, with TLS verified against the original hostname. Redirects are followed manually, at most 5 hops, with the full validation re-run per hop, so a redirect to a private address is refused before connecting (that refusal, met mid-fetch, ends the track as FAILED). No credentials are ever sent: the request carries no Authorization or Cookie header. Hosts named in BotConfig.allow_private_hosts (a list, empty by default) skip the public-address rule but are still resolved once and pinned. The exemption never covers the hard-deny list: the link-local ranges (169.254.0.0/16 and fe80::/10) and the well-known cloud metadata addresses (169.254.169.254, 169.254.170.2, fd00:ec2::254, 100.100.100.200 and 168.63.129.16) stay blocked for allowlisted hosts too, in literal, resolved and embedded (IPv4-mapped, 6to4 and NAT64) forms alike. Bodies are capped by BotConfig.voice_url_max_bytes (default 512 MiB); connect and idle reads are bounded by voice_url_connect_timeout / voice_url_idle_timeout, and resolution on every hop is bounded by voice_url_dns_timeout (default 5 s), with at most 4 resolutions running at once. HLS and DASH playlists are rejected, not half-supported, and only identity Content-Encoding is accepted. Seeking stays an ffmpeg output seek over the pipe, which costs the same as it did when ffmpeg opened the URL itself: in a local benchmark (120 s MP3 served over HTTP, median of 5) the first frame after a 60 s seek arrived in about 224 ms with fetch-and-pipe versus about 248 ms before, the seek cost being the decode-and-discard of the skipped audio in both designs.
  • Drops are the connection's problem. When the transport dies mid-track, the connection reconnects (bounded attempts, backoff on the bot's clock) and resumes at the position reached. The optional refresh callback is asked for a fresh URL first, because a resolved stream URL may have expired. Callbacks registered with on_event receive VoiceEvent values (DROPPED, RECONNECTED, GAVE_UP). Only when the reconnect gives up does wait_finished return FinishReason.DROPPED; the other reasons are ENDED, STOPPED and FAILED.
  • The facade also answers presence: await ctx.voice.members(community_id, channel_id) lists a channel's members, await ctx.voice.find_member(community_id, user_id) finds which of a community's voice channels a user is in (the follow-me lookup; the scan is bounded at MAX_VOICE_CHANNEL_SCAN = 64 voice channels and costs one presence read per scanned channel), and ctx.voice.connection(community_id) returns the plugin's live connection in a community, if any.

The music plugin's pinned dashboard goes through this surface like everything else the plugin does: it adopts its earlier message with ctx.adopt_recent_messages, pins with ctx.pin and refreshes with ctx.edit. It used to be the documented exception, reaching the Bot's chat watcher and presence internals through bundles the serve composition injected; those bundles are gone.

Which path guards what

The fetcher guards the URLs it fetches. Not every URL a bot plays is fetched by it: the music example's player splits its routes by URL kind, and the provider routes never pass through the fetcher. Read the guards per route, not per URL:

RouteWhat validates the URLWhat opens the networkWhat the fetcher guards
Provider track via Lavalink (the music example's default)The play_url syntax layer (scheme, userinfo, port, playlist path, literal address), plus the example's provider-host gate before resolutionThe Lavalink server fetches provider media on its side; the bot itself only opens the localhost stream endpoint (via curl)Nothing on this route: no framework fetch happens. The guards are the provider-host allowlist and Lavalink's own source configuration (the deploy template disables its http and local sources)
Provider track via yt-dlp (Lavalink unavailable)The same syntax layer and provider-host gateyt-dlp itself, with its own DNS and redirect handling, run with --no-playlist --ignore-configNothing on this route either: yt-dlp's network handling is outside the fetcher. The guards are the provider-host allowlist and the hardened invocation
Direct URL via the framework fetcher (any plugin on the framework player; the music example with allow_direct_urls enabled)The full fetcher validation: syntax, one resolution per hop, every address public and hard-deny-checked, pinned connect, re-validated per redirect hopThe fetcher's own pinned sockets; ffmpeg receives only pipe bytesEverything on this route: the SSRF policy, the hard-deny list, the DNS/connect/idle timeouts, the size cap and the parser limits

So a direct URL pasted into the music example (with the operator's allow_direct_urls on) is fetched by the third route and only that route: it never reaches yt-dlp or Lavalink for playback. A provider locator is never fetched by the framework at all; claiming the fetcher "protects playback" without naming the route is wrong in both directions.

Message ownership

ctx.edit and ctx.pin act only on messages the plugin owns. A plugin owns:

  • every message id its own ctx.send calls returned this session, and
  • its own earlier messages it has taken back through ctx.adopt_recent_messages, which returns the bot account's own messages among a container's recent history (author == ctx.self_id) and records their ids as owned.

The owned-id record is bounded (the last 100 ids per container; older ids are evicted), in memory only, and dropped when the plugin unloads. It does not persist across restarts: a message sent by an earlier process is not editable or pinnable until the plugin adopts it. That is deliberate. Adoption is the one moment a plugin claims earlier messages, and it can only ever claim the bot's own.

An id the plugin does not own, an id in a community where the plugin is disabled, and an edit or pin the API rejects all return False and are logged; they never raise. Ownership is attribution, not isolation: it keeps well-behaved plugins from rewriting each other's messages by accident, and it is not a security boundary (see the trust model above).

Versioning

Two versions guard a plugin, on purpose:

  • PLUGIN_API_VERSION (currently 1) versions the contract itself: the Protocol shape, the PluginContext surface and the attribution semantics. A plugin declares api_version; a mismatch fails the load with PluginVersionError naming both numbers. The number bumps only when the contract changes in a way existing plugins cannot absorb, such as a PluginContext member being removed or the setup signature changing. Additive members and new error types do not bump it.
  • requires_framework is a PEP 440 specifier over the framework's release version, checked with the packaging library, the one runtime dependency the framework carries.