from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes
from app.database import AsyncSessionLocal
from app.database.repository import GroupRepository, MessageRepository, MessageGroupRepository
from app.utils.keyboards import (
get_main_keyboard, get_back_keyboard, get_message_actions_keyboard,
get_group_actions_keyboard, CallbackType
)
import logging
logger = logging.getLogger(__name__)
async def start_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Главное меню"""
query = update.callback_query
logger.info(f"🔘 Получена кнопка MAIN_MENU от пользователя {update.effective_user.id}")
await query.answer()
text = """🤖 Автопостер - Главное меню
Выберите, что вы хотите делать:"""
await query.edit_message_text(
text,
parse_mode='HTML',
reply_markup=get_main_keyboard()
)
async def manage_messages(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Меню управления сообщениями"""
try:
query = update.callback_query
logger.info(f"🔘 Получена кнопка MANAGE_MESSAGES от пользователя {update.effective_user.id}")
await query.answer()
text = """📨 Управление сообщениями
Выберите действие:"""
keyboard = [
[InlineKeyboardButton("➕ Новое сообщение", callback_data=CallbackType.CREATE_MESSAGE.value)],
[InlineKeyboardButton("📜 Список сообщений", callback_data=CallbackType.LIST_MESSAGES.value)],
[InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MAIN_MENU.value)],
]
await query.edit_message_text(
text,
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(keyboard)
)
logger.info(f"✅ Сообщение обновлено для manage_messages")
except Exception as e:
logger.error(f"❌ Ошибка в manage_messages: {e}", exc_info=True)
async def manage_groups(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Меню управления группами"""
try:
query = update.callback_query
logger.info(f"🔘 Получена кнопка MANAGE_GROUPS от пользователя {update.effective_user.id}")
await query.answer()
text = """👥 Управление группами
Выберите действие:"""
keyboard = [
[InlineKeyboardButton("📜 Список групп", callback_data=CallbackType.LIST_GROUPS.value)],
[InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MAIN_MENU.value)],
]
await query.edit_message_text(
text,
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(keyboard)
)
logger.info(f"✅ Сообщение обновлено для manage_groups")
except Exception as e:
logger.error(f"❌ Ошибка в manage_groups: {e}", exc_info=True)
async def list_messages(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Список всех сообщений"""
query = update.callback_query
logger.info(f"🔘 Получена кнопка LIST_MESSAGES от пользователя {update.effective_user.id}")
await query.answer()
async with AsyncSessionLocal() as session:
repo = MessageRepository(session)
messages = await repo.get_all_messages()
if not messages:
text = "📭 Нет сообщений"
keyboard = [[InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MANAGE_MESSAGES.value)]]
else:
text = "📨 Ваши сообщения:\n\n"
keyboard = []
for msg in messages:
status = "✅" if msg.is_active else "❌"
text += f"{status} {msg.title} (ID: {msg.id})\n"
keyboard.append([
InlineKeyboardButton(f"📤 {msg.title}", callback_data=f"send_msg_{msg.id}"),
InlineKeyboardButton("🗑️", callback_data=f"delete_msg_{msg.id}")
])
keyboard.append([InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MANAGE_MESSAGES.value)])
await query.edit_message_text(
text,
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def list_groups(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Список всех групп"""
query = update.callback_query
logger.info(f"🔘 Получена кнопка LIST_GROUPS от пользователя {update.effective_user.id}")
await query.answer()
async with AsyncSessionLocal() as session:
repo = GroupRepository(session)
groups = await repo.get_all_active_groups()
if not groups:
text = "👥 Нет групп в базе данных\n\nДобавьте бота в группы - они автоматически появятся здесь."
keyboard = [[InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MANAGE_GROUPS.value)]]
else:
text = "👥 Группы в базе данных:\n\n"
keyboard = []
for group in groups:
status = "✅" if group.is_active else "❌"
delay = f"⏱️ {group.slow_mode_delay}s" if group.slow_mode_delay > 0 else "🚀 нет"
text += f"{status} {group.title}\n"
text += f" ID: {group.chat_id}\n"
text += f" {delay}\n\n"
keyboard.append([
InlineKeyboardButton(f"📝 {group.title}", callback_data=f"group_messages_{group.id}"),
InlineKeyboardButton("🗑️", callback_data=f"delete_group_{group.id}")
])
keyboard.append([InlineKeyboardButton("⬅️ Назад", callback_data=CallbackType.MANAGE_GROUPS.value)])
await query.edit_message_text(
text,
parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(keyboard)
)