Skip to content

Library Reference

The rootbot package is the reusable library, the framework core (bot), the platform adapter (wire, client, chat) and the optional integrations (voice, music). The examples in examples/ are built only on what is documented here. All modules use the standard library except voice.py, which uses the LiveKit Python SDK (livekit==1.3.0).

For the exact signature of every public symbol, see the API Reference.

rootbot.core.bot

Bot, the framework core. It owns the API client, multi-community discovery (ListMine, with a config fallback) and the polling loop, and is deliberately voice-free: voice lives in rootbot.voice.session and rootbot.voice.player and is used only by the music example.

from rootbot.core.bot import Bot

bot = Bot()   # token from ROOT_TOKEN or .env; or Bot(token=..., config=...)
MemberBehaviour
@bot.command(name=None, brief="", usage="", cooldown=0.0, aliases=(), owner_only=False)Register an async command handler. The handler receives a Context. cooldown is per-user seconds (0 = none); owner_only restricts the command to BotConfig.owner_id. A built-in help command is auto-registered at startup when auto_help is on and no help command exists, it is generated from the registered commands' names, briefs and usages.
@bot.event / @bot.on(name)Register an event handler: on_ready(bot), on_message(message), on_voice_join(member) / on_voice_leave(member) (presence diffing over WebRtcGrpcService/List, polling-based, best-effort, only polled when a handler is registered), on_tick(bot) (each loop iteration), on_shutdown(bot).
bot.before_dispatch(fn) / bot.after_dispatch(fn)Hooks around command dispatch. A before-hook returning False vetoes the command.
bot.use(middleware)Append a middleware to the dispatch pipeline (see rootbot.core.middleware). Middleware compose in registration order around the handler.
bot.run() / await bot.start() / bot.stop()Blocking run (asyncio), async start, graceful stop. The loop polls all watched containers, dispatches fresh messages, rescans communities every rescan_seconds, and survives handler and poll errors (both are logged, never fatal).
bot.discover()Refresh community/channel discovery → (communities, source) where source is "api" or "config". Results also fill the entity cache.
bot.get_channel(id) / bot.get_community(id) / await bot.fetch_channel(community_id, channel_id)Entity lookup: cache first, then discovered state; fetch_channel falls back to the API.
bot.say(container_id, text)Send plain text to a container, split at message_limit.
bot.help_text()The generated help listing.
ContextWhat handlers receive: message (a Message model), command, args (raw string), arg_list, author_id, container_id, community_id, channel / community properties, reply(text), send(container_id, text), and converters arg_int(i), arg_float(i), arg_bool(i), arg_duration(i) (raise ConversionError on bad input, which dispatch turns into a short Invalid argument: reply). Args tolerate Root's link markup (a pasted URL arrives as [url](root://…); clean_query in the music example (examples/musicbot/music.py) unwraps it).

rootbot.core.models

Typed dataclasses returned at every user-facing boundary. Each also supports dict-style access (msg["content"], "id" in msg, msg.get("id"), msg.to_dict()) as a migration bridge.

ModelFields
Messageid, user_id, user_name, content, container_id, community_id.
Channelid, name, type (1 text, 4 voice), members, community_id.
Communityid, name, default_channel_id.
Userid, name.
Roleid, name, community_id.
Memberuser_id, community_id, name, roles.
VoiceMemberuser_id, channel_id, community_id, is_muted, is_deafened, is_video, is_screen.
Tracktitle, url, duration (ms), author.

Parsing is tolerant: unknown payload fields are ignored everywhere (wire.try_parse never raises on new fields), so a Root update that adds fields does not crash the bot.

rootbot.errors

RootBotError is the base. AuthError (HTTP 401/403, token dead), APIError (carries status, service, method), NotFoundError (HTTP 404), ConfigError, TokenMissingError (a ConfigError with a hint on where to put the token), ConversionError (bad command argument; carries value and kind).

rootbot.config

BotConfig dataclass: token, prefix (default "!"), community_id / container_id (discovery fallback seed), communities (fallback list), error_reply, poll_seconds (2.0), rescan_seconds (60), owner_id, auto_help (True), message_limit (2000), cooldown_reply. validate() raises ConfigError on bad values. load_token() reads ROOT_TOKEN from the environment or a .env file ($ROOTBOT_ENV, ./.env, repo-root .env) and raises TokenMissingError with instructions when absent. load_config() merges env + an optional JSON file (unknown JSON keys land in BotConfig.extra). ROOTBOT_OWNER_ID sets the owner from the environment.

rootbot.core.converters

parse_int, parse_float, parse_bool, parse_duration, parse_str, and convert(kind, text). Durations accept a bare number (seconds) or unit parts: 90, 5m, 2h, 1h30m, 1m15s (units s, m, h, d). Bad input raises ConversionError with a message that names the expected form.

