Files
stcs/run.py
2025-10-12 15:05:50 +05:00

57 lines
1.7 KiB
Python

import asyncio
import contextlib
import logging.config
from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.redis import RedisStorage
from database import init_db
from app.bybit.web_socket import WebSocketBot
from app.telegram.handlers import router
from config import BOT_TOKEN
from logger_helper.logger_helper import LOGGING_CONFIG
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("run")
async def main():
"""
The main function of launching the bot.
Performs database initialization, creation of bot and dispatcher objects,
then it triggers the long polling event.
Logs important events and errors.
"""
try:
await init_db()
bot = Bot(token=BOT_TOKEN)
storage = RedisStorage.from_url("redis://localhost:6379")
dp = Dispatcher(storage=storage)
dp.include_router(router)
web_socket = WebSocketBot(telegram_bot=bot)
await web_socket.clear_user_sockets()
ws_task = asyncio.create_task(web_socket.run_user_check_loop())
tg_task = asyncio.create_task(dp.start_polling(bot))
try:
logger.info("Bot started")
await asyncio.gather(ws_task, tg_task)
except Exception as e:
logger.error("Bot stopped with error: %s", e)
finally:
for task in (ws_task, tg_task):
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ws_task
await tg_task
await web_socket.clear_user_sockets()
except Exception as e:
logger.error("Bot stopped with error: %s", e)
if __name__ == "__main__":
asyncio.run(main())