Skip to content

Message

Message represents a Matrix room message and exposes methods to react to, edit, or reply to it. Instances are obtained from Context.message or event listener callbacks.

from matrix import Bot, Context

bot = Bot()

@bot.command("like")
async def like(ctx: Context):
    await ctx.message.react("👍")

matrix.message.Message

Message(*, room, event, client)

Represents a Matrix message with methods to interact with it.

Source code in matrix/message.py
23
24
25
26
27
28
def __init__(self, *, room: "Room", event: Event, client: AsyncClient) -> None:
    self._room = room
    self._matrix_event: Event = event
    self._client = client

    self._body = getattr(self._matrix_event, "body", None)

room property

room

The room this message was sent in.

event property

event

The matrix event of this message

client property

client

The Matrix client.

event_id property

event_id

The event ID of this message.

body property

body

The text content of this message.

key property

key

The key of this message.

fetch_reactions async

fetch_reactions()

Fetch all reactions for this message.

Returns a dict mapping emoji to a list of sender IDs who reacted with it.

Example
    @bot.command()
    async def reactions(ctx: Context):
        reactions = await ctx.message.fetch_reactions()

        for emoji, senders in reactions.items():
            await ctx.reply(f"{emoji}: {len(senders)} reaction(s)")
Source code in matrix/message.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
async def fetch_reactions(self) -> list[Reaction]:
    """Fetch all reactions for this message.

    Returns a dict mapping emoji to a list of sender IDs who reacted with it.

    ## Example
    ```python
        @bot.command()
        async def reactions(ctx: Context):
            reactions = await ctx.message.fetch_reactions()

            for emoji, senders in reactions.items():
                await ctx.reply(f"{emoji}: {len(senders)} reaction(s)")
    ```
    """
    raw: dict[str, list[str]] = {}

    async for reaction_event in self._iter_reaction_events():
        raw.setdefault(reaction_event.emoji, []).append(reaction_event.sender)

    return [Reaction(key=emoji, senders=senders) for emoji, senders in raw.items()]

reply async

reply(body)

Reply to this message.

Creates a threaded reply to this message in the same room.

Example
@bot.command()
async def echo(ctx: Context):
    msg = await ctx.reply("Echo!")
    await msg.reply("Replying to my own message")
Source code in matrix/message.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
async def reply(self, body: str) -> "Message":
    """Reply to this message.

    Creates a threaded reply to this message in the same room.

    ## Example
    ```python
    @bot.command()
    async def echo(ctx: Context):
        msg = await ctx.reply("Echo!")
        await msg.reply("Replying to my own message")
    ```
    """
    try:
        return await self.room.send_text(content=body, reply_to=self.event_id)
    except Exception as e:
        raise MatrixError(f"Failed to send reply: {e}")

react async

react(emoji)

Add a reaction emoji to this message.

Example
@bot.command()
async def thumbsup(ctx: Context):
    msg = await ctx.reply("React to this!")
    await msg.react("👍")
Source code in matrix/message.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
async def react(self, emoji: str) -> None:
    """Add a reaction emoji to this message.

    ## Example
    ```python
    @bot.command()
    async def thumbsup(ctx: Context):
        msg = await ctx.reply("React to this!")
        await msg.react("👍")
    ```
    """
    content = ReactionContent(event_id=self.event_id, emoji=emoji)

    await matrix_call(
        self.client.room_send(
            room_id=self.room.room_id,
            message_type="m.reaction",
            content=content.build(),
        ),
        error_message="Failed to add reaction",
    )

unreact async

unreact(emoji)

Remove this client's reaction emoji from the message.

If the client has not reacted with the requested emoji, this method does nothing.

Example
@bot.command()
async def toggle(ctx: Context):
    msg = await ctx.reply("React to this!")
    await msg.react("👍")
    await msg.unreact("👍")
