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
16
17
18
19
20
21
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
56
57
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
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]] = {}

    try:
        async for event in self.client.room_get_event_relations(
            room_id=self.room.room_id,
            event_id=self.event_id,
        ):
            emoji = getattr(event, "key", None)
            sender = getattr(event, "sender", None)

            if emoji and sender:
                raw.setdefault(emoji, []).append(sender)
    except Exception as e:
        raise MatrixError(f"Failed to fetch reactions: {e}")

    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
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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)

    try:
        await self.client.room_send(
            room_id=self.room.room_id,
            message_type="m.reaction",
            content=content.build(),
        )
    except Exception as e:
        raise MatrixError(f"Failed to add reaction: {e}")

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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)

    try:
        await self.client.room_send(
            room_id=self.room.room_id,
            message_type="m.room.message",
            content=content.build(),
        )
        self._body = new_body
    except Exception as e:
        raise MatrixError(f"Failed to edit message: {e}")

delete async

delete()

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

Example
@bot.command()
async def oops(ctx: Context):
    msg = await ctx.reply("Secret info!")
    await msg.delete()
Source code in matrix/message.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
async def delete(self) -> None:
    """Removes the message content from the room. This action cannot be undone.

    ## Example

    ```python
    @bot.command()
    async def oops(ctx: Context):
        msg = await ctx.reply("Secret info!")
        await msg.delete()
    ```
    """
    try:
        await self.client.room_redact(
            room_id=self.room.room_id,
            event_id=self.event_id,
        )
    except Exception as e:
        raise MatrixError(f"Failed to delete message: {e}")