Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- from typing import Any
- from loguru import logger
- from core.config import settings
- from pydantic_models.group import GroupModel
- from pydantic_models.user import UserModel
- from repositories.user_repo import UserRepository
- class BotManager:
- def __init__(self):
- self.bots: dict[int, Any] = {} # type: ignore
- self.started_bots: dict[int, bool] = {} # type: ignore
- def add_bot(self, bot_id: int, bot: Any):
- self.bots[bot_id] = bot
- logger.debug(
- f"{'User' if bot_id > 0 else 'Group'} {bot_id} added to session combiner"
- )
- def get_bot(self, bot_id: int) -> UserModel | None:
- bot = self.bots.get(bot_id)
- if not bot:
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} not found")
- return None
- return bot
- def get_group(self) -> GroupModel | None:
- bot = self.bots.get(-settings.GROUP_ID)
- if not bot:
- logger.debug("Group not found")
- return None
- return bot
- async def init(self, bot_id: int):
- bot = self.bots.get(bot_id)
- if not bot:
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} not found")
- return
- await bot.init()
- async def start_bot(self, bot_id: int):
- bot = self.bots.get(bot_id)
- if not bot:
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} not found")
- return
- await bot.init()
- await bot.run_bot()
- self.started_bots[bot_id] = True
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} session is started")
- async def stop_bot(self, bot_id: int):
- bot = self.bots.get(bot_id)
- if not bot:
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} not found")
- return False
- await bot.stop_bot()
- self.started_bots[bot_id] = False
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} session is stopped")
- return True
- async def restart_bot(self, bot_id: int):
- bot = self.bots.get(bot_id)
- if not bot:
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} not found")
- return False
- await self.stop_bot(bot_id)
- await self.start_bot(bot_id)
- self.started_bots[bot_id] = True
- logger.debug(
- f"{'User' if bot_id > 0 else 'Group'} {bot_id} session is restarted"
- )
- return True
- async def stop_all_bots(self):
- for bot in self.bots.values():
- await bot.stop_bot()
- logger.debug("All bots stopped")
- async def delete_bot(self, bot_id: int):
- bot = self.bots.get(bot_id)
- if bot:
- await bot.stop_bot()
- del self.bots[bot_id]
- if self.started_bots.get(bot_id):
- del self.started_bots[bot_id]
- await UserRepository.delete_user(user_id=bot_id)
- logger.debug(f"{'User' if bot_id > 0 else 'Group'} {bot_id} session is deleted")
- async def run_health_checks(self):
- while True:
- bot_ids = list(self.bots.keys())
- for bot_id in bot_ids:
- bot = self.bots.get(bot_id)
- if bot:
- await bot.health_check()
- await asyncio.sleep(30)
- bot_manager = BotManager()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement