Context
Context is passed as the first argument to every command callback. It bundles the bot instance, the room the message arrived in, the originating event, and the parsed arguments — giving commands everything they need to respond.
from matrix import Bot, Context
bot = Bot()
@bot.command("info")
async def info(ctx: Context):
await ctx.reply(f"Sent by {ctx.sender} in {ctx.room.room_id}")
matrix.context.Context
Context(bot, room, event)
Represents the context in which a command is executed. Provides access to the bot instance, room and event metadata, parsed arguments, and other utilities.
Source code in matrix/context.py
22 23 24 25 26 27 28 29 30 31 32 33 | |
bot
instance-attribute
bot = bot
room
instance-attribute
room = room
event
instance-attribute
event = event
body
instance-attribute
body = getattr(event, 'body', '')
sender
instance-attribute
sender = sender
command
instance-attribute
command = None
subcommand
instance-attribute
subcommand = None
args
property
args
Returns the list of parsed arguments from the message body.
If a command is present, the command name is excluded.
:return: The list of arguments. :rtype: List[str]
logger
property
logger
Logger for instance specific to the current room or event.
reply
async
reply(content=None, *, raw=False, notice=False, file=None)
Reply to the command with a message.
This is a convenience method that sends a message to the room where the command was invoked. Supports text messages (with optional markdown formatting) and file uploads (including images, videos, and audio).
See Room.send() for detailed usage examples and documentation.
Example
@bot.command()
async def hello(ctx: Context):
await ctx.reply("Hello **world**!")
@bot.command()
async def status(ctx: Context):
await ctx.reply("Bot is online!", notice=True)
@bot.command()
async def cat(ctx: Context):
# Upload and send an image
from PIL import Image as PILImage
with PILImage.open("cat.jpg") as img:
width, height = img.size
with open("cat.jpg", "rb") as f:
resp, _ = await ctx.room.client.upload(f, content_type="image/jpeg")
image = Image(
path=resp.content_uri,
filename="cat.jpg",
mimetype="image/jpeg",
width=width,
height=height
)
await ctx.reply(file=image)
Source code in matrix/context.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
send_help
async
send_help()
Send help from the current command context.
Displays help text for the current subcommand, command, or the bot's general help menu depending on what's available in the context. The help hierarchy is: subcommand help > command help > bot help.
Example
@bot.group()
async def config(ctx: Context):
# If user runs just "!config" with no subcommand
await ctx.send_help()
Source code in matrix/context.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |