Files
new_lottery_bot/src/controllers/bot_controller.py
Andrey K. Choi 0fdad07d82
Some checks failed
continuous-integration/drone/pr Build is failing
refactor
2026-02-17 00:22:42 +09:00

122 lines
5.1 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"""
from src.utils.keyboards import get_main_reply_keyboard
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 += "📝 Для участия в розыгрышах необходимо зарегистрироваться."
# Inline клавиатура
inline_keyboard = self.keyboard_builder.get_main_keyboard(
is_admin=self.is_admin(message.from_user.id),
is_registered=user.is_registered
)
# Обычная клавиатура
reply_keyboard = get_main_reply_keyboard(
is_admin=self.is_admin(message.from_user.id),
is_registered=user.is_registered
)
await message.answer(
welcome_text,
reply_markup=reply_keyboard # Обычная клавиатура
)
# Отправляем inline клавиатуру отдельным сообщением
await message.answer(
"Выберите действие:",
reply_markup=inline_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"
)