init commit
This commit is contained in:
43
app/bot/handlers/utils.py
Normal file
43
app/bot/handlers/utils.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import re
|
||||
from typing import Tuple, Optional, Any
|
||||
from telegram.constants import ChatType
|
||||
from telegram.error import Forbidden, BadRequest
|
||||
|
||||
async def verify_and_fetch_chat(ctx, raw: str | int):
|
||||
"""Return (chat, member, can_post) for the bot in that chat."""
|
||||
bot = ctx.bot
|
||||
|
||||
# Normalize t.me links to @username
|
||||
if isinstance(raw, str) and "t.me/" in raw:
|
||||
raw = raw.strip().split("t.me/")[-1]
|
||||
raw = raw.strip().lstrip("/")
|
||||
if raw and not raw.startswith("@"):
|
||||
raw = "@" + raw
|
||||
|
||||
chat = await bot.get_chat(raw)
|
||||
try:
|
||||
member = await bot.get_chat_member(chat.id, bot.id)
|
||||
except Forbidden:
|
||||
return chat, None, False
|
||||
except BadRequest as e:
|
||||
raise e
|
||||
|
||||
can_post = False
|
||||
if chat.type == ChatType.CHANNEL:
|
||||
status = getattr(member, "status", "")
|
||||
if status in ("administrator", "creator"):
|
||||
flag = getattr(member, "can_post_messages", None)
|
||||
can_post = True if (flag is None or flag is True) else False
|
||||
elif chat.type in (ChatType.SUPERGROUP, ChatType.GROUP):
|
||||
status = getattr(member, "status", "")
|
||||
can_post = status in ("member", "administrator", "creator")
|
||||
return chat, member, can_post
|
||||
|
||||
def parse_chat_id(text: str) -> int | None:
|
||||
m = re.search(r'(-?\d{5,})', text or "")
|
||||
if m:
|
||||
try:
|
||||
return int(m.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
Reference in New Issue
Block a user