Source code in matrix/message.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
async def unreact(self, emoji: str) -> None:
    """Remove this client's reaction emoji from the message.

    If the client has not reacted with the requested emoji, this method
    does nothing.

    ## Example
    ```python
    @bot.command()
    async def toggle(ctx: Context):
        msg = await ctx.reply("React to this!")
        await msg.react("👍")
        await msg.unreact("👍")
    ```
    """
    reaction_event_id = None
    async for reaction_event in self._iter_reaction_events():
        if (
            reaction_event.emoji == emoji
            and reaction_event.sender == self.client.user_id
        ):
            reaction_event_id = reaction_event.event_id
            break

    if reaction_event_id is None:
        return

    await matrix_call(
        self.client.room_redact(
            room_id=self.room.room_id,
            event_id=reaction_event_id,
        ),
        error_message="Failed to remove reaction",
    )

edit async

edit(new_body)

Updates the message content to the new text.

Example
@bot.command()
async def typo(ctx: Context):
    msg = await ctx.reply("Helo world!")
    await msg.edit("Hello world!")
Source code in matrix/message.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
async def edit(self, new_body: str) -> None:
    """Updates the message content to the new text.

    ## Example

    ```python
    @bot.command()
    async def typo(ctx: Context):
        msg = await ctx.reply("Helo world!")
        await msg.edit("Hello world!")
    ```
    """
    content = EditContent(new_body, original_event_id=self.event_id)

    await matrix_call(
        self.client.room_send(
            room_id=self.room.room_id,
            message_type="m.room.message",
            content=content.build(),
        ),
        error_message="Failed to edit message",
    )
    self._body = new_body

delete async

delete(reason=None)

Removes the message content from the room. This action cannot be undone.

Optionally provide a reason that will be visible to room moderators.

Example
@bot.command()
async def oops(ctx: Context):
    msg = await ctx.reply("Secret info!")
    await msg.delete()

# Delete with a reason
await message.delete(reason="Violated room rules")
Source code in matrix/message.py
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
async def delete(self, reason: str | None = None) -> None:
    """Removes the message content from the room. This action cannot be undone.

    Optionally provide a reason that will be visible to room moderators.

    ## Example

    ```python
    @bot.command()
    async def oops(ctx: Context):
        msg = await ctx.reply("Secret info!")
        await msg.delete()

    # Delete with a reason
    await message.delete(reason="Violated room rules")
    ```
    """
    await matrix_call(
        self.client.room_redact(
            room_id=self.room.room_id,
            event_id=self.event_id,
            reason=reason,
        ),
        error_message="Failed to delete message",
    )

pin async

pin()

Pin this message to the room.

Example
@bot.command()
async def pin(ctx: Context):
    await ctx.message.pin()
Source code in matrix/message.py
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
async def pin(self) -> None:
    """Pin this message to the room.

    ## Example
    ```python
    @bot.command()
    async def pin(ctx: Context):
        await ctx.message.pin()
    ```
    """
    pinned = await self._fetch_pinned()

    if self.event_id in pinned:
        return

    pinned.append(self.event_id)

    await matrix_call(
        self.client.room_put_state(
            room_id=self.room.room_id,
            event_type="m.room.pinned_events",
            content={"pinned": pinned},
        ),
        error_message="Failed to pin message",
    )

unpin async

unpin()

Unpin this message from the room.

Example
@bot.command()
async def unpin(ctx: Context):
    await ctx.message.unpin()
Source code in matrix/message.py
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
async def unpin(self) -> None:
    """Unpin this message from the room.

    ## Example
    ```python
    @bot.command()
    async def unpin(ctx: Context):
        await ctx.message.unpin()
    ```
    """
    pinned = await self._fetch_pinned()

    if self.event_id not in pinned:
        return

    pinned.remove(self.event_id)

    await matrix_call(
        self.client.room_put_state(
            room_id=self.room.room_id,
            event_type="m.room.pinned_events",
            content={"pinned": pinned},
        ),
        error_message="Failed to unpin message",
    )