rootbot.core.middleware

A middleware is async def mw(ctx, nxt), call await nxt() to run the rest of the pipeline (and ultimately the handler), or return without calling it to veto the command. Built in: logging_middleware() (logs command start/done/raised through the framework logger) and rate_limit_middleware(limit=5, per_seconds=60, clock=None, reply=None) (sliding window per command+user; the clock is injectable so tests never sleep).

rootbot.core.cache

EntityCache(maxsize=1024), a bounded LRU cache keyed by (kind, id), with typed helpers put_user/get_user, put_channel/get_channel, put_community/get_community, put_member/get_member, plus discard, clear and len().

rootbot.core.text

split_message(text, limit=2000), split a long reply into chunks of at most limit chars, preferring newline breaks, then spaces, then a hard cut. The framework sends plain text only, it never generates mention markup, and Bot.say applies this splitting automatically.

rootbot.logging

Stdlib logging, preconfigured: get_logger(name) returns a logger writing plain %(message)s lines to stdout. A RedactionFilter scrubs Bearer <token> patterns and every string registered with register_secret(value) (the API client registers the token) from records before they are emitted. configure_logging(level, fmt) adjusts the framework loggers. Set ROOTBOT_LOG_PAYLOADS=1 to log raw API payload sizes and prefixes at debug level when re-mapping an endpoint after a Root update.

rootbot.testing

Test doubles for bot authors: FakeRootApi (in-memory communities, channels, scripted messages and voice presence; records sent, edited, pinned, deleted), FakeClock (callable now + advance()

  • a recording sleep()), and builders fake_community, fake_channel, fake_message, fake_voice_member. The framework's own suite (tests/test_framework.py) is written against these.

rootbot.wire

Minimal protobuf + grpc-web framing, and the GUID codec. Root GUIDs are encoded as a message of two fixed64 fields, each half being the little-endian storage of the big-endian u64 of that GUID half.

FunctionSignature / behaviour
varint(n)Encode an unsigned varint → bytes.
tag(field, wire_type)Encode a field tag.
field_varint(field, value)A varint field (wire type 0).
field_bytes(field, data)A length-delimited field (wire type 2).
field_fixed64(field, value)A fixed64 field (wire type 1), little-endian.
guid_message(guid)Encode a GUID string as the two-fixed64 message.
parse(buf)Decode a buffer → list of (field_number, value); values are int for varints, bytes otherwise.
try_parse(buf)parse that returns None instead of raising.
find_field(buf, target)First length-delimited field with that number, searching nested messages recursively.
find_varint(buf, target)First varint field with that number, also recursive.
parse_guid(b)Decode a two-fixed64 message back to a GUID string, or None.
grpc_frame(payload)Wrap a payload in a grpc-web data frame.
grpc_deframe(data)Extract the data-frame payload from a grpc-web response body.

rootbot.adapters.root.client

RootApi, authenticated calls to https://api.rootapp.com.

from rootbot.adapters.root.client import RootApi

api = RootApi(token)   # token: the account's Bearer token, no "Bearer " prefix
MethodBehaviour
call(service, method, payload)POST root.<service>/<method> with the grpc-web-framed payload and the Bearer header (30 s timeout); returns the deframed response body (bytes). Transient failures (HTTP 429/500/502/503/504 and connection errors) are retried with exponential backoff + jitter, RootApi(token, retry=RetryPolicy(max_attempts=3, base_delay=0.5, max_delay=8.0), sleep=…, rand=…); sleep and rand are injectable for tests. HTTP 401/403 raise AuthError immediately, 404 raises NotFoundError, other HTTP errors raise APIError after the attempts run out.
get_self()UserGrpcService/GetSelf with an empty payload → raw response.
self_id()The account's own user id (GUID string), parsed from GetSelf field 10, or None.
list_communities()CommunityGrpcService/ListMine (empty request) → list of Community models for every community the account belongs to.
list_channels(community_id)CommunityGrpcService/GetExtended → list of Channel models. type is 1 (text) or 4 (voice); members is the list of user ids currently in the channel's voice (from webrtc_members), empty for text channels.
webrtc_members(community_id, container_id)WebRtcGrpcService/List, read-only presence: user ids currently in that voice channel. No join required.
webrtc_presence(community_id, container_id)Same endpoint → list of VoiceMember models (mute/deafen/video/screen flags included).
list_messages(container_id, community_id, limit=20)v2.MessageGrpcService/List, newest first. limit must be 10–50 (server validator). Returns Message models; user_name is only set when the author appears in the response's reference maps (mentions), otherwise None.
send_message(container_id, community_id, text)v2.MessageGrpcService/Create (context field omitted, content as StringValue) → the new message's id, or None.
edit_message(container_id, community_id, message_id, text)v2.MessageGrpcService/Edit (content as a plain string field) → the message id.
delete_message(container_id, community_id, message_id)v2.MessageGrpcService/Delete → True. Implemented from the mapped schema; not yet live-verified (see the modbot example).
pin_message(container_id, community_id, message_id)v2.MessageGrpcService/PinCreate → True.
list_pins(container_id, community_id)v2.MessageGrpcService/PinList → pinned Message models.
session_create(community_id, container_id)WebRtcGrpcService/SessionCreate with supports_v2=1 → (backend, url, jwt): backend selector varint, LiveKit wss:// URL, and the join JWT. Returns empty strings instead of raising when the reply is missing fields.

