Files
post_bot/handlers/add_group.py
Choi A.K. 86f7c65697
Some checks failed
continuous-integration/drone/push Build is failing
Merge branch 'main' into security
2025-09-07 14:22:04 +09:00

178 lines
6.8 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 telegram import Update
# from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
# from db import AsyncSessionLocal
# from models import Group
# INPUT_NAME, INPUT_LINK = range(2)
# async def add_group_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_group_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['group_name'] = text
# if update.message:
# await update.message.reply_text('Теперь отправьте chat_id группы (например, -1001234567890):')
# return INPUT_LINK
# async def input_group_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('-100'):
# if update.message:
# await update.message.reply_text('Ошибка: chat_id группы должен начинаться с -100. Попробуйте снова.')
# return INPUT_LINK
# context.user_data['group_link'] = link
# return await save_group(update, context)
# async def save_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
# if context.user_data is None:
# context.user_data = {}
# name = context.user_data.get('group_name')
# link = context.user_data.get('group_link')
# if not name or not link:
# if update.message:
# await update.message.reply_text('Ошибка: не указано название или ссылка.')
# return ConversationHandler.END
# async with AsyncSessionLocal() as session:
# group = Group(name=name, link=link)
# session.add(group)
# await session.commit()
# if update.message:
# await update.message.reply_text(f'Группа "{name}" добавлена.')
# return ConversationHandler.END
# add_group_conv = ConversationHandler(
# entry_points=[CommandHandler('add_group', add_group_start)],
# states={
# INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_name)],
# INPUT_LINK: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_link)],
# },
# fallbacks=[]
# )
# handlers/add_group.py
from telegram import Update
from telegram.ext import (
ContextTypes,
ConversationHandler,
CommandHandler,
MessageHandler,
filters,
)
from sqlalchemy import select
from db import AsyncSessionLocal
from models import Group, Admin
INPUT_NAME, INPUT_LINK = range(2)
async def add_group_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_group_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
return ConversationHandler.END
name = (update.message.text or "").strip()
if not name:
await update.message.reply_text("Имя не может быть пустым. Введите имя группы:")
return INPUT_NAME
context.user_data["group_name"] = name
await update.message.reply_text('Отправьте ссылку на группу (формат "@username" или "-100..."):')
return INPUT_LINK
async def _get_or_create_admin(session: AsyncSessionLocal, tg_id: int) -> Admin:
res = await session.execute(select(Admin).where(Admin.tg_id == tg_id))
admin = res.scalar_one_or_none()
if not admin:
admin = Admin(tg_id=tg_id)
session.add(admin)
# Чтобы получить admin.id до commit
await session.flush()
return admin
async def input_group_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
return ConversationHandler.END
link = (update.message.text or "").strip()
if not (link.startswith("@") or link.startswith("-100")):
await update.message.reply_text(
'Неверный формат. Укажите "@username" (публичная группа/супергруппа) или "-100..." (ID).'
)
return INPUT_LINK
name = (context.user_data or {}).get("group_name", "").strip()
if not name:
await update.message.reply_text("Не найдено имя группы. Начните заново: /add_group")
return ConversationHandler.END
user = update.effective_user
if not user:
await update.message.reply_text("Не удалось определить администратора. Попробуйте ещё раз.")
return ConversationHandler.END
async with AsyncSessionLocal() as session:
<<<<<<< HEAD
group = Group(name=name, link=link)
session.add(group)
await session.commit()
from db import log_action
user_id = update.effective_user.id if update.effective_user else None
log_action(user_id, "add_group", f"name={name}, link={link}")
if update.message:
await update.message.reply_text(f'Группа "{name}" добавлена.')
=======
# гарантируем наличие админа
admin = await _get_or_create_admin(session, user.id)
# проверка на существование группы по ссылке
existing_q = await session.execute(select(Group).where(Group.link == link))
existing = existing_q.scalar_one_or_none()
if existing:
existing.name = name
existing.admin_id = admin.id
await session.commit()
await update.message.reply_text(
f'Группа "{name}" уже была в базе — обновил владельца и имя.'
)
else:
group = Group(name=name, link=link, admin_id=admin.id)
session.add(group)
await session.commit()
await update.message.reply_text(f'Группа "{name}" добавлена и привязана к вашему админ-аккаунту.')
>>>>>>> main
return ConversationHandler.END
add_group_conv = ConversationHandler(
entry_points=[CommandHandler("add_group", add_group_start)],
states={
INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_name)],
INPUT_LINK: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_link)],
},
fallbacks=[],
)