Files
new_lottery_bot/src/controllers/bot_controller.py
Andrew K. Choi ec8a23887d
All checks were successful
continuous-integration/drone/push Build is passing
fix: исправлена обработка редактирования розыгрышей
- Добавлен обработчик handle_edit_field для admin_edit_field_{id}_{field} callbacks
- Исправлен toggle_lottery_active - теперь передаёт state вместо None
- Правильный парсинг lottery_id из позиции 3, а не с конца строки
- Обработка 'message is not modified' в bot_controller
- Модифицированы обработчики сообщений для поддержки редактирования
- Добавлен метод update_lottery в LotteryService
- Исправлены ошибки ValueError и AttributeError в меню редактирования
2025-11-22 19:34:30 +09:00

107 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from aiogram.types import Message, CallbackQuery
from aiogram import F
import logging
from src.interfaces.base import IBotController, ILotteryService, IUserService, IKeyboardBuilder, IMessageFormatter
from src.interfaces.base import ILotteryRepository, IParticipationRepository
from src.core.config import ADMIN_IDS
logger = logging.getLogger(__name__)
class BotController(IBotController):
"""Основной контроллер бота"""
def __init__(
self,
lottery_service: ILotteryService,
user_service: IUserService,
keyboard_builder: IKeyboardBuilder,
message_formatter: IMessageFormatter,
lottery_repo: ILotteryRepository,
participation_repo: IParticipationRepository
):
self.lottery_service = lottery_service
self.user_service = user_service
self.keyboard_builder = keyboard_builder
self.message_formatter = message_formatter
self.lottery_repo = lottery_repo
self.participation_repo = participation_repo
def is_admin(self, user_id: int) -> bool:
"""Проверить, является ли пользователь администратором"""
return user_id in ADMIN_IDS
async def handle_start(self, message: Message):
"""Обработать команду /start"""
user = await self.user_service.get_or_create_user(
telegram_id=message.from_user.id,
username=message.from_user.username,
first_name=message.from_user.first_name,
last_name=message.from_user.last_name
)
welcome_text = f"👋 Добро пожаловать, {user.first_name or 'дорогой пользователь'}!\n\n"
welcome_text += "🎲 Это бот для участия в розыгрышах.\n\n"
if user.is_registered:
welcome_text += "✅ Вы уже зарегистрированы в системе!"
else:
welcome_text += "📝 Для участия в розыгрышах необходимо зарегистрироваться."
keyboard = self.keyboard_builder.get_main_keyboard(
is_admin=self.is_admin(message.from_user.id),
is_registered=user.is_registered
)
await message.answer(
welcome_text,
reply_markup=keyboard
)
async def handle_active_lotteries(self, callback: CallbackQuery):
"""Показать активные розыгрыши"""
lotteries = await self.lottery_repo.get_active()
if not lotteries:
await callback.answer("❌ Нет активных розыгрышей", show_alert=True)
return
text = "🎲 **Активные розыгрыши:**\n\n"
for lottery in lotteries:
participants_count = await self.participation_repo.get_count_by_lottery(lottery.id)
lottery_info = self.message_formatter.format_lottery_info(lottery, participants_count)
text += lottery_info + "\n" + "="*30 + "\n\n"
# Получаем информацию о регистрации пользователя
user = await self.user_service.get_or_create_user(
telegram_id=callback.from_user.id,
username=callback.from_user.username,
first_name=callback.from_user.first_name,
last_name=callback.from_user.last_name
)
keyboard = self.keyboard_builder.get_main_keyboard(
is_admin=self.is_admin(callback.from_user.id),
is_registered=user.is_registered
)
try:
await callback.message.edit_text(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
except Exception as e:
# Если сообщение не изменилось - просто отвечаем на callback
if "message is not modified" in str(e):
await callback.answer("✅ Уже показаны активные розыгрыши")
else:
# Другие ошибки - пробуем отправить новое сообщение
await callback.answer()
await callback.message.answer(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)