do not register callbacks every restart

This commit is contained in:
bain 2023-10-27 14:09:52 +02:00
parent 70045efa3e
commit 93aebbf77f
Signed by: bain
GPG key ID: 31F0F25E3BED0B9B

View file

@ -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: