Extension
Demonstrates how to split a bot into modules using Extension and how to organise related commands into a Group.
from matrix import Extension, Context
extension = Extension("math")
@extension.group("math", description="Math Group")
async def math_group(ctx: Context):
pass
@math_group.command()
async def add(ctx: Context, a: int, b: int):
await ctx.reply(f"**{a} + {b} = {a + b}**")
@math_group.command()
async def subtract(ctx: Context, a: int, b: int):
await ctx.reply(f"{a} - {b} = {a - b}")
@math_group.command()
async def multiply(ctx: Context, a: int, b: int):
await ctx.reply(f"{a} x {b} = {a * b}")
@math_group.command()
async def divide(ctx: Context, a: int, b: int):
await ctx.reply(f"{a} ÷ {b} = {a / b}")
@divide.error(ZeroDivisionError)
async def divide_error(ctx: Context, error):
await ctx.reply(f"Divide error: {error}")
"""
# bot.py
from matrix import Bot
from math_extension import extension as math_extension
bot = Bot()
bot.load_extension(math_extension)
bot.start(config="config.yaml")
"""
Key points:
Extension("math")creates a standalone module. It supports commands, groups, events, checks, and error handlers — everythingBotsupports.@extension.group("math")creates a command group. Sub-commands are registered with@math_group.command()and invoked as!math add,!math subtract, etc.- Per-command error handlers work the same as on
Bot:@divide.error(ZeroDivisionError)handles division by zero inside the group.
To load this extension in your bot:
from matrix import Bot
from math_extension import extension as math_extension
bot = Bot()
bot.load_extension(math_extension)
bot.start(config="config.yaml")
See the Bigger Bot guide for a full project layout using multiple extensions.