-
Notifications
You must be signed in to change notification settings - Fork 0
/
ext.py
43 lines (35 loc) · 1.26 KB
/
ext.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import re
from dataclasses import dataclass
from typing import List, Optional
@dataclass(frozen=True)
class InlineCommand:
"""Represents a command parsed from an inline query string."""
name: str
"""Name of the command."""
value: Optional[str] = None
"""Value of the command (if any)."""
@dataclass(frozen=True)
class ParsedQuery:
"""Represents a parsed query object from an inline query string."""
text: str
"""The original query string that was parsed."""
query: str
"""The query string without the commands."""
commands: Optional[List[InlineCommand]] = None
"""A list of :class:`InlineCommand` objects parsed from the query (if any)."""
def parse_query(text: str) -> ParsedQuery:
"""Return a parsed query object from the given query string.
Args:
- text (`str`): The query string to parse.
Returns:
- `ParsedQuery`: A parsed query object.
"""
cmd_pattern = r"([0-9a-zA-Z_]+):([^\s]*)"
commands = re.findall(cmd_pattern, text)
if commands:
commands = [
InlineCommand(name, value)
for name, value in commands
]
query = re.sub(cmd_pattern, "", text).strip()
return ParsedQuery(text, query, commands)