From 93aebbf77f805ff19fbbd67f420bfe300c3ba73c Mon Sep 17 00:00:00 2001 From: bain Date: Fri, 27 Oct 2023 14:09:52 +0200 Subject: [PATCH] do not register callbacks every restart --- matrix-invitation-dealer/main.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/matrix-invitation-dealer/main.py b/matrix-invitation-dealer/main.py index 4f48c15..3e4f5ea 100644 --- a/matrix-invitation-dealer/main.py +++ b/matrix-invitation-dealer/main.py @@ -33,7 +33,12 @@ class Bot: # FIXME: weird hack because we get the same event twice when we join a room self.seen_events: Deque[str] = deque(maxlen=20) + self.callback_inhibitor = True + async def invite_callback(self, room: MatrixRoom, event: InviteMemberEvent): + if self.callback_inhibitor: + return + if ( event.membership == "invite" and event.state_key == self.client.user_id # event about me @@ -49,6 +54,9 @@ class Bot: async def room_member_update_callback( self, room: MatrixRoom, event: RoomMemberEvent ): + if self.callback_inhibitor: + return + if event.event_id in self.seen_events: return else: @@ -66,6 +74,9 @@ class Bot: await self.leave(room) async def room_message_callback(self, room: MatrixRoom, event: RoomMessage): + if self.callback_inhibitor: + return + if type(room) is not MatrixRoom or event.sender == self.client.user_id: return @@ -206,8 +217,11 @@ class Bot: async def main(self): await self.client.synced.wait() + self.callback_inhibitor = False + logger.info("logged in as %s !", self.client.user_id) + def register_callbacks(self): self.client.add_event_callback(self.invite_callback, (InviteMemberEvent,)) # type: ignore self.client.add_event_callback(self.room_member_update_callback, (RoomMemberEvent,)) # type: ignore self.client.add_event_callback(self.room_message_callback, (RoomMessage,)) # type: ignore @@ -219,8 +233,12 @@ class Bot: ) self.db = await aiosqlite.connect(env.DATABASE_FILE) + self.register_callbacks() + while True: + self.callback_inhibitor = True future = asyncio.gather(self.client.sync_forever(30_000), self.main()) + try: await asyncio.shield(future) except asyncio.CancelledError: @@ -228,6 +246,7 @@ class Bot: # and then gracefully shutdown all connections logger.info("Gracefully shutting down") + await self.db_lock.acquire() try: