Make url parameter optional for send_web_page

This commit is contained in:
KurimuzonAkuma 2024-01-17 11:39:00 +03:00
parent 964e156630
commit 4054fff626
2 changed files with 30 additions and 6 deletions

View File

@ -27,8 +27,8 @@ class SendWebPage:
async def send_web_page(
self: "pyrogram.Client",
chat_id: Union[int, str],
url: str,
text: str = None,
url: str = None,
force_large_media: bool = None,
force_small_media: bool = None,
parse_mode: Optional["enums.ParseMode"] = None,
@ -51,7 +51,7 @@ class SendWebPage:
"types.ForceReply"
] = None
) -> "types.Message":
"""Send text Web Page Preview.
"""Send Web Page Preview.
.. include:: /_includes/usable-by/users-bots.rst
@ -61,12 +61,13 @@ class SendWebPage:
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists in your Telegram address book you can use his phone number (str).
url (``str``):
Link that will be previewed.
text (``str``, *optional*):
Text of the message to be sent.
url (``str``, *optional*):
Link that will be previewed.
If url not specified, the first URL found in the text will be used.
parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*):
By default, texts are parsed using both Markdown and HTML styles.
You can combine both syntaxes together.
@ -123,7 +124,7 @@ class SendWebPage:
instructions to remove reply keyboard or to force a reply from the user.
Returns:
:obj:`~pyrogram.types.Message`: On success, the sent text message is returned.
:obj:`~pyrogram.types.Message`: On success, the sent message is returned.
Example:
.. code-block:: python
@ -140,6 +141,19 @@ class SendWebPage:
quote_text, quote_entities = (await utils.parse_text_entities(self, quote_text, parse_mode, quote_entities)).values()
if not url:
if entities:
for entity in entities:
if isinstance(entity, enums.MessageEntityType.URL):
url = entity.url
break
if not url:
url = utils.get_first_url(message)
if not url:
raise ValueError("URL not specified")
r = await self.invoke(
raw.functions.messages.SendMedia(
peer=await self.resolve_peer(chat_id),

View File

@ -25,6 +25,7 @@ import struct
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timezone
from getpass import getpass
import re
from typing import Union, List, Dict, Optional
import pyrogram
@ -462,3 +463,12 @@ def timestamp_to_datetime(ts: Optional[int]) -> Optional[datetime]:
def datetime_to_timestamp(dt: Optional[datetime]) -> Optional[int]:
return int(dt.timestamp()) if dt else None
def get_first_url(text):
text = re.sub(r"^\s*(<[\w<>=\s\"]*>)\s*", r"\1", text)
text = re.sub(r"\s*(</[\w</>]*>)\s*$", r"\1", text)
matches = re.findall(r"(https?):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])", text)
return f"{matches[0][0]}://{matches[0][1]}{matches[0][2]}" if matches else None