Skip to content

Commit e61bf92

Browse files
committed
Add Parser package
Revamped from HTML/Markdown
1 parent be5f0c9 commit e61bf92

3 files changed

Lines changed: 61 additions & 2 deletions

File tree

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,4 @@
1616
# You should have received a copy of the GNU Lesser General Public License
1717
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
1818

19-
from .html import HTML
20-
from .markdown import Markdown
19+
from .parser import Parser

pyrogram/client/parser/parser.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Pyrogram - Telegram MTProto API Client Library for Python
2+
# Copyright (C) 2017-2019 Dan Tès <https://github.com/delivrance>
3+
#
4+
# This file is part of Pyrogram.
5+
#
6+
# Pyrogram is free software: you can redistribute it and/or modify
7+
# it under the terms of the GNU Lesser General Public License as published
8+
# by the Free Software Foundation, either version 3 of the License, or
9+
# (at your option) any later version.
10+
#
11+
# Pyrogram is distributed in the hope that it will be useful,
12+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
# GNU Lesser General Public License for more details.
15+
#
16+
# You should have received a copy of the GNU Lesser General Public License
17+
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
18+
19+
from collections import OrderedDict
20+
from typing import Union
21+
22+
23+
import pyrogram
24+
from .html import HTML
25+
from .markdown import Markdown
26+
27+
28+
class Parser:
29+
def __init__(self, client: Union["pyrogram.BaseClient", None]):
30+
self.html = HTML(client)
31+
self.markdown = Markdown(client)
32+
33+
def parse(self, text: str, mode: str = ""):
34+
if mode is None:
35+
return OrderedDict([
36+
("message", text),
37+
("entities", [])
38+
])
39+
40+
mode = mode.lower()
41+
42+
if mode == "":
43+
return self.markdown.parse(text)
44+
45+
if mode in ["markdown", "md"]:
46+
return self.markdown.parse(text, True)
47+
48+
if mode == "html":
49+
return self.html.parse(text)
50+
51+
@staticmethod
52+
def unparse(text: str, entities: list, is_html: bool):
53+
if is_html:
54+
return HTML.unparse(text, entities)
55+
else:
56+
return Markdown.unparse(text, entities)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,7 @@ def add_surrogates(text):
3535
def remove_surrogates(text):
3636
# Replace each surrogate pair with a SMP code point
3737
return text.encode("utf-16", "surrogatepass").decode("utf-16")
38+
39+
40+
def replace_once(source: str, old: str, new: str, start: int):
41+
return source[:start] + source[start:].replace(old, new, 1)

0 commit comments

Comments
 (0)