From cbbafb7778dc54bde1f000938144245789896fb8 Mon Sep 17 00:00:00 2001 From: nikita Date: Sat, 21 Nov 2026 22:20:36 +0300 Subject: [PATCH] Implemented ignoring of events sent before the room was joined - Fixed room bot so that it only sends help message when the message has text in it - Incremeneted database SCHEMA_VERSION, now it's 2 --- examples/room_bot.py | 2 +- src/mab/bot/_callbacks.py | 51 +++++++++++++++++++++++++++++++++++++++ src/mab/bot/_database.py | 33 ++++++++++++++++++++++++- 3 files changed, 84 insertions(+), 2 deletions(-) diff --git a/examples/room_bot.py b/examples/room_bot.py index 0f210a4..855906c 100644 --- a/examples/room_bot.py +++ b/examples/room_bot.py @@ -226,7 +226,7 @@ async def main() -> None: ) # bot.add_callback( - ~SenderIsBotFilter() & NewMessageFilter(), + ~SenderIsBotFilter() & NewMessageFilter() & BodyExistsFilter(), on_help_message ) diff --git a/src/mab/bot/_callbacks.py b/src/mab/bot/_callbacks.py index 255a410..573d662 100644 --- a/src/mab/bot/_callbacks.py +++ b/src/mab/bot/_callbacks.py @@ -7,6 +7,7 @@ from dataclasses import dataclass from nio import AsyncClient from nio import MatrixRoom from nio import MatrixInvitedRoom, InviteMemberEvent, JoinResponse +from nio import RoomGetStateResponse, SyncResponse from nio.events.room_events import Event as RoomEvent from ._database import _Database @@ -42,6 +43,42 @@ class Callbacks: # # PRIVATE # + async def _callback_room_left(self, raw: Any) -> None: + """This callback check if SyncResponse contains info about leaving the + room due to ban, kick or any other reason, and preforms some actions.""" + if not isinstance(raw, list): + raw = [raw] + for resp in raw: + if not isinstance(resp, SyncResponse): + continue + for room_id in resp.rooms.leave: + await self._db.join_timestamp_remove(room_id) + + async def _get_room_join_timestamp(self, room_id: str) -> int | None: + """Gets the room join timestamp.""" + if self._client is None: + raise RuntimeError("Callbacks were not set up") + state = await self._client.room_get_state(room_id) + if not isinstance(state, RoomGetStateResponse): + return None + timestamp = 0 + for event in state.events: + # only m.room.member + if event.get("type") != "m.room.member": + continue + # only describing our state + if event.get("state_key") != self._client.user_id: + continue + # only describing our join state + if event["content"].get("membership") != "join": + continue + if event.get("prev_content") and event["prev_content"].get("membership") not in ("invite", "leave"): + continue + origin_server_ts = event.get("origin_server_ts", 0) + if origin_server_ts > timestamp: + timestamp = origin_server_ts + return timestamp or None + async def _callback_room_event_router(self, room: MatrixRoom, event: RoomEvent) -> None: @@ -50,6 +87,17 @@ class Callbacks: """ if self._config is None or self._client is None: raise RuntimeError("Callbacks were not set up") + # update join time if needed + joined_timestamp = await self._db.join_timestamp_get(room.room_id) + if joined_timestamp is None: + joined_timestamp = await self._get_room_join_timestamp(room.room_id) + if joined_timestamp is not None: + await self._db.join_timestamp_set(room.room_id, joined_timestamp) + else: + return + # do not handle the event if it happened before we joined + if event.server_timestamp < joined_timestamp: + return # build the event context event_context = EventContext( room=room, @@ -131,6 +179,9 @@ class Callbacks: """ if self._config is None or self._client is None: raise RuntimeError("Callbacks were not set up") + self._client.add_response_callback( + self._callback_room_left, # type: ignore + ) # filter-based callback routing self._client.add_event_callback( self._callback_room_event_router, RoomEvent) diff --git a/src/mab/bot/_database.py b/src/mab/bot/_database.py index 19cf68d..062c806 100644 --- a/src/mab/bot/_database.py +++ b/src/mab/bot/_database.py @@ -8,7 +8,7 @@ from ..types import MatrixBotConfig class _Database: """Database interface""" - SCHEMA_VERSION = 1 + SCHEMA_VERSION = 2 """Version of the database schema""" async def _create_tables(self) -> None: @@ -22,6 +22,12 @@ class _Database: "value" ")" ), + ( + "CREATE TABLE IF NOT EXISTS join_timestamps(" + "room_id TEXT UNIQUE ON CONFLICT REPLACE," + "timestamp INTEGER" + ")" + ) ) for statement in STATEMENTS: async with self._conn.execute(statement) as cursor: @@ -81,4 +87,29 @@ class _Database: raise RuntimeError("No connection exists") async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)", (name, value)) as cursor: + await cursor.fetchall() + + async def join_timestamp_get(self, room_id: str) -> int | None: + """Returns the server timestamp when the room was joined (or None).""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("SELECT timestamp FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor: + row = await cursor.fetchone() + if row is None: + return None + return row["timestamp"] + + async def join_timestamp_set(self, room_id: str, timestamp: int) -> None: + """Sets the server timestamp when the room was joined.""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("REPLACE INTO join_timestamps(room_id, timestamp) VALUES(?, ?)", + (room_id, timestamp)) as cursor: + await cursor.fetchall() + + async def join_timestamp_remove(self, room_id: str) -> None: + """Removes the server timestamp when the room was joined.""" + if self._conn is None: + raise RuntimeError("No connection exists") + async with self._conn.execute("DELETE FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor: await cursor.fetchall() \ No newline at end of file