Write Your Own Bot
The framework is not a music-bot kit, the music bot is just the biggest example. This tutorial goes from nothing to a running bot, then extends it. Everything here is plain text chat: no voice, no Lavalink.
1. Get a token
A Root bot is a normal user account driven headlessly, authenticated by its Bearer token. Use a throwaway alt account (Root's Terms of Use do not permit automated use, Section 2.5; never your main). Capture the token once by following Token Capture, about two minutes with Proxifier + mitmproxy.
Put it in a .env file in your working directory, or export it:
export ROOT_TOKEN=<the captured token>2. The echobot
examples/echobot/echobot.py is a complete bot:
from rootbot.core.bot import Bot
bot = Bot()
@bot.event
async def on_ready(bot):
print(
f"echobot ready as {bot.self_id}, watching "
f"{len(bot.watcher.containers)} channels",
flush=True,
)
@bot.command("ping")
async def ping(ctx):
await ctx.reply("pong")
@bot.command("echo")
async def echo(ctx):
await ctx.reply(ctx.args or "say what?")
if __name__ == "__main__":
bot.run()Run it:
python3 -m examples.echobot.echobotBot() finds the token (environment, then .env), discovers every community the account belongs to, no ids to configure, primes the message history so old messages never replay as commands, and starts polling. Type !ping in any channel the alt can see: pong.
Running it with the rootbot command
Any bot module can also run under the framework's generic runner, which is what the examples and the Docker image use:
rootbot doctor # setup checks only, then stop
rootbot serve examples/echobot/echobot.py # or a module path: examples.echobot.echobot
rootbot new mybot # a starter project that runs the same wayserve takes a module path or a .py file and uses its bot attribute (or a create_bot() factory). Startup runs the setup checks in error-table order and fails fast with a [RB-E0xx] message, never a traceback. Exit codes: 0 the bot ran and stopped cleanly; 1 a setup check failed (the message carries its RB-E id, see Troubleshooting); 2 bad arguments or a target that does not load as a bot module.
3. Commands with metadata
Handlers receive a typed Context. Add brief/usage and the built-in !help (auto-registered) lists your command; add a cooldown for a per-user rate limit; add converters for typed args:
@bot.command("remind", brief="Remind you in a while", usage="<duration> <text>", cooldown=10)
async def remind(ctx):
seconds = ctx.arg_duration(0) # "5m" -> 300.0
text = " ".join(ctx.arg_list[1:])
await ctx.reply(f"ok, {seconds:.0f}s: {text}")A bad argument (!remind soon x) does not crash anything: dispatch catches the ConversionError and replies Invalid argument: …. Aliases work too: @bot.command("remind", aliases=("r",)).
Restrict a command to yourself with owner_only=True and ROOTBOT_OWNER_ID=<your user id> in the environment, with no owner configured, owner-only commands refuse everyone.
4. Events and middleware
React to every message (not just commands) with on_message, and to voice joins with presence diffing:
@bot.event
async def on_message(message):
if "hello" in (message.content or "").lower():
pass # your logic; use bot.say(message.container_id, ...) to answer
@bot.event
async def on_voice_join(member):
print(f"{member.user_id} joined voice in {member.community_id}")Voice events are polling-based (Root has no push gateway), so treat them as best-effort. Cross-cutting behaviour goes in middleware, which wraps dispatch in registration order:
from rootbot.core.middleware import logging_middleware, rate_limit_middleware
bot.use(logging_middleware())
bot.use(rate_limit_middleware(limit=5, per_seconds=60))5. A moderation bot
examples/modbot/ watches messages against a banned-word list and warns the author, and adds an owner-only !delete <message id> built on the client's delete_message. One honesty note: delete is implemented from the mapped MessageGrpcService/Delete schema and has not yet been live-verified, test it on your alt first.
6. Test without a server
rootbot.testing ships the doubles the framework's own suite uses:
from rootbot.testing import FakeRootApi, FakeClock, fake_message
api = FakeRootApi(self_id="bot-id", communities=[...], channels={...})
bot = Bot(api=api, config=BotConfig(...), clock=FakeClock())
await bot.dispatch(fake_message("m1", "user-id", "!ping", "chan", "comm"))
assert api.sent # replies the bot recordedFakeClock drives cooldowns and retry backoff without sleeping.
7. Going further
- Configuration (prefix, poll cadence, error replies): see Configuration and
rootbot.config. - Running it 24/7 on a VPS under systemd: see Deployment.
- Every module and method: the Library Reference.
- The rules the framework itself is built to: Standards Mapping.