do not register callbacks every restart
This commit is contained in:
parent
70045efa3e
commit
93aebbf77f
1 changed files with 19 additions and 0 deletions
|
@ -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:
|
||||
|
|
Loading…
Reference in a new issue