Skip to content

Room

Room wraps a Matrix room and provides high-level helpers for sending messages of every type — plain text, Markdown, notices, files, images, audio, and video. It delegates unknown attribute access to the underlying MatrixRoom from matrix-nio.

from matrix import Bot, Context

bot = Bot()

@bot.command("announce")
async def announce(ctx: Context, *, message: str):
    await ctx.room.send_markdown(f"**Announcement:** {message}")

matrix.room.Room

Room(matrix_room, client)

Represents a Matrix room and provides methods to interact with it.

Source code in matrix/room.py
24
25
26
def __init__(self, matrix_room: MatrixRoom, client: AsyncClient) -> None:
    self._matrix_room: MatrixRoom = matrix_room
    self._client: AsyncClient = client

matrix_room property

matrix_room

Access to underlying MatrixRoom object.

client property

client

Access to the Matrix client.

name property

name

Room display name.

room_id property

room_id

Room ID.

display_name property

display_name

Room display name (alias for name).

topic property

topic

Room topic.

member_count property

member_count

Number of members in the room.

encrypted property

encrypted

Whether the room is encrypted.

send async

send(content=None, *, raw=False, notice=False, file=None)

Send a message to the room.

This is a convenience method that automatically routes to the appropriate send method based on the provided arguments. Supports text messages (with optional markdown formatting) and file uploads (including images, videos, and audio).

For detailed text message examples, see Room.send_text(). For detailed file upload examples, see Room.send_file().

Example
# Send a markdown-formatted text message
await room.send("Hello **world**!")

# Send a file
file = File(path="mxc://...", filename="document.pdf", mimetype="application/pdf")
await room.send(file=file)

# Send an image
image = Image(path="mxc://...", filename="photo.jpg", mimetype="image/jpeg", width=800, height=600)
await room.send(file=image)
Source code in matrix/room.py
 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
116
117
118
119
120
121
async def send(
    self,
    content: str | None = None,
    *,
    raw: bool = False,
    notice: bool = False,
    file: File | None = None,
) -> Message:
    """Send a message to the room.

    This is a convenience method that automatically routes to the appropriate
    send method based on the provided arguments. Supports text messages (with
    optional markdown formatting) and file uploads (including images, videos, and audio).

    For detailed text message examples, see `Room.send_text()`.
    For detailed file upload examples, see `Room.send_file()`.

    ## Example

    ```python
    # Send a markdown-formatted text message
    await room.send("Hello **world**!")

    # Send a file
    file = File(path="mxc://...", filename="document.pdf", mimetype="application/pdf")
    await room.send(file=file)

    # Send an image
    image = Image(path="mxc://...", filename="photo.jpg", mimetype="image/jpeg", width=800, height=600)
    await room.send(file=image)
    ```
    """
    if content:
        return await self.send_text(content, raw=raw, notice=notice)

    if file:
        return await self.send_file(file)
    raise ValueError("You must provide content or file.")

send_text async

send_text(
    content, *, raw=False, notice=False, reply_to=None
)

Send a text message to the room.

By default, messages are formatted using Markdown. You can send raw unformatted
text with `raw=True`, or send a notice message (typically used for bot status
updates) with `notice=True`. Use `reply_to` to create a threaded reply.
Example
# Send markdown-formatted message
await room.send_text("**Bold** and *italic* text")

# Send raw text without formatting
await room.send_text("This is plain text", raw=True)

# Send a notice message
await room.send_text("Bot restarted successfully", notice=True)

# Reply to another message
await room.send_text("Replying to you!", reply_to="$event_id")
Source code in matrix/room.py
123
124
125
126
127
128
129
130
131
132
133
134
135
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
async def send_text(
    self,
    content: str,
    *,
    raw: bool = False,
    notice: bool = False,
    reply_to: str | None = None,
) -> Message:
    """Send a text message to the room.

        By default, messages are formatted using Markdown. You can send raw unformatted
        text with `raw=True`, or send a notice message (typically used for bot status
        updates) with `notice=True`. Use `reply_to` to create a threaded reply.

    ## Example

    ```python
    # Send markdown-formatted message
    await room.send_text("**Bold** and *italic* text")

    # Send raw text without formatting
    await room.send_text("This is plain text", raw=True)

    # Send a notice message
    await room.send_text("Bot restarted successfully", notice=True)

    # Reply to another message
    await room.send_text("Replying to you!", reply_to="$event_id")
    ```
    """
    payload: TextContent

    if reply_to:
        payload = ReplyContent(content, reply_to_event_id=reply_to)
    elif notice:
        payload = NoticeContent(content)
    elif raw:
        payload = TextContent(content)
    else:
        payload = MarkdownMessage(content)

    return await self._send_payload(payload)

send_file async

send_file(file)

Send a file, image, video, or audio to the room.

Accepts any File object or its subclasses (Image, Video, Audio). The file must be uploaded to the Matrix content repository before sending. Use the room's client upload method to get the MXC URI.

The method automatically detects the file type and sends it with the appropriate Matrix message type (m.file, m.image, m.video, or m.audio).

