"""Telegram bot dispatcher and bootstrap.Initializes routers, background tasks, and starts long-polling using aiogram.Reads environment with ``dotenv`` and ensures database is initialized."""importasyncioimportosimportsysfromaiogramimportBot,Dispatcherfromdotenvimportload_dotenvsys.path.append(os.path.join(os.path.dirname(__file__),".."))fromshared.dbimportinit_db,list_completed_tasks_sincefromshared.loggingimportget_loggerfrombot.handlersimport(get_general_router,get_settings_router,get_notifications_router,get_tasks_router,)# Lazy imports will be done inside functionsload_dotenv()BOT_TOKEN=os.getenv("TELEGRAM_BOT_TOKEN")ifnotBOT_TOKEN:raiseValueError("TELEGRAM_BOT_TOKEN not found in environment variables")logger=get_logger(__name__)bot=Bot(token=BOT_TOKEN)dp=Dispatcher()dp.include_router(get_settings_router())dp.include_router(get_notifications_router())dp.include_router(get_tasks_router())dp.include_router(get_general_router())
[docs]asyncdefmain()->None:"""Start the bot dispatcher and background workers. - Ensures database is initialized. - Launches background tasks for analyses and completed task delivery. - Starts long polling. :returns: ``None``. """logger.info("Starting Telegram bot...")awaitinit_db()logger.info("Database initialized for bot")# Start background task to check for new analyseslogger.info("Starting background analysis checker...")frombot.handlers.notificationsimportcheck_new_analysesasyncio.create_task(check_new_analyses(bot))logger.info("Background analysis checker started")logger.info("Telegram bot ready to work")# Start background task to process completed tasks (DB polling)asyncdefcheck_completed_tasks():last_checked_id=0whileTrue:try:tasks=awaitlist_completed_tasks_since(last_checked_id)fortaskintasks:frombot.handlers.notificationsimportprocess_completed_taskawaitprocess_completed_task(bot,task)last_checked_id=max(last_checked_id,task.id)awaitasyncio.sleep(2)exceptExceptionase:logger.error(f"Error in completed tasks checker: {e}")awaitasyncio.sleep(5)asyncio.create_task(check_completed_tasks())# Start the botlogger.info("Starting bot polling...")awaitdp.start_polling(bot)