Extension
Extensions let you split a bot's commands and event handlers across multiple files without losing access to the bot
instance or its config. An extension is loaded at runtime and can hook into bot lifecycle events via on_load and
on_unload.
# greetings.py
from matrix import Context
from matrix.extension import Extension
greetings = Extension("greetings")
@greetings.command("hello")
async def hello(ctx: Context):
await ctx.reply("Hello there!")
# main.py
from matrix import Bot
from greetings import greetings
bot = Bot()
bot.load_extension(greetings)
bot.start(config="config.yml")
matrix.extension.Extension
Extension(name, prefix=None)
Bases: Registry
Source code in matrix/extension.py
14 15 16 17 18 19 | |
bot
property
bot
config
property
config
get_room
get_room(room_id)
Retrieve a Room instance by its Matrix room ID.
Returns the Room object corresponding to room_id if it exists in
the client's known rooms. Returns None if the room cannot be found.
Example
room = extension.get_room("!abc123:matrix.org")
if room:
print(room.name)
Source code in matrix/extension.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
load
load(bot)
Source code in matrix/extension.py
46 47 48 49 50 | |
on_load
on_load(func)
Decorator to register a function to be called after this extension is loaded into the bot.
Example
@extension.on_load
def setup():
print("extension loaded")
Source code in matrix/extension.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
unload
unload()
Source code in matrix/extension.py
69 70 71 72 73 | |
on_unload
on_unload(func)
Decorator to register a function to be called before this extension is unloaded from the bot.
Example
@extension.on_unload
def teardown():
print("extension unloaded")
Source code in matrix/extension.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | |