Files
TG_autoposter/app/handlers/callbacks.py
Andrew K. Choi 48f8c6f0eb UserBot Integration Complete: Fixed container startup, integrated UserBot menu to main bot
MAJOR FIXES:
 Fixed UserBot container startup by making TELEGRAM_BOT_TOKEN optional
 Broke circular import chain between app modules
 Made Config.validate() conditional for UserBot-only mode
 Removed unused celery import from userbot_service.py

INTEGRATION:
 UserBot menu now accessible from main bot /start command
 Added 🤖 UserBot button to main keyboard
 Integrated userbot_manager.py handlers:
   - userbot_menu: Main UserBot interface
   - userbot_settings: Configuration
   - userbot_collect_groups: Gather all user groups
   - userbot_collect_members: Parse group members
 UserBot handlers properly registered in ConversationHandler

CONTAINERS:
 tg_autoposter_bot: Running and handling /start commands
 tg_autoposter_userbot: Running as standalone microservice
 All dependent services (Redis, PostgreSQL, Celery workers) operational

STATUS: Bot is fully operational and ready for testing
2025-12-21 12:09:11 +09:00

154 lines
6.3 KiB
Python
Raw Permalink 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 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 = """🤖 <b>Автопостер - Главное меню</b>
Выберите, что вы хотите делать:"""
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 = """📨 <b>Управление сообщениями</b>
Выберите действие:"""
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 = """👥 <b>Управление группами</b>
Выберите действие:"""
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 = "📨 <b>Ваши сообщения:</b>\n\n"
keyboard = []
for msg in messages:
status = "" if msg.is_active else ""
text += f"{status} <b>{msg.title}</b> (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 = "👥 <b>Группы в базе данных:</b>\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} <b>{group.title}</b>\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)
)