Bot
The Bot class is the heart of every matrix.py application. It manages the connection to a Matrix homeserver, registers
commands and event handlers, and drives the main event loop.
from matrix import Bot, Context
bot = Bot()
@bot.command("ping")
async def ping(ctx: Context):
await ctx.reply("Pong!")
bot.start(config="config.yml")
matrix.bot.Bot
Bot(*, help_=None)
Bases: Registry
The base class defining a Matrix bot.
This class manages the connection to a Matrix homeserver, listens for events, and dispatches them to registered handlers. It also supports a command system with decorators for easy registration.
Source code in matrix/bot.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
extensions
instance-attribute
extensions = {}
log
instance-attribute
log = getLogger(__name__)
start_at
instance-attribute
start_at = None
client
property
client
config
property
config
help
property
help
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 = bot.get_room("!abc123:matrix.org")
if room:
print(room.name)
Source code in matrix/bot.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
load_extension
load_extension(extension)
Source code in matrix/bot.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
unload_extension
unload_extension(ext_name)
Source code in matrix/bot.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
on_ready
async
on_ready()
Override this in a subclass.
Source code in matrix/bot.py
169 170 171 | |
on_error
async
on_error(error)
Override this in a subclass.
Source code in matrix/bot.py
178 179 180 | |
on_command
async
on_command(_ctx)
Override this in a subclass.
Source code in matrix/bot.py
189 190 191 | |
on_command_error
async
on_command_error(_ctx, error)
Override this in a subclass.
Source code in matrix/bot.py
196 197 198 | |
start
start(*, config)
Synchronous entry point for running the bot.
This is a convenience wrapper that allows running the bot like a
script using a blocking call. It internally calls :meth:run within
:func:asyncio.run, and ensures the client is closed gracefully
on interruption.
Source code in matrix/bot.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
run
async
run()
Log in to the Matrix homeserver and begin syncing events.
This method should be used within an asynchronous context,
typically via :func:asyncio.run. It handles authentication,
calls the :meth:on_ready hook, and starts the long-running
sync loop for receiving events.
Source code in matrix/bot.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
on_message
async
on_message(room, event)
Source code in matrix/bot.py
286 287 | |