understanding commited on
Commit
cb2264a
·
verified ·
1 Parent(s): 9e9ab3f

Create link_parser.py

Browse files
Files changed (1) hide show
  1. bot/core/link_parser.py +41 -0
bot/core/link_parser.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PATH: bot/core/link_parser.py
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Tuple, Union, Optional
6
+
7
+ ChatRef = Union[int, str]
8
+
9
+ _TME_RE = re.compile(
10
+ r"^(?:https?://)?t\.me/(?:(?:c/)?(?P<cchat>\d+)|(?P<user>[A-Za-z0-9_]{4,}))/+(?P<msg>\d+)",
11
+ re.IGNORECASE,
12
+ )
13
+
14
+ def parse_link(link: str) -> Optional[Tuple[ChatRef, int]]:
15
+ if not link:
16
+ return None
17
+ link = link.strip().split("?", 1)[0].rstrip("/")
18
+
19
+ m = _TME_RE.match(link)
20
+ if not m:
21
+ parts = link.strip("/").split("/")
22
+ if len(parts) >= 2:
23
+ chat = parts[-2]
24
+ msg = parts[-1]
25
+ try:
26
+ mid = int(msg)
27
+ except Exception:
28
+ return None
29
+ try:
30
+ cid = int(chat)
31
+ return cid, mid
32
+ except Exception:
33
+ return chat, mid
34
+ return None
35
+
36
+ msg_id = int(m.group("msg"))
37
+ if m.group("cchat"):
38
+ internal = m.group("cchat")
39
+ return int("-100" + internal), msg_id
40
+
41
+ return m.group("user"), msg_id