rootbot.chat

ChatWatcher, polling reader over a set of containers.

from rootbot.chat import ChatWatcher

watcher = ChatWatcher(api, containers, self_id)
# containers: {container_id: community_id}
MethodBehaviour
prime()Fetch every watched container once and mark all existing message ids seen, so history never replays as commands. Returns the count primed.
prime_container(container_id)Prime a single container; returns its message count.
add_container(container_id, community_id)Start watching a container, priming it first. Returns the primed count.
remove_container(container_id)Stop watching a container.
poll_all()Fetch all containers and return every fresh Message (id unseen, not from self_id, has content), oldest first, each tagged with its container_id + community_id. This is what Bot.start() dispatches.
poll()Legacy filter over poll_all(): only messages whose stripped text starts with ! or is a single digit (picker replies).
send(container_id, text)Send a message into a watched container (looks up its community). Returns the new message id.
edit(container_id, message_id, text) / pin(container_id, message_id) / pins(container_id)Edit / pin / list pins in a watched container.

rootbot.voice.player

Player, one LiveKit room connection publishing one audio track. Audio format throughout: 48 kHz, mono, s16le PCM, 20 ms frames (960 samples). Module constants: SAMPLE_RATE = 48000, CHANNELS = 1, FRAME_MS = 20, SAMPLES_PER_FRAME = 960.

from rootbot.voice.player import Player

player = Player(url, jwt)   # url + jwt from RootApi.session_create()
await player.connect()
MemberBehaviour
connect()Join the room and publish a mic-source LocalAudioTrack fed by an internal AudioSource.
play_process(proc)Pump a PCM-producing process (see to_pcm/stream_*) into the track, frame by frame, until its stdout ends or stop_current() kills it. Honours paused and gain. Resets the position clock at start.
to_pcm(source_stdout)Wrap a byte stream in ffmpeg, decoding to the standard PCM format → Popen.
stream_feed(feed_proc)Register an arbitrary producer process (e.g. a curl stream) as the feed and return its PCM pump process.
stream_ytdlp(url)Start yt-dlp -f bestaudio for a URL (resolved next to the Python executable first, then PATH) and return its PCM pump process.
set_paused(value)Pause/resume the pump. While paused, the pump stops reading, so the producer blocks on its pipe, position is preserved exactly.
played_seconds()Pause-adjusted elapsed seconds for the current track.
gainFloat attribute (1.0 = 100%). Applied per frame via scale_pcm when ≠ 1.0.
pausedBool attribute reflecting pause state.
play_tone(seconds=10, freq=440)Publish a generated sine tone, the simplest end-to-end voice check.
stop_current()Kill the pump and feed processes and clear pause state.
disconnect()stop_current() plus leaving the room.

scale_pcm(data, gain), module-level helper: multiply s16le samples by gain, clamping to int16 range.

The music example (examples/musicbot/music.py)

YouTube/Lavalink helpers, part of the reference example (not the framework package).

Function / memberBehaviour
youtube_id(url)Extract a video id from youtu.be, watch, shorts, embed, and live URLs, or None.
info_track(track)Normalise a Lavalink track object → a Track model (duration in ms), or None when it has no URI.
Lavalink(base_url="http://127.0.0.1:2333", password=None, password_file=None)Client for one Lavalink server.
Lavalink.from_env()Build from LAVALINK_BASE / LAVALINK_PASSWORD_FILE environment variables; raises SetupError RB-E014 when no password is configured.
password()Resolve the server password: constructor value → LAVALINK_PASSWORD env → password file → SetupError RB-E014 (no default file).
available()True when a password resolved, i.e. Lavalink playback is usable.
fetch(identifier)GET /v4/loadtracks?identifier=… with the password header → parsed JSON.
resolve(query)Resolve a URL, video id, or search terms (terms become ytsearch:) → (kind, tracks) where kind is "track", "search", "playlist", or None; tracks are Track models. Pasted Root link markup is unwrapped first (clean_query).
search(query, limit=5)First limit tracks from resolve.
load(query)First track from resolve, or None.
open_stream(video_id)Start curl against <base>/youtube/stream/<videoId> with the password header → Popen whose stdout is the audio byte stream, ready for Player.stream_feed.