49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
def parse_telegram_target(target: str) -> dict[str, Any] | None:
|
||
|
|
target = target.strip()
|
||
|
|
|
||
|
|
if target.startswith("tg://"):
|
||
|
|
target = target[5:]
|
||
|
|
elif target.startswith("tg:"):
|
||
|
|
target = target[3:]
|
||
|
|
elif target.startswith("telegram://"):
|
||
|
|
target = target[11:]
|
||
|
|
elif target.startswith("telegram:"):
|
||
|
|
target = target[9:]
|
||
|
|
|
||
|
|
if target.lstrip("-").isdigit():
|
||
|
|
return {"chat_id": target, "type": "chat_id"}
|
||
|
|
|
||
|
|
if target.startswith("@"):
|
||
|
|
return {"username": target[1:], "type": "username"}
|
||
|
|
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def parse_messaging_target(target: str) -> dict[str, Any] | None:
|
||
|
|
parts = target.split("/")
|
||
|
|
if len(parts) >= 2:
|
||
|
|
chat_part = parse_telegram_target(parts[0])
|
||
|
|
if chat_part and parts[1].isdigit():
|
||
|
|
return {**chat_part, "thread_id": parts[1]}
|
||
|
|
return parse_telegram_target(target)
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_telegram_chat_id(chat_id: str | int) -> str:
|
||
|
|
return str(chat_id).removeprefix("-100")
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_telegram_target(target: str) -> str:
|
||
|
|
parsed = parse_telegram_target(target)
|
||
|
|
if not parsed:
|
||
|
|
return target
|
||
|
|
if "chat_id" in parsed:
|
||
|
|
return f"tg:{normalize_telegram_chat_id(parsed['chat_id'])}"
|
||
|
|
elif "username" in parsed:
|
||
|
|
return f"tg:@{parsed['username']}"
|
||
|
|
return target
|