For more information on the upload method, see the matrix-nio documentation: https://matrix-nio.readthedocs.io/en/latest/nio.html#nio.AsyncClient.upload

Example
import os

# Send a document
file_path = "document.pdf"
file_size = os.path.getsize(file_path)

with open(file_path, "rb") as f:
    resp, _ = await room.client.upload(
        f,
        content_type="application/pdf",
        filesize=file_size
    )

file = File(
    path=resp.content_uri,
    filename="document.pdf",
    mimetype="application/pdf"
)
await room.send_file(file)

# Send an image
from PIL import Image as PILImage

image_path = "photo.jpg"

with PILImage.open(image_path) as img:
    width, height = img.size

file_size = os.path.getsize(image_path)

with open(image_path, "rb") as f:
    resp, _ = await room.client.upload(
        f,
        content_type="image/jpeg",
        filesize=file_size
    )

image = Image(
    path=resp.content_uri,
    filename="photo.jpg",
    mimetype="image/jpeg",
    width=width,
    height=height
)
await room.send_file(image)

# Send a video
import cv2

video_path = "video.mp4"

cap = cv2.VideoCapture(video_path)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = int((frame_count / fps) * 1000)
cap.release()

file_size = os.path.getsize(video_path)

with open(video_path, "rb") as f:
    resp, _ = await room.client.upload(
        f,
        content_type="video/mp4",
        filesize=file_size
    )

video = Video(
    path=resp.content_uri,
    filename="video.mp4",
    mimetype="video/mp4",
    width=width,
    height=height,
    duration=duration
)
await room.send_file(video)

# Send audio
audio_path = "audio.mp3"
file_size = os.path.getsize(audio_path)

with open(audio_path, "rb") as f:
    resp, _ = await room.client.upload(
        f,
        content_type="audio/mpeg",
        filesize=file_size
    )

audio = Audio(
    path=resp.content_uri,
    filename="audio.mp3",
    mimetype="audio/mpeg",
    duration=180000  # 3 minutes in milliseconds
)
await room.send_file(audio)
Source code in matrix/room.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
async def send_file(self, file: File) -> Message:
    """Send a file, image, video, or audio to the room.

    Accepts any File object or its subclasses (Image, Video, Audio). The file must
    be uploaded to the Matrix content repository before sending. Use the room's
    client upload method to get the MXC URI.

    The method automatically detects the file type and sends it with the appropriate
    Matrix message type (m.file, m.image, m.video, or m.audio).

    For more information on the upload method, see the matrix-nio documentation:
    https://matrix-nio.readthedocs.io/en/latest/nio.html#nio.AsyncClient.upload

    ## Example

    ```python
    import os

    # Send a document
    file_path = "document.pdf"
    file_size = os.path.getsize(file_path)

    with open(file_path, "rb") as f:
        resp, _ = await room.client.upload(
            f,
            content_type="application/pdf",
            filesize=file_size
        )

    file = File(
        path=resp.content_uri,
        filename="document.pdf",
        mimetype="application/pdf"
    )
    await room.send_file(file)

    # Send an image
    from PIL import Image as PILImage

    image_path = "photo.jpg"

    with PILImage.open(image_path) as img:
        width, height = img.size

    file_size = os.path.getsize(image_path)

    with open(image_path, "rb") as f:
        resp, _ = await room.client.upload(
            f,
            content_type="image/jpeg",
            filesize=file_size
        )

    image = Image(
        path=resp.content_uri,
        filename="photo.jpg",
        mimetype="image/jpeg",
        width=width,
        height=height
    )
    await room.send_file(image)

    # Send a video
    import cv2

    video_path = "video.mp4"

    cap = cv2.VideoCapture(video_path)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = int((frame_count / fps) * 1000)
    cap.release()

    file_size = os.path.getsize(video_path)

    with open(video_path, "rb") as f:
        resp, _ = await room.client.upload(
            f,
            content_type="video/mp4",
            filesize=file_size
        )

    video = Video(
        path=resp.content_uri,
        filename="video.mp4",
        mimetype="video/mp4",
        width=width,
        height=height,
        duration=duration
    )
    await room.send_file(video)

    # Send audio
    audio_path = "audio.mp3"
    file_size = os.path.getsize(audio_path)

    with open(audio_path, "rb") as f:
        resp, _ = await room.client.upload(
            f,
            content_type="audio/mpeg",
            filesize=file_size
        )

    audio = Audio(
        path=resp.content_uri,
        filename="audio.mp3",
        mimetype="audio/mpeg",
        duration=180000  # 3 minutes in milliseconds
    )
    await room.send_file(audio)
    ```
    """
    payload: FileContent

    match file:
        case Image():
            payload = ImageContent(
                filename=file.filename,
                url=file.path,
                mimetype=file.mimetype,
                height=file.height,
                width=file.width,
            )
        case Audio():
            payload = AudioContent(
                filename=file.filename,
                url=file.path,
                mimetype=file.mimetype,
                duration=file.duration,
            )
        case Video():
            payload = VideoContent(
                filename=file.filename,
                url=file.path,
                mimetype=file.mimetype,
                height=file.height,
                width=file.width,
                duration=file.duration,
            )
        case _:
            payload = FileContent(
                filename=file.filename, url=file.path, mimetype=file.mimetype
            )

    return await self._send_payload(payload)

