Files
tg_post_min/app/bot/handlers/bind_chat.py
Andrey K. Choi c16ec54891 Bot become a Community Guard & Post send manager
added: dictionary support for censore
message/user management with dict triggers
2025-08-22 21:44:14 +09:00

81 lines
3.0 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.constants import ChatType
from telegram.ext import ContextTypes
from app.db.session import get_session
from app.db.models import User, Chat
from app.bot.messages import BIND_OK, BIND_FAIL_NOT_ADMIN, BIND_FAIL_BOT_RIGHTS, BIND_FAIL_GENERIC
async def bind_chat_cb(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
q = update.callback_query
await q.answer()
data = q.data or ""
if not data.startswith("bind:"):
return
try:
chat_id = int(data.split(":", 1)[1])
except Exception:
await q.edit_message_text(BIND_FAIL_GENERIC)
return
try:
# 1) Проверим, что кликнувший — админ канала
user = update.effective_user
if not user:
await q.edit_message_text(BIND_FAIL_GENERIC)
return
try:
member_user = await ctx.bot.get_chat_member(chat_id, user.id)
if member_user.status not in ("administrator", "creator"):
await q.edit_message_text(BIND_FAIL_NOT_ADMIN)
return
except Exception:
await q.edit_message_text(BIND_FAIL_NOT_ADMIN)
return
# 2) Проверим права бота в канале (должен быть админ с правом постинга)
try:
member_bot = await ctx.bot.get_chat_member(chat_id, ctx.bot.id)
can_post = False
if member_bot.status in ("administrator", "creator"):
flag = getattr(member_bot, "can_post_messages", None)
can_post = True if (flag is None or flag is True) else False
if not can_post:
await q.edit_message_text(BIND_FAIL_BOT_RIGHTS)
return
except Exception:
await q.edit_message_text(BIND_FAIL_BOT_RIGHTS)
return
# 3) Получим инфо о канале и запишем в БД как привязанный
tg_chat = await ctx.bot.get_chat(chat_id)
with get_session() as s:
u = s.query(User).filter_by(tg_id=user.id).first()
if not u:
from app.db.models import User as U
u = U(tg_id=user.id, name=user.full_name)
s.add(u); s.commit(); s.refresh(u)
row = s.query(Chat).filter_by(chat_id=chat_id).first()
if not row:
row = Chat(
chat_id=chat_id,
type=tg_chat.type,
title=tg_chat.title,
owner_user_id=u.id,
can_post=True,
)
s.add(row)
else:
row.title = tg_chat.title
row.type = tg_chat.type
row.owner_user_id = row.owner_user_id or u.id
row.can_post = True
s.commit()
await q.edit_message_text(BIND_OK.format(title=tg_chat.title or chat_id))
except Exception:
await q.edit_message_text(BIND_FAIL_GENERIC)