64 lines
2.8 KiB
Python
64 lines
2.8 KiB
Python
|
||
from telegram import Update
|
||
from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
|
||
from db import AsyncSessionLocal
|
||
from models import Channel
|
||
|
||
INPUT_NAME, INPUT_LINK = range(2)
|
||
|
||
async def add_channel_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
if context.user_data is None:
|
||
context.user_data = {}
|
||
if update.message:
|
||
await update.message.reply_text('Введите имя канала:')
|
||
return INPUT_NAME
|
||
|
||
async def input_channel_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
if context.user_data is None:
|
||
context.user_data = {}
|
||
text = update.message.text.strip() if update.message and update.message.text else ''
|
||
context.user_data['channel_name'] = text
|
||
if update.message:
|
||
await update.message.reply_text('Теперь отправьте ссылку на канал (должна начинаться с @):')
|
||
return INPUT_LINK
|
||
|
||
async def input_channel_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
if context.user_data is None:
|
||
context.user_data = {}
|
||
link = update.message.text.strip() if update.message and update.message.text else ''
|
||
if not link.startswith('@'):
|
||
if update.message:
|
||
await update.message.reply_text('Ошибка: ссылка на канал должна начинаться с @. Попробуйте снова.')
|
||
return INPUT_LINK
|
||
context.user_data['channel_link'] = link
|
||
return await save_channel(update, context)
|
||
|
||
async def save_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
if context.user_data is None:
|
||
context.user_data = {}
|
||
name = context.user_data.get('channel_name')
|
||
link = context.user_data.get('channel_link')
|
||
if not name or not link:
|
||
if update.message:
|
||
await update.message.reply_text('Ошибка: не указано название или ссылка.')
|
||
return ConversationHandler.END
|
||
async with AsyncSessionLocal() as session:
|
||
channel = Channel(name=name, link=link)
|
||
session.add(channel)
|
||
await session.commit()
|
||
from db import log_action
|
||
user_id = update.effective_user.id if update.effective_user else None
|
||
await log_action(user_id, "add_channel", f"name={name}, link={link}")
|
||
if update.message:
|
||
await update.message.reply_text(f'Канал "{name}" добавлен.')
|
||
return ConversationHandler.END
|
||
|
||
add_channel_conv = ConversationHandler(
|
||
entry_points=[CommandHandler('add_channel', add_channel_start)],
|
||
states={
|
||
INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_channel_name)],
|
||
INPUT_LINK: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_channel_link)],
|
||
},
|
||
fallbacks=[]
|
||
)
|