fetch_event async

fetch_event(event_id)

Fetch a Matrix event by its ID.

Example
    event = await room.fetch_event("$event_id:matrix.org")
    print(event.sender)
Source code in matrix/room.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
async def fetch_event(self, event_id: str) -> Event:
    """Fetch a Matrix event by its ID.

    ## Example
    ```python
        event = await room.fetch_event("$event_id:matrix.org")
        print(event.sender)
    ```
    """
    try:
        response = await self.client.room_get_event(
            room_id=self.room_id,
            event_id=event_id,
        )
        return response.event
    except Exception as e:
        raise MatrixError(f"Failed to get event: {e}")

fetch_message async

fetch_message(event_id)

Fetch a Message by its event ID.

Example
    message = await room.fetch_message("$event_id:matrix.org")
    message.reply("hello world")
Source code in matrix/room.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
async def fetch_message(self, event_id: str) -> Message:
    """Fetch a Message by its event ID.

    ## Example
    ```python
        message = await room.fetch_message("$event_id:matrix.org")
        message.reply("hello world")
    ```
    """
    event = await self.fetch_event(event_id)
    return Message(
        room=self,
        event=event,
        client=self.client,
    )

invite_user async

invite_user(user_id)

Invite a user to the room.

The bot must have permission to invite users to the room. The user will receive an invitation that they can accept or decline.

Example
# Invite a user by their Matrix ID
await room.invite_user("@alice:example.com")
Source code in matrix/room.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
async def invite_user(self, user_id: str) -> None:
    """Invite a user to the room.

    The bot must have permission to invite users to the room. The user will
    receive an invitation that they can accept or decline.

    ## Example

    ```python
    # Invite a user by their Matrix ID
    await room.invite_user("@alice:example.com")
    ```
    """
    try:
        await self.client.room_invite(room_id=self.room_id, user_id=user_id)
    except Exception as e:
        raise MatrixError(f"Failed to invite user: {e}")

ban_user async

ban_user(user_id, reason=None)

Ban a user from the room.

The bot must have permission to ban users. Banned users cannot rejoin the room until they are unbanned. Optionally provide a reason for the ban.

Example
# Ban a user without a reason
await room.ban_user("@spammer:example.com")

# Ban a user with a reason
await room.ban_user("@spammer:example.com", reason="Spam and harassment")
Source code in matrix/room.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
async def ban_user(self, user_id: str, reason: str | None = None) -> None:
    """Ban a user from the room.

    The bot must have permission to ban users. Banned users cannot rejoin
    the room until they are unbanned. Optionally provide a reason for the ban.

    ## Example

    ```python
    # Ban a user without a reason
    await room.ban_user("@spammer:example.com")

    # Ban a user with a reason
    await room.ban_user("@spammer:example.com", reason="Spam and harassment")
    ```
    """
    try:
        await self.client.room_ban(
            room_id=self.room_id, user_id=user_id, reason=reason
        )
    except Exception as e:
        raise MatrixError(f"Failed to ban user: {e}")

unban_user async

unban_user(user_id)

Unban a user from the room.

The bot must have permission to unban users. This removes the ban, allowing the user to rejoin the room if invited or if the room is public.

Example
# Unban a previously banned user
await room.unban_user("@alice:example.com")
Source code in matrix/room.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
async def unban_user(self, user_id: str) -> None:
    """Unban a user from the room.

    The bot must have permission to unban users. This removes the ban,
    allowing the user to rejoin the room if invited or if the room is public.

    ## Example

    ```python
    # Unban a previously banned user
    await room.unban_user("@alice:example.com")
    ```
    """
    try:
        await self.client.room_unban(room_id=self.room_id, user_id=user_id)
    except Exception as e:
        raise MatrixError(f"Failed to unban user: {e}")

kick_user async

kick_user(user_id, reason=None)

Kick a user from the room.

The bot must have permission to kick users. Unlike banning, kicked users can rejoin the room if they have an invite or if the room is public. Optionally provide a reason for the kick.

Example
# Kick a user without a reason
await room.kick_user("@troublemaker:example.com")

# Kick a user with a reason
await room.kick_user("@troublemaker:example.com", reason="Violating room rules")
Source code in matrix/room.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
async def kick_user(self, user_id: str, reason: str | None = None) -> None:
    """Kick a user from the room.

    The bot must have permission to kick users. Unlike banning, kicked users
    can rejoin the room if they have an invite or if the room is public.
    Optionally provide a reason for the kick.

    ## Example

    ```python
    # Kick a user without a reason
    await room.kick_user("@troublemaker:example.com")

    # Kick a user with a reason
    await room.kick_user("@troublemaker:example.com", reason="Violating room rules")
    ```
    """
    try:
        await self.client.room_kick(
            room_id=self.room_id, user_id=user_id, reason=reason
        )
    except Exception as e:
        raise MatrixError(f"Failed to kick user: {e}")