Implemented syncing

This commit is contained in:
2026-08-18 02:52:38 +03:00
parent 75388d8693
commit 8c1399d781
2 changed files with 33 additions and 5 deletions

View File

@@ -35,16 +35,21 @@ async def main() -> None:
util.log_error("Could't load config")
return
# setup the bot
matrix_bot_config = MatrixBotConfig(
matrix_homeserver_url=cfg.matrix_homeserver,
matrix_username_localpart=cfg.matrix_user,
storage_directory=Path(cfg.store_dir)
)
bot = MatrixBot(matrix_bot_config)
# start the app
bot.start()
# wait for Ctrl+C
await util.get_app_stop_event().wait()
# stop the app
await bot.stop()
if __name__ == "__main__":

View File

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