Add new set_parse_mode utility method

This commit is contained in:
Dan 2019-07-11 19:28:33 +02:00
parent e1197e066e
commit fed8cbf87e
20 changed files with 109 additions and 19 deletions

View File

@ -136,6 +136,7 @@ def pyrogram_api():
remove_handler
stop_transmission
export_session_string
set_parse_mode
""",
messages="""
Messages

View File

@ -491,6 +491,84 @@ class Client(Methods, BaseClient):
"""
raise Client.StopTransmission
def export_session_string(self):
"""Export the current authorized session as a serialized string.
Session strings are useful for storing in-memory authorized sessions in a portable, serialized string.
More detailed information about session strings can be found at the dedicated page of
:doc:`Storage Engines <../../topics/storage-engines>`.
Has no parameters.
Returns:
``str``: The session serialized into a printable, url-safe string.
Example:
.. code-block:: python
:emphasize-lines: 6
from pyrogram import Client
app = Client("my_account")
with app:
print(app.export_session_string())
"""
return self.storage.export_session_string()
def set_parse_mode(self, parse_mode: Union[str, None] = "combined"):
"""Set the parse mode to be used globally by the client.
When setting the parse mode with this method, all methods having a *parse_mode* parameter will follow the global
value by default. The default value *"combined"* enables both Markdown and HTML styles to be used and combined
together.
Parameters:
parse_mode (``str``):
The new parse mode, can be any of: *"combined"*, for the default combined mode. *"markdown"* or *"md"*
to force Markdown-only styles. *"html"* to force HTML-only styles. *None* to disable the parser
completely.
Raises:
ValueError: In case the provided *parse_mode* is not a valid parse mode.
Example:
.. code-block:: python
:emphasize-lines: 10,14,18,22
from pyrogram import Client
app = Client("my_account")
with app:
# Default combined mode: Markdown + HTML
app.send_message("haskell", "1. **markdown** and <i>html</i>")
# Force Markdown-only, HTML is disabled
app.set_parse_mode("markdown")
app.send_message("haskell", "2. **markdown** and <i>html</i>")
# Force HTML-only, Markdown is disabled
app.set_parse_mode("html")
app.send_message("haskell", "3. **markdown** and <i>html</i>")
# Disable the parser completely
app.set_parse_mode(None)
app.send_message("haskell", "4. **markdown** and <i>html</i>")
# Bring back the default combined mode
app.set_parse_mode()
app.send_message("haskell", "5. **markdown** and <i>html</i>")
"""
if parse_mode not in self.PARSE_MODES:
raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format(
", ".join('"{}"'.format(m) for m in self.PARSE_MODES[:-1]),
parse_mode
))
self.parse_mode = parse_mode
def authorize_bot(self):
try:
r = self.send(

View File

@ -59,6 +59,8 @@ class BaseClient:
WORKDIR = PARENT_DIR
CONFIG_FILE = PARENT_DIR / "config.ini"
PARSE_MODES = ["combined", "markdown", "md", "html", None]
MEDIA_TYPE_ID = {
0: "photo_thumbnail",
1: "chat_photo",
@ -93,6 +95,7 @@ class BaseClient:
self.rnd_id = MsgId
self.parser = Parser(self)
self.parse_mode = "combined"
self.session = None
self.media_sessions = {}

View File

@ -28,7 +28,7 @@ class EditInlineText(BaseClient):
self,
inline_message_id: str,
text: str,
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
disable_web_page_preview: bool = None,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> bool:

View File

@ -29,7 +29,7 @@ class EditMessageText(BaseClient):
chat_id: Union[int, str],
message_id: int,
text: str,
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
disable_web_page_preview: bool = None,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":

View File

@ -32,7 +32,7 @@ class SendAnimation(BaseClient):
animation: str,
caption: str = "",
unsave: bool = False,
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
duration: int = 0,
width: int = 0,
height: int = 0,

View File

@ -31,7 +31,7 @@ class SendAudio(BaseClient):
chat_id: Union[int, str],
audio: str,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
duration: int = 0,
performer: str = None,
title: str = None,

View File

@ -29,7 +29,7 @@ class SendCachedMedia(BaseClient):
chat_id: Union[int, str],
file_id: str,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
disable_notification: bool = None,
reply_to_message_id: int = None,
reply_markup: Union[

View File

@ -32,7 +32,7 @@ class SendDocument(BaseClient):
document: str,
thumb: str = None,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
disable_notification: bool = None,
reply_to_message_id: int = None,
reply_markup: Union[

View File

@ -28,7 +28,7 @@ class SendMessage(BaseClient):
self,
chat_id: Union[int, str],
text: str,
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,

View File

@ -31,7 +31,7 @@ class SendPhoto(BaseClient):
chat_id: Union[int, str],
photo: str,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
ttl_seconds: int = None,
disable_notification: bool = None,
reply_to_message_id: int = None,

View File

@ -31,7 +31,7 @@ class SendVideo(BaseClient):
chat_id: Union[int, str],
video: str,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
duration: int = 0,
width: int = 0,
height: int = 0,

View File

@ -31,7 +31,7 @@ class SendVoice(BaseClient):
chat_id: Union[int, str],
voice: str,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
duration: int = 0,
disable_notification: bool = None,
reply_to_message_id: int = None,

View File

@ -19,7 +19,6 @@
from collections import OrderedDict
from typing import Union
import pyrogram
from .html import HTML
from .markdown import Markdown
@ -27,12 +26,16 @@ from .markdown import Markdown
class Parser:
def __init__(self, client: Union["pyrogram.BaseClient", None]):
self.client = client
self.html = HTML(client)
self.markdown = Markdown(client)
def parse(self, text: str, mode: str = ""):
def parse(self, text: str, mode: Union[str, None] = object):
text = str(text or "").strip()
if mode == object:
mode = self.client.parse_mode
if mode is None:
return OrderedDict([
("message", text),
@ -41,7 +44,7 @@ class Parser:
mode = mode.lower()
if mode == "":
if mode == "combined":
return self.markdown.parse(text)
if mode in ["markdown", "md"]:
@ -50,6 +53,11 @@ class Parser:
if mode == "html":
return self.html.parse(text)
raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format(
", ".join('"{}"'.format(m) for m in self.client.PARSE_MODES[:-1]),
mode
))
@staticmethod
def unparse(text: str, entities: list, is_html: bool):
if is_html:

View File

@ -63,7 +63,7 @@ class InputMediaAnimation(InputMedia):
media: str,
thumb: str = None,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
width: int = 0,
height: int = 0,
duration: int = 0

View File

@ -65,7 +65,7 @@ class InputMediaAudio(InputMedia):
media: str,
thumb: str = None,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
duration: int = 0,
performer: int = "",
title: str = ""

View File

@ -54,7 +54,7 @@ class InputMediaDocument(InputMedia):
media: str,
thumb: str = None,
caption: str = "",
parse_mode: Union[str, None] = ""
parse_mode: Union[str, None] = object
):
super().__init__(media, caption, parse_mode)

View File

@ -49,6 +49,6 @@ class InputMediaPhoto(InputMedia):
self,
media: str,
caption: str = "",
parse_mode: Union[str, None] = ""
parse_mode: Union[str, None] = object
):
super().__init__(media, caption, parse_mode)

View File

@ -68,7 +68,7 @@ class InputMediaVideo(InputMedia):
media: str,
thumb: str = None,
caption: str = "",
parse_mode: Union[str, None] = "",
parse_mode: Union[str, None] = object,
width: int = 0,
height: int = 0,
duration: int = 0,

View File

@ -43,7 +43,7 @@ class InputTextMessageContent(InputMessageContent):
__slots__ = ["message_text", "parse_mode", "disable_web_page_preview"]
def __init__(self, message_text: str, parse_mode: Union[str, None] = "", disable_web_page_preview: bool = None):
def __init__(self, message_text: str, parse_mode: Union[str, None] = object, disable_web_page_preview: bool = None):
super().__init__()
self.message_text = message_text