miltubot devel
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
# bot/management/commands/runbots.py
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
from typing import Sequence
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
from bot.models import TelegramBot
|
||||
from bot.bot_factory import build_application_for_bot
|
||||
@@ -13,27 +14,27 @@ class Command(BaseCommand):
|
||||
|
||||
def handle(self, *args, **options):
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
asyncio.run(self._amain())
|
||||
|
||||
async def _amain(self):
|
||||
bots = list(TelegramBot.objects.filter(is_active=True))
|
||||
# ORM здесь, в синхронном контексте
|
||||
bots: Sequence[TelegramBot] = list(TelegramBot.objects.filter(is_active=True))
|
||||
if not bots:
|
||||
self.stderr.write(self.style.ERROR("Нет активных ботов (is_active=True)."))
|
||||
return
|
||||
|
||||
asyncio.run(self._amain(bots))
|
||||
|
||||
async def _amain(self, bots: Sequence[TelegramBot]):
|
||||
apps = []
|
||||
try:
|
||||
# Инициализация и старт polling для каждого бота
|
||||
for tb in bots:
|
||||
app, allowed_updates = build_application_for_bot(tb)
|
||||
await app.initialize()
|
||||
await app.start()
|
||||
# в 22.x polling запускается через updater
|
||||
await app.updater.start_polling(allowed_updates=allowed_updates)
|
||||
apps.append(app)
|
||||
log.info("Bot started: %s (@%s)", tb.name, tb.username or "—")
|
||||
|
||||
# Ожидание сигнала остановки
|
||||
# Ждём SIGINT/SIGTERM
|
||||
stop_event = asyncio.Event()
|
||||
|
||||
def _stop(*_):
|
||||
@@ -44,13 +45,11 @@ class Command(BaseCommand):
|
||||
try:
|
||||
loop.add_signal_handler(sig, _stop)
|
||||
except NotImplementedError:
|
||||
# Windows
|
||||
pass
|
||||
pass # Windows
|
||||
|
||||
await stop_event.wait()
|
||||
|
||||
finally:
|
||||
# Корректная остановка всех приложений
|
||||
for app in reversed(apps):
|
||||
try:
|
||||
await app.updater.stop()
|
||||
|
||||
Reference in New Issue
Block a user