from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, CallbackQueryHandler, MessageHandler, filters from db import AsyncSessionLocal from models import Channel, Group, Button SELECT_TARGET, INPUT_NAME, INPUT_URL = range(3) async def add_button_start(update: Update, context: ContextTypes.DEFAULT_TYPE): # Если выбран канал или группа уже сохранены — сразу переход к названию if context.user_data is None: context.user_data = {} user_data = context.user_data if user_data.get('channel_id'): context.user_data['target'] = f"channel_{user_data['channel_id']}" if update.message: await update.message.reply_text('Введите название кнопки:') return INPUT_NAME elif user_data.get('group_id'): context.user_data['target'] = f"group_{user_data['group_id']}" if update.message: await update.message.reply_text('Введите название кнопки:') return INPUT_NAME # Если нет — стандартный выбор from sqlalchemy import select async with AsyncSessionLocal() as session: result_channels = await session.execute(select(Channel)) channels = result_channels.scalars().all() result_groups = await session.execute(select(Group)) groups = result_groups.scalars().all() keyboard = [] for c in channels: keyboard.append([InlineKeyboardButton(f'Канал: {getattr(c, "name", str(c.name))}', callback_data=f'channel_{getattr(c, "id", str(c.id))}')]) for g in groups: keyboard.append([InlineKeyboardButton(f'Группа: {getattr(g, "name", str(g.name))}', callback_data=f'group_{getattr(g, "id", str(g.id))}')]) if not keyboard: if update.message: await update.message.reply_text('Нет каналов или групп для добавления кнопки.') return ConversationHandler.END if update.message: await update.message.reply_text('Выберите канал или группу:', reply_markup=InlineKeyboardMarkup(keyboard)) context.user_data['keyboard'] = keyboard return SELECT_TARGET async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE): if context.user_data is None: context.user_data = {} query = update.callback_query if query: await query.answer() data = query.data context.user_data['target'] = data await query.edit_message_text('Введите название кнопки:') return INPUT_NAME return ConversationHandler.END async def input_name(update: Update, context: ContextTypes.DEFAULT_TYPE): if context.user_data is None: context.user_data = {} if update.message and hasattr(update.message, 'text'): context.user_data['button_name'] = update.message.text await update.message.reply_text('Введите ссылку для кнопки:') return INPUT_URL return ConversationHandler.END async def input_url(update: Update, context: ContextTypes.DEFAULT_TYPE): url = update.message.text if update.message and hasattr(update.message, 'text') else None name = context.user_data.get('button_name') if context.user_data else None target = context.user_data.get('target') if context.user_data else None if not url or not name or not target or ('_' not in target): if update.message: await update.message.reply_text('Ошибка: не выбран канал или группа. Попробуйте снова.') return ConversationHandler.END session = AsyncSessionLocal() try: type_, obj_id = target.split('_', 1) obj_id = int(obj_id) if type_ == 'channel': button = Button(name=name, url=url, channel_id=obj_id) elif type_ == 'group': button = Button(name=name, url=url, group_id=obj_id) else: if update.message: await update.message.reply_text('Ошибка: неверный тип объекта.') await session.close() return ConversationHandler.END session.add(button) await session.commit() if update.message: await update.message.reply_text('Кнопка добавлена.') except Exception as e: if update.message: await update.message.reply_text(f'Ошибка при добавлении кнопки: {e}') try: type_, obj_id = target.split('_', 1) obj_id = int(obj_id) if type_ == 'channel': button = Button(name=name, url=url, channel_id=obj_id) elif type_ == 'group': button = Button(name=name, url=url, group_id=obj_id) else: await update.message.reply_text('Ошибка: неверный тип объекта.') session.close() return ConversationHandler.END session.add(button) session.commit() from db import log_action user_id = update.effective_user.id if update.effective_user else None log_action(user_id, "add_button", f"type={type_}, obj_id={obj_id}, name={name}, url={url}") await update.message.reply_text('Кнопка добавлена.') except Exception as e: await update.message.reply_text(f'Ошибка при добавлении кнопки: {e}') finally: session.close() return ConversationHandler.END add_button_conv = ConversationHandler( entry_points=[CommandHandler('add_button', add_button_start)], states={ SELECT_TARGET: [CallbackQueryHandler(select_target)], INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_name)], INPUT_URL: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_url)], }, fallbacks=[] )