multi-bot finished
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
# bot/management/commands/runbots.py
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
from typing import Sequence
|
||||
from typing import Sequence, Tuple
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from bot.models import TelegramBot
|
||||
from bot.bot_factory import build_application_for_bot
|
||||
from bot.models import TelegramBot, BotConfig
|
||||
from bot.bot_factory import get_all_active_bots_with_configs, build_application_for_bot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -15,19 +16,20 @@ class Command(BaseCommand):
|
||||
def handle(self, *args, **options):
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
# ORM здесь, в синхронном контексте
|
||||
bots: Sequence[TelegramBot] = list(TelegramBot.objects.filter(is_active=True))
|
||||
if not bots:
|
||||
# ВАЖНО: ORM здесь, в синхронном контексте
|
||||
bot_cfg_pairs: Sequence[Tuple[TelegramBot, BotConfig]] = get_all_active_bots_with_configs()
|
||||
if not bot_cfg_pairs:
|
||||
self.stderr.write(self.style.ERROR("Нет активных ботов (is_active=True)."))
|
||||
return
|
||||
|
||||
asyncio.run(self._amain(bots))
|
||||
asyncio.run(self._amain(bot_cfg_pairs))
|
||||
|
||||
async def _amain(self, bots: Sequence[TelegramBot]):
|
||||
async def _amain(self, bot_cfg_pairs: Sequence[Tuple[TelegramBot, BotConfig]]):
|
||||
apps = []
|
||||
try:
|
||||
for tb in bots:
|
||||
app, allowed_updates = build_application_for_bot(tb)
|
||||
# Ни одной ORM-операции тут — только PTB
|
||||
for tb, cfg in bot_cfg_pairs:
|
||||
app, allowed_updates = build_application_for_bot(tb, cfg)
|
||||
await app.initialize()
|
||||
await app.start()
|
||||
await app.updater.start_polling(allowed_updates=allowed_updates)
|
||||
@@ -57,3 +59,4 @@ class Command(BaseCommand):
|
||||
await app.shutdown()
|
||||
except Exception:
|
||||
log.exception("Shutdown error")
|
||||
log.info("All bots stopped gracefully.")
|
||||
Reference in New Issue
Block a user