Files
tg_post_min/app/bot/handlers/join_info.py
2025-08-20 21:10:31 +09:00

52 lines
2.2 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 ChatMemberStatus, ChatType, ParseMode
from telegram.ext import ContextTypes
from app.bot.messages import JOIN_INFO_GROUP, JOIN_INFO_CHANNEL
async def on_my_chat_member(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
"""
Сообщаем инструкцию и chat_id, когда бота добавили в группу/канал
или повысили до администратора.
"""
mcm = update.my_chat_member
if not mcm:
return
chat = mcm.chat
new_status = mcm.new_chat_member.status
if new_status not in (ChatMemberStatus.MEMBER, ChatMemberStatus.ADMINISTRATOR):
return
title = chat.title or str(chat.id)
chat_id = chat.id
# Текст подсказки
if chat.type in (ChatType.GROUP, ChatType.SUPERGROUP):
text = JOIN_INFO_GROUP.format(title=title, chat_id=chat_id)
# Пытаемся написать прямо в группу
try:
await ctx.bot.send_message(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN)
except Exception:
# как запасной вариант — в ЛС пользователю, который добавил
if update.effective_user:
try:
await ctx.bot.send_message(update.effective_user.id, text=text, parse_mode=ParseMode.MARKDOWN)
except Exception:
pass
elif chat.type == ChatType.CHANNEL:
text = JOIN_INFO_CHANNEL.format(title=title, chat_id=chat_id)
# В канале можем не иметь права постинга — пробуем ЛС добавившему
sent = False
try:
# если права даны, сообщим прямо в канал
await ctx.bot.send_message(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN)
sent = True
except Exception:
pass
if not sent and update.effective_user:
try:
await ctx.bot.send_message(update.effective_user.id, text=text, parse_mode=ParseMode.MARKDOWN)
except Exception:
pass