from django.core.management.base import BaseCommand, CommandError from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ChatMemberHandler, filters from django.db import transaction from bot.models import TelegramBot, BotConfig from bot.handlers import on_my_chat_member, upsert_chat_from_update async def cmd_start(update, context): await upsert_chat_from_update(update, context) await update.message.reply_text("Я на связи. Добавьте меня в группу — запомню чат автоматически.") async def cmd_groups(update, context): """ /groups — покажем список чатов, где бот сейчас состоит. (Лучше ограничить доступ: например, только admin_user_ids из BotConfig) """ bot_conf = await context.application.bot_data.get("bot_conf") admin_ids = bot_conf.admin_user_ids if bot_conf else [] if update.effective_user and admin_ids and update.effective_user.id not in admin_ids: return from bot.models import TelegramChat qs = TelegramChat.objects.filter(is_member=True).exclude(type="private").order_by("type", "title") if not qs.exists(): await update.message.reply_text("Пока ни одной группы/канала не найдено.") return lines = [] for ch in qs: label = ch.title or ch.username or ch.id lines.append(f"• {label} [{ch.type}] — {ch.id}") await update.message.reply_text("\n".join(lines)[:3900]) class Command(BaseCommand): help = "Запуск телеграм-бота (polling) на основе активного TelegramBot" def add_arguments(self, parser): parser.add_argument("--bot-id", type=int, help="ID TelegramBot (если не указан — берём первый активный)") def handle(self, *args, **options): bot_id = options.get("bot_id") try: if bot_id: bot = TelegramBot.objects.get(id=bot_id, is_active=True) else: bot = TelegramBot.objects.filter(is_active=True).first() if not bot: raise CommandError("Нет активного TelegramBot.") except TelegramBot.DoesNotExist: raise CommandError("Указанный TelegramBot не найден или неактивен.") conf = getattr(bot, "config", None) app = ApplicationBuilder().token(bot.token).build() # Сохраним конфиг в bot_data, чтобы был доступ в хендлерах: app.bot_data["bot_conf"] = conf # Команды app.add_handler(CommandHandler("start", cmd_start)) app.add_handler(CommandHandler("groups", cmd_groups)) # Обновление списка чатов при изменении статуса бота app.add_handler(ChatMemberHandler(on_my_chat_member, ChatMemberHandler.MY_CHAT_MEMBER)) # Любые входящие сообщения — обновляем last_message_at для чатов app.add_handler(MessageHandler(filters.ALL, upsert_chat_from_update)) # allowed_updates (если заданы в конфиге) allowed_updates = conf.allowed_updates if conf and conf.allowed_updates else None self.stdout.write(self.style.SUCCESS(f"Бот {bot} запущен (polling).")) app.run_polling(allowed_updates=allowed_updates, drop_pending_updates=True)