Implemented syncing
This commit is contained in:
33
new_bot.py
33
new_bot.py
@@ -23,6 +23,7 @@ class MatrixBot:
|
||||
by yourself.
|
||||
"""
|
||||
NEXT_BATCH_DUMP_PERIOD = 120.0
|
||||
MATRIX_SYNC_PERIOD = 5000
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
@@ -263,6 +264,23 @@ class MatrixBot:
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
async def _client_cancellable_sync_forever(self, *args, **kwargs) -> Any:
|
||||
"""Behaves exactly like AsyncClient.sync_forever, but supports task cancellation"""
|
||||
sync_forever_task = asyncio.create_task(
|
||||
self._client.sync_forever(*args, **kwargs)
|
||||
)
|
||||
try:
|
||||
return await sync_forever_task
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
self._client.stop_sync_forever()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
sync_forever_task.cancel()
|
||||
await asyncio.gather(sync_forever_task, return_exceptions=True)
|
||||
raise
|
||||
|
||||
async def _background_coroutine(self) -> None:
|
||||
"""This function implements bot lifecycle."""
|
||||
# we should stop when this task stops
|
||||
@@ -281,13 +299,18 @@ class MatrixBot:
|
||||
except:
|
||||
traceback.print_exc()
|
||||
self._logger.info("Succesfully logged in")
|
||||
# test
|
||||
wait_task = asyncio.create_task(asyncio.sleep(100000))
|
||||
# sync forever
|
||||
self._logger.info("Syncing forever")
|
||||
sync_task = asyncio.create_task(
|
||||
self._client_cancellable_sync_forever(
|
||||
timeout=self.MATRIX_SYNC_PERIOD,
|
||||
since=(await self._read_next_batch())
|
||||
)
|
||||
)
|
||||
try:
|
||||
self._logger.info("Bot is not implemented yet, sleeping forever")
|
||||
await self._wait_for_task_and_stop_event(wait_task, stop_wait_task)
|
||||
await self._wait_for_task_and_stop_event(sync_task, stop_wait_task)
|
||||
except asyncio.CancelledError:
|
||||
self._logger.info("Background task is cancelled during eternal sleep")
|
||||
self._logger.debug("Sync task is cancelled")
|
||||
await self._client_destroy()
|
||||
return
|
||||
except:
|
||||
|
||||
Reference in New Issue
Block a user