From 19ce22088074a197254ae9c4a6fdd07914c9e435 Mon Sep 17 00:00:00 2001
From: anonymousx97 <88324835+anonymousx97@users.noreply.github.com>
Date: Sun, 15 Dec 2024 16:16:13 +0530
Subject: [PATCH 01/14] feat: use lib side check of valid lengths and prevent
invalid requests being sent.
New Checks in:
send_message
edit_message text/caption
set_administrator_title
update_profile (bio)
---
.../methods/chats/set_administrator_title.py | 4 +++-
.../methods/messages/edit_inline_caption.py | 5 ++++-
pyrogram/methods/messages/edit_inline_text.py | 3 +++
.../methods/messages/edit_message_caption.py | 12 +++++++++++-
pyrogram/methods/messages/edit_message_text.py | 3 +++
pyrogram/methods/messages/send_message.py | 3 +++
pyrogram/methods/users/update_profile.py | 15 +++++++++------
pyrogram/utils.py | 17 +++++++++++++++++
8 files changed, 53 insertions(+), 9 deletions(-)
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index 2c77066ed7..e1334bb10b 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -19,7 +19,7 @@
from typing import Union
import pyrogram
-from pyrogram import raw
+from pyrogram import raw, utils
class SetAdministratorTitle:
@@ -56,6 +56,8 @@ async def set_administrator_title(
await app.set_administrator_title(chat_id, user_id, "Admin Title")
"""
+ utils.check_valid_length(text=title, arg_type="title", max_length=utils.MAX_ADMIN_RANK_LEN)
+
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/edit_inline_caption.py b/pyrogram/methods/messages/edit_inline_caption.py
index fd2f9442ce..15f2c5abea 100644
--- a/pyrogram/methods/messages/edit_inline_caption.py
+++ b/pyrogram/methods/messages/edit_inline_caption.py
@@ -19,7 +19,7 @@
from typing import Optional, List
import pyrogram
-from pyrogram import types, enums
+from pyrogram import types, enums, utils
class EditInlineCaption:
@@ -70,6 +70,9 @@ async def edit_inline_caption(
link_preview_options = types.LinkPreviewOptions(
show_above_text=show_caption_above_media
)
+
+ utils.check_valid_length(text=caption, arg_type="caption", max_length=utils.MAX_CAPTION_LEN)
+
return await self.edit_inline_text(
inline_message_id=inline_message_id,
text=caption,
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index 2f0dd30ef1..2f13a6bf6b 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -80,6 +80,9 @@ async def edit_inline_text(
)
)
"""
+
+ utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
+
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
diff --git a/pyrogram/methods/messages/edit_message_caption.py b/pyrogram/methods/messages/edit_message_caption.py
index 6752d00258..1cbe4f714d 100644
--- a/pyrogram/methods/messages/edit_message_caption.py
+++ b/pyrogram/methods/messages/edit_message_caption.py
@@ -20,7 +20,7 @@
from typing import Union, List, Optional
import pyrogram
-from pyrogram import types, enums
+from pyrogram import types, enums, utils
class EditMessageCaption:
@@ -85,6 +85,16 @@ async def edit_message_caption(
show_above_text=show_caption_above_media
)
+ pyrogram.utils.check_valid_length(
+ text=caption,
+ arg_type="caption",
+ max_length=(
+ utils.MAX_PREMIUM_CAPTION_LEN
+ if self.me.is_premium
+ else utils.MAX_CAPTION_LEN
+ ),
+ )
+
return await self.edit_message_text(
chat_id=chat_id,
message_id=message_id,
diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py
index 62ad47f507..6ce4cf8bdb 100644
--- a/pyrogram/methods/messages/edit_message_text.py
+++ b/pyrogram/methods/messages/edit_message_text.py
@@ -94,6 +94,9 @@ async def edit_message_text(
)
)
"""
+
+ utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
+
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index 21044d6149..a28913ac8c 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -153,6 +153,9 @@ async def send_message(
[InlineKeyboardButton("Docs", url="https://docs.pyrogram.org")]
]))
"""
+
+ utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
+
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index 0ec7ee969c..2f4b4aeba8 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -17,16 +17,16 @@
# along with Pyrogram. If not, see .
import pyrogram
-from pyrogram import raw
+from pyrogram import raw, utils
class UpdateProfile:
async def update_profile(
- self: "pyrogram.Client",
- *,
- first_name: str = None,
- last_name: str = None,
- bio: str = None
+ self: "pyrogram.Client",
+ *,
+ first_name: str = None,
+ last_name: str = None,
+ bio: str = None
) -> bool:
"""Update your profile details such as first name, last name and bio.
@@ -62,6 +62,9 @@ async def update_profile(
# Remove the last name
await app.update_profile(last_name="")
"""
+ if bio:
+ utils.check_valid_length(text=bio, arg_type="bio",
+ max_length=utils.MAX_PREMIUM_USER_BIO_LEN if self.me.is_premium else utils.MAX_USER_BIO_LEN)
return bool(
await self.invoke(
diff --git a/pyrogram/utils.py b/pyrogram/utils.py
index 52a62d8aa5..711932ab5a 100644
--- a/pyrogram/utils.py
+++ b/pyrogram/utils.py
@@ -245,6 +245,23 @@ def unpack_inline_message_id(inline_message_id: str) -> "raw.base.InputBotInline
MAX_USER_ID_OLD = 2147483647
MAX_USER_ID = 999999999999
+MAX_CAPTION_LEN = 1024
+MAX_PREMIUM_CAPTION_LEN = 4096
+MAX_USER_BIO_LEN = 70
+MAX_PREMIUM_USER_BIO_LEN = 140
+MAX_MESSAGE_TEXT_LEN = 4096
+MAX_ADMIN_RANK_LEN = 16
+
+
+def check_valid_length(text: str, arg_type: str, max_length: int):
+ if not isinstance(text, str):
+ raise ValueError(f"Argument {arg_type} must be a str")
+
+ text_length = len(text)
+
+ assert bool(0 < text_length <= max_length), \
+ f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: 1-{max_length}"
+
def get_raw_peer_id(peer: raw.base.Peer) -> Optional[int]:
"""Get the raw peer id from a Peer object"""
From 11de34919e5ceb181522882c9e5fb770d55bcad9 Mon Sep 17 00:00:00 2001
From: Shrimadhav U K
Date: Mon, 16 Dec 2024 10:59:23 +0530
Subject: [PATCH 02/14] minor change in Constants
---
.../methods/chats/set_administrator_title.py | 9 ++--
.../methods/messages/edit_inline_caption.py | 2 -
pyrogram/methods/messages/edit_inline_text.py | 10 ++++-
.../methods/messages/edit_message_caption.py | 10 -----
.../methods/messages/edit_message_text.py | 10 ++++-
pyrogram/methods/messages/send_message.py | 6 ++-
pyrogram/methods/users/update_profile.py | 12 +++++-
pyrogram/utils.py | 43 +++++++++++--------
8 files changed, 62 insertions(+), 40 deletions(-)
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index e1334bb10b..422f4036b0 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see .
-from typing import Union
+from typing import Optional, Union
import pyrogram
from pyrogram import raw, utils
@@ -27,7 +27,7 @@ async def set_administrator_title(
self: "pyrogram.Client",
chat_id: Union[int, str],
user_id: Union[int, str],
- title: str,
+ title: Optional[str] = None,
) -> bool:
"""Set a custom title (rank) to an administrator of a supergroup.
@@ -56,7 +56,10 @@ async def set_administrator_title(
await app.set_administrator_title(chat_id, user_id, "Admin Title")
"""
- utils.check_valid_length(text=title, arg_type="title", max_length=utils.MAX_ADMIN_RANK_LEN)
+
+ if title:
+ cc = utils.Constants()
+ cc.check_valid_length(text=title, arg_type="title", max_length="MAX_ADMIN_RANK_LEN")
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/edit_inline_caption.py b/pyrogram/methods/messages/edit_inline_caption.py
index 15f2c5abea..55dff07413 100644
--- a/pyrogram/methods/messages/edit_inline_caption.py
+++ b/pyrogram/methods/messages/edit_inline_caption.py
@@ -71,8 +71,6 @@ async def edit_inline_caption(
show_above_text=show_caption_above_media
)
- utils.check_valid_length(text=caption, arg_type="caption", max_length=utils.MAX_CAPTION_LEN)
-
return await self.edit_inline_text(
inline_message_id=inline_message_id,
text=caption,
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index 2f13a6bf6b..3b2bf67629 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -81,7 +81,12 @@ async def edit_inline_text(
)
"""
- utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
+ message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
+
+ if message:
+ cc = utils.Constants()
+ # TODO
+ cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
if disable_web_page_preview and link_preview_options:
raise ValueError(
@@ -109,7 +114,8 @@ async def edit_inline_text(
no_webpage=link_preview_options.is_disabled if link_preview_options else None,
invert_media=link_preview_options.show_above_text if link_preview_options else None,
reply_markup=await reply_markup.write(self) if reply_markup else None,
- **await utils.parse_text_entities(self, text, parse_mode, entities)
+ message=message,
+ entities=entities
),
sleep_threshold=self.sleep_threshold
)
diff --git a/pyrogram/methods/messages/edit_message_caption.py b/pyrogram/methods/messages/edit_message_caption.py
index 1cbe4f714d..bf04392a6b 100644
--- a/pyrogram/methods/messages/edit_message_caption.py
+++ b/pyrogram/methods/messages/edit_message_caption.py
@@ -85,16 +85,6 @@ async def edit_message_caption(
show_above_text=show_caption_above_media
)
- pyrogram.utils.check_valid_length(
- text=caption,
- arg_type="caption",
- max_length=(
- utils.MAX_PREMIUM_CAPTION_LEN
- if self.me.is_premium
- else utils.MAX_CAPTION_LEN
- ),
- )
-
return await self.edit_message_text(
chat_id=chat_id,
message_id=message_id,
diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py
index 6ce4cf8bdb..f520f91479 100644
--- a/pyrogram/methods/messages/edit_message_text.py
+++ b/pyrogram/methods/messages/edit_message_text.py
@@ -95,7 +95,12 @@ async def edit_message_text(
)
"""
- utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
+ message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
+
+ if message:
+ cc = utils.Constants()
+ # TODO
+ cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
if disable_web_page_preview and link_preview_options:
raise ValueError(
@@ -132,7 +137,8 @@ async def edit_message_text(
media=media,
reply_markup=await reply_markup.write(self) if reply_markup else None,
schedule_date=utils.datetime_to_timestamp(schedule_date),
- **await utils.parse_text_entities(self, text, parse_mode, entities)
+ message=message,
+ entities=entities
)
session = None
business_connection = None
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index a28913ac8c..d556fd7b5e 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -154,8 +154,6 @@ async def send_message(
]))
"""
- utils.check_valid_length(text=text, arg_type="text", max_length=utils.MAX_MESSAGE_TEXT_LEN)
-
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
@@ -191,6 +189,10 @@ async def send_message(
)
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
+ if message:
+ cc = utils.Constants()
+ cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
+
session = None
business_connection = None
if business_connection_id:
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index 2f4b4aeba8..dd5430502d 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -63,8 +63,16 @@ async def update_profile(
await app.update_profile(last_name="")
"""
if bio:
- utils.check_valid_length(text=bio, arg_type="bio",
- max_length=utils.MAX_PREMIUM_USER_BIO_LEN if self.me.is_premium else utils.MAX_USER_BIO_LEN)
+ cc = utils.Constants()
+ cc.check_valid_length(
+ text=bio,
+ arg_type="bio",
+ max_length=(
+ "MAX_PREMIUM_USER_BIO_LEN"
+ if self.me and self.me.is_premium
+ else "MAX_USER_BIO_LEN"
+ )
+ )
return bool(
await self.invoke(
diff --git a/pyrogram/utils.py b/pyrogram/utils.py
index 711932ab5a..9ef71fb191 100644
--- a/pyrogram/utils.py
+++ b/pyrogram/utils.py
@@ -245,23 +245,6 @@ def unpack_inline_message_id(inline_message_id: str) -> "raw.base.InputBotInline
MAX_USER_ID_OLD = 2147483647
MAX_USER_ID = 999999999999
-MAX_CAPTION_LEN = 1024
-MAX_PREMIUM_CAPTION_LEN = 4096
-MAX_USER_BIO_LEN = 70
-MAX_PREMIUM_USER_BIO_LEN = 140
-MAX_MESSAGE_TEXT_LEN = 4096
-MAX_ADMIN_RANK_LEN = 16
-
-
-def check_valid_length(text: str, arg_type: str, max_length: int):
- if not isinstance(text, str):
- raise ValueError(f"Argument {arg_type} must be a str")
-
- text_length = len(text)
-
- assert bool(0 < text_length <= max_length), \
- f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: 1-{max_length}"
-
def get_raw_peer_id(peer: raw.base.Peer) -> Optional[int]:
"""Get the raw peer id from a Peer object"""
@@ -609,3 +592,29 @@ def fix_up_voice_audio_uri(
mime_type = "audio/ogg"
# BEWARE: https://t.me/c/1279877202/74
return mime_type
+
+
+class Constants:
+ # TODO: https://github.com/pyrogram/pyrogram/pull/323#issuecomment-629629992
+ # Text of the message to be sent, 1-4096 characters
+ MAX_MESSAGE_TEXT_LEN = 4096
+
+ # Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
+ MAX_CAPTION_LEN = 1024
+ MAX_PREMIUM_CAPTION_LEN = 2048
+
+ MAX_USER_BIO_LEN = 70
+ MAX_PREMIUM_USER_BIO_LEN = 140
+
+ MAX_ADMIN_RANK_LEN = 16
+
+
+ def check_valid_length(self, text: str, arg_type: str, max_length_tye: str):
+ if not isinstance(text, str):
+ raise ValueError(f"Argument {arg_type} must be a str")
+
+ text_length = len(text)
+ max_length = getattr(self, max_length_tye, 0) # TODO
+
+ assert bool(0 < text_length <= max_length), \
+ f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: 1-{max_length}"
From 722a2f619d3c94612d7e6de9cdfa8a30f1bb8119 Mon Sep 17 00:00:00 2001
From: Shrimadhav U K
Date: Mon, 23 Dec 2024 10:04:25 +0530
Subject: [PATCH 03/14] another trying attempt
---
pyrogram/session/session.py | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py
index 036d6a7a8b..82a06bfcb6 100644
--- a/pyrogram/session/session.py
+++ b/pyrogram/session/session.py
@@ -125,7 +125,7 @@ async def start(self):
await self.send(raw.functions.Ping(ping_id=0), timeout=self.START_TIMEOUT)
if not self.is_cdn:
- await self.send(
+ cfg = await self.send(
raw.functions.InvokeWithLayer(
layer=layer,
query=raw.functions.InitConnection(
@@ -146,6 +146,9 @@ async def start(self):
),
timeout=self.START_TIMEOUT
)
+ if isinstance(cfg, raw.types.Config): # TODO
+ pyrogram.utils.Constants.MAX_MESSAGE_TEXT_LEN = cfg.message_length_max
+ pyrogram.utils.Constants.MAX_CAPTION_LEN = cfg.caption_length_max
self.ping_task = self.loop.create_task(self.ping_worker())
From 5e9accffc6d3047bf3ab49802a17cf190d196203 Mon Sep 17 00:00:00 2001
From: Shrimadhav U K
Date: Tue, 24 Dec 2024 09:17:57 +0530
Subject: [PATCH 04/14] Testing Changes ?
make Client attribute instead of Global constant
---
pyrogram/client.py | 30 +++++++++++++++++++
.../methods/chats/set_administrator_title.py | 3 +-
pyrogram/methods/messages/edit_inline_text.py | 4 +--
.../methods/messages/edit_message_text.py | 4 +--
pyrogram/methods/messages/send_message.py | 3 +-
pyrogram/methods/users/update_profile.py | 7 ++---
pyrogram/session/session.py | 4 +--
pyrogram/utils.py | 26 ----------------
8 files changed, 39 insertions(+), 42 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index 7d39a8eb31..e4ce7f925e 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -362,6 +362,8 @@ def __init__(
self.message_cache = Cache(self.max_message_cache_size)
self.business_user_connection_cache = Cache(self.max_business_user_connection_cache_size)
+ self.app_constant = Constant()
+
# Sometimes, for some reason, the server will stop sending updates and will only respond to pings.
# This watchdog will invoke updates.GetState in order to wake up the server and enable it sending updates again
# after some idle time has been detected.
@@ -1240,3 +1242,31 @@ def __setitem__(self, key, value):
if len(self.store) > self.capacity:
for _ in range(self.capacity // 2 + 1):
del self.store[next(iter(self.store))]
+
+
+class Constant:
+ # Text of the message to be sent, 1-4096 characters
+ MAX_MESSAGE_LENGTH = (1, 4096)
+
+ # Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
+ MAX_CAPTION_LENGTH = (0, 1024)
+
+ MAX_USERBIO_LENGTH = (0, 70)
+ MAX_PREMIUM_USERBIO_LENGTH = (0, 140)
+
+ MAX_ADMIN_RANK_LENGTH = (0, 16)
+
+
+ def __init__(self):
+ super().__init__()
+
+
+ def check_valid_length(self, text: str, arg_type: str, max_length_tye: str):
+ if not isinstance(text, str):
+ raise ValueError(f"Argument {arg_type} must be a str")
+
+ text_length = len(text)
+ max_length = getattr(self, max_length_tye, (0, 0))
+
+ assert bool(max_length[0] < text_length <= max_length[1]), \
+ f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: {max_length[0]}-{max_length[1]}"
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index 422f4036b0..c42f1d403e 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -58,8 +58,7 @@ async def set_administrator_title(
"""
if title:
- cc = utils.Constants()
- cc.check_valid_length(text=title, arg_type="title", max_length="MAX_ADMIN_RANK_LEN")
+ self.app_constant.check_valid_length(text=title, arg_type="title", max_length="MAX_ADMIN_RANK_LENGTH")
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index 3b2bf67629..b00d4e0f9f 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -84,9 +84,7 @@ async def edit_inline_text(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- cc = utils.Constants()
- # TODO
- cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
if disable_web_page_preview and link_preview_options:
raise ValueError(
diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py
index f520f91479..5ec8821f3f 100644
--- a/pyrogram/methods/messages/edit_message_text.py
+++ b/pyrogram/methods/messages/edit_message_text.py
@@ -98,9 +98,7 @@ async def edit_message_text(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- cc = utils.Constants()
- # TODO
- cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
if disable_web_page_preview and link_preview_options:
raise ValueError(
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index d556fd7b5e..6fbcf6ff2f 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -190,8 +190,7 @@ async def send_message(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- cc = utils.Constants()
- cc.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_TEXT_LEN")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
session = None
business_connection = None
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index dd5430502d..ef777f824c 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -63,14 +63,13 @@ async def update_profile(
await app.update_profile(last_name="")
"""
if bio:
- cc = utils.Constants()
- cc.check_valid_length(
+ self.app_constant.check_valid_length(
text=bio,
arg_type="bio",
max_length=(
- "MAX_PREMIUM_USER_BIO_LEN"
+ "MAX_PREMIUM_USERBIO_LENGTH"
if self.me and self.me.is_premium
- else "MAX_USER_BIO_LEN"
+ else "MAX_USERBIO_LENGTH"
)
)
diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py
index 82a06bfcb6..9e73fafb80 100644
--- a/pyrogram/session/session.py
+++ b/pyrogram/session/session.py
@@ -147,8 +147,8 @@ async def start(self):
timeout=self.START_TIMEOUT
)
if isinstance(cfg, raw.types.Config): # TODO
- pyrogram.utils.Constants.MAX_MESSAGE_TEXT_LEN = cfg.message_length_max
- pyrogram.utils.Constants.MAX_CAPTION_LEN = cfg.caption_length_max
+ self.client.app_constant.MAX_MESSAGE_LENGTH[1] = cfg.message_length_max
+ self.client.app_constant.MAX_CAPTION_LENGTH[1] = cfg.caption_length_max
self.ping_task = self.loop.create_task(self.ping_worker())
diff --git a/pyrogram/utils.py b/pyrogram/utils.py
index 9ef71fb191..52a62d8aa5 100644
--- a/pyrogram/utils.py
+++ b/pyrogram/utils.py
@@ -592,29 +592,3 @@ def fix_up_voice_audio_uri(
mime_type = "audio/ogg"
# BEWARE: https://t.me/c/1279877202/74
return mime_type
-
-
-class Constants:
- # TODO: https://github.com/pyrogram/pyrogram/pull/323#issuecomment-629629992
- # Text of the message to be sent, 1-4096 characters
- MAX_MESSAGE_TEXT_LEN = 4096
-
- # Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
- MAX_CAPTION_LEN = 1024
- MAX_PREMIUM_CAPTION_LEN = 2048
-
- MAX_USER_BIO_LEN = 70
- MAX_PREMIUM_USER_BIO_LEN = 140
-
- MAX_ADMIN_RANK_LEN = 16
-
-
- def check_valid_length(self, text: str, arg_type: str, max_length_tye: str):
- if not isinstance(text, str):
- raise ValueError(f"Argument {arg_type} must be a str")
-
- text_length = len(text)
- max_length = getattr(self, max_length_tye, 0) # TODO
-
- assert bool(0 < text_length <= max_length), \
- f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: 1-{max_length}"
From 0eb8ee5325aa751c307531e8ad666b1dbfb1d5a6 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Tue, 24 Dec 2024 14:32:57 +0100
Subject: [PATCH 05/14] Try to fix some more conditions
---
pyrogram/methods/chats/set_administrator_title.py | 3 ++-
pyrogram/methods/messages/edit_inline_text.py | 2 +-
pyrogram/methods/messages/edit_message_text.py | 2 +-
pyrogram/methods/messages/send_message.py | 2 +-
pyrogram/methods/users/update_profile.py | 2 +-
pyrogram/session/session.py | 4 ++--
6 files changed, 8 insertions(+), 7 deletions(-)
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index c42f1d403e..bb98a8b9db 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -45,6 +45,7 @@ async def set_administrator_title(
For a contact that exists in your Telegram address book you can use his phone number (str).
title (``str``, *optional*):
+ New custom title for the administrator; 0-16 characters, emoji are not allowed.
A custom title that will be shown to all members instead of "Owner" or "Admin".
Pass None or "" (empty string) to remove the custom title.
@@ -58,7 +59,7 @@ async def set_administrator_title(
"""
if title:
- self.app_constant.check_valid_length(text=title, arg_type="title", max_length="MAX_ADMIN_RANK_LENGTH")
+ self.app_constant.check_valid_length(text=title, arg_type="title", max_length_tye="MAX_ADMIN_RANK_LENGTH")
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index b00d4e0f9f..984505d21e 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -84,7 +84,7 @@ async def edit_inline_text(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
if disable_web_page_preview and link_preview_options:
raise ValueError(
diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py
index 5ec8821f3f..016587843c 100644
--- a/pyrogram/methods/messages/edit_message_text.py
+++ b/pyrogram/methods/messages/edit_message_text.py
@@ -98,7 +98,7 @@ async def edit_message_text(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
if disable_web_page_preview and link_preview_options:
raise ValueError(
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index 6fbcf6ff2f..cacf2d0124 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -190,7 +190,7 @@ async def send_message(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length="MAX_MESSAGE_LENGTH")
+ self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
session = None
business_connection = None
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index ef777f824c..946ab59725 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -66,7 +66,7 @@ async def update_profile(
self.app_constant.check_valid_length(
text=bio,
arg_type="bio",
- max_length=(
+ max_length_tye=(
"MAX_PREMIUM_USERBIO_LENGTH"
if self.me and self.me.is_premium
else "MAX_USERBIO_LENGTH"
diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py
index 9e73fafb80..c592d3673d 100644
--- a/pyrogram/session/session.py
+++ b/pyrogram/session/session.py
@@ -147,8 +147,8 @@ async def start(self):
timeout=self.START_TIMEOUT
)
if isinstance(cfg, raw.types.Config): # TODO
- self.client.app_constant.MAX_MESSAGE_LENGTH[1] = cfg.message_length_max
- self.client.app_constant.MAX_CAPTION_LENGTH[1] = cfg.caption_length_max
+ self.client.app_constant.MAX_MESSAGE_LENGTH = (1, cfg.message_length_max)
+ self.client.app_constant.MAX_CAPTION_LENGTH = (0, cfg.caption_length_max)
self.ping_task = self.loop.create_task(self.ping_worker())
From 0596ef43673fc26c17f3386f1bf9744f820aa0a3 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Tue, 24 Dec 2024 14:45:42 +0100
Subject: [PATCH 06/14] add check for answer_inline_query
---
pyrogram/client.py | 26 ++++++++++++++++----
pyrogram/methods/bots/answer_inline_query.py | 2 ++
2 files changed, 23 insertions(+), 5 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index e4ce7f925e..616d51eebe 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -1256,17 +1256,33 @@ class Constant:
MAX_ADMIN_RANK_LENGTH = (0, 16)
+ # Use the InlineQuery.answer() method. No more than 50 results per query are allowed.
+ MAX_INLINE_QUERY_RESULTS = (0, 50)
def __init__(self):
super().__init__()
- def check_valid_length(self, text: str, arg_type: str, max_length_tye: str):
- if not isinstance(text, str):
- raise ValueError(f"Argument {arg_type} must be a str")
+ def check_valid_length(
+ self,
+ text: Union[List, str],
+ arg_type: str,
+ max_length_tye: str
+ ):
+ if not (
+ isinstance(text, str) or
+ isinstance(text, list)
+ ):
+ raise ValueError(f"Argument {arg_type} must be a str | list")
text_length = len(text)
max_length = getattr(self, max_length_tye, (0, 0))
- assert bool(max_length[0] < text_length <= max_length[1]), \
- f"Invalid length of {text_length} for arg {arg_type}\nValid Lengths: {max_length[0]}-{max_length[1]}"
+ assert (
+ bool(max_length[0] < text_length <= max_length[1]),
+ (
+ f"Invalid length of {text_length} for arg {arg_type}\n"
+ f"Valid Lengths: {max_length[0]}-{max_length[1]}"
+ )
+ )
+
diff --git a/pyrogram/methods/bots/answer_inline_query.py b/pyrogram/methods/bots/answer_inline_query.py
index c3a450a015..1f15a889cb 100644
--- a/pyrogram/methods/bots/answer_inline_query.py
+++ b/pyrogram/methods/bots/answer_inline_query.py
@@ -96,6 +96,8 @@ async def answer_inline_query(
InputTextMessageContent("Message content"))])
"""
+ self.app_constant.check_valid_length(text=results, arg_type="results", max_length_tye="MAX_INLINE_QUERY_RESULTS")
+
return await self.invoke(
raw.functions.messages.SetInlineBotResults(
query_id=int(inline_query_id),
From 132b7ddf1aa75bfae124b5ff1abf8724e828fc42 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Tue, 24 Dec 2024 14:58:02 +0100
Subject: [PATCH 07/14] Add condition check in update_profile
first_name and last_name
---
pyrogram/client.py | 2 ++
.../methods/chats/set_administrator_title.py | 2 +-
.../methods/messages/edit_inline_caption.py | 2 +-
pyrogram/methods/messages/edit_inline_text.py | 8 +-----
.../methods/messages/edit_message_caption.py | 2 +-
.../methods/messages/edit_message_text.py | 8 +-----
pyrogram/methods/users/update_profile.py | 25 +++++++++++++++----
7 files changed, 27 insertions(+), 22 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index 616d51eebe..6a984abe27 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -1251,6 +1251,8 @@ class Constant:
# Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
MAX_CAPTION_LENGTH = (0, 1024)
+ MAX_USER_FIRSTNAME_LENGTH = (1, 64)
+ MAX_USER_LASTNAME_LENGTH = (0, 64)
MAX_USERBIO_LENGTH = (0, 70)
MAX_PREMIUM_USERBIO_LENGTH = (0, 140)
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index bb98a8b9db..aeb7d5d13b 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -19,7 +19,7 @@
from typing import Optional, Union
import pyrogram
-from pyrogram import raw, utils
+from pyrogram import raw
class SetAdministratorTitle:
diff --git a/pyrogram/methods/messages/edit_inline_caption.py b/pyrogram/methods/messages/edit_inline_caption.py
index 55dff07413..9dd5aa2c4b 100644
--- a/pyrogram/methods/messages/edit_inline_caption.py
+++ b/pyrogram/methods/messages/edit_inline_caption.py
@@ -19,7 +19,7 @@
from typing import Optional, List
import pyrogram
-from pyrogram import types, enums, utils
+from pyrogram import types, enums
class EditInlineCaption:
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index 984505d21e..28f3c1ced8 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -81,11 +81,6 @@ async def edit_inline_text(
)
"""
- message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
-
- if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
-
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
@@ -112,8 +107,7 @@ async def edit_inline_text(
no_webpage=link_preview_options.is_disabled if link_preview_options else None,
invert_media=link_preview_options.show_above_text if link_preview_options else None,
reply_markup=await reply_markup.write(self) if reply_markup else None,
- message=message,
- entities=entities
+ **await utils.parse_text_entities(self, text, parse_mode, entities)
),
sleep_threshold=self.sleep_threshold
)
diff --git a/pyrogram/methods/messages/edit_message_caption.py b/pyrogram/methods/messages/edit_message_caption.py
index bf04392a6b..6752d00258 100644
--- a/pyrogram/methods/messages/edit_message_caption.py
+++ b/pyrogram/methods/messages/edit_message_caption.py
@@ -20,7 +20,7 @@
from typing import Union, List, Optional
import pyrogram
-from pyrogram import types, enums, utils
+from pyrogram import types, enums
class EditMessageCaption:
diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py
index 016587843c..57dceab615 100644
--- a/pyrogram/methods/messages/edit_message_text.py
+++ b/pyrogram/methods/messages/edit_message_text.py
@@ -95,11 +95,6 @@ async def edit_message_text(
)
"""
- message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
-
- if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
-
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
@@ -135,8 +130,7 @@ async def edit_message_text(
media=media,
reply_markup=await reply_markup.write(self) if reply_markup else None,
schedule_date=utils.datetime_to_timestamp(schedule_date),
- message=message,
- entities=entities
+ **await utils.parse_text_entities(self, text, parse_mode, entities)
)
session = None
business_connection = None
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index 946ab59725..f3a1cf3dbe 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -22,11 +22,11 @@
class UpdateProfile:
async def update_profile(
- self: "pyrogram.Client",
- *,
- first_name: str = None,
- last_name: str = None,
- bio: str = None
+ self: "pyrogram.Client",
+ *,
+ first_name: str = None,
+ last_name: str = None,
+ bio: str = None
) -> bool:
"""Update your profile details such as first name, last name and bio.
@@ -62,6 +62,21 @@ async def update_profile(
# Remove the last name
await app.update_profile(last_name="")
"""
+
+ if first_name:
+ self.app_constant.check_valid_length(
+ text=first_name,
+ arg_type="first_name",
+ max_length_tye="MAX_USER_FIRSTNAME_LENGTH"
+ )
+
+ if last_name:
+ self.app_constant.check_valid_length(
+ text=last_name,
+ arg_type="last_name",
+ max_length_tye="MAX_USER_LASTNAME_LENGTH"
+ )
+
if bio:
self.app_constant.check_valid_length(
text=bio,
From 3d342f9b832d571f0fb7b2a9b6809b4916a087b1 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Tue, 24 Dec 2024 15:00:24 +0100
Subject: [PATCH 08/14] minor fixes
---
pyrogram/methods/messages/edit_inline_caption.py | 1 -
pyrogram/methods/messages/edit_inline_text.py | 1 -
pyrogram/methods/users/update_profile.py | 2 +-
3 files changed, 1 insertion(+), 3 deletions(-)
diff --git a/pyrogram/methods/messages/edit_inline_caption.py b/pyrogram/methods/messages/edit_inline_caption.py
index 9dd5aa2c4b..fd2f9442ce 100644
--- a/pyrogram/methods/messages/edit_inline_caption.py
+++ b/pyrogram/methods/messages/edit_inline_caption.py
@@ -70,7 +70,6 @@ async def edit_inline_caption(
link_preview_options = types.LinkPreviewOptions(
show_above_text=show_caption_above_media
)
-
return await self.edit_inline_text(
inline_message_id=inline_message_id,
text=caption,
diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py
index 28f3c1ced8..2f0dd30ef1 100644
--- a/pyrogram/methods/messages/edit_inline_text.py
+++ b/pyrogram/methods/messages/edit_inline_text.py
@@ -80,7 +80,6 @@ async def edit_inline_text(
)
)
"""
-
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index f3a1cf3dbe..3398b78fe5 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -17,7 +17,7 @@
# along with Pyrogram. If not, see .
import pyrogram
-from pyrogram import raw, utils
+from pyrogram import raw
class UpdateProfile:
From 0b193c1d785ea4ff69f76551fa1ea696ac861791 Mon Sep 17 00:00:00 2001
From: anonymousx97 <88324835+anonymousx97@users.noreply.github.com>
Date: Wed, 25 Dec 2024 12:21:13 +0530
Subject: [PATCH 09/14] use arg_type to fetch values and use a single
is_premium check
---
pyrogram/client.py | 58 +++++++++----------
pyrogram/methods/bots/answer_inline_query.py | 2 +-
.../methods/chats/set_administrator_title.py | 2 +-
pyrogram/methods/messages/send_message.py | 2 +-
pyrogram/methods/users/update_profile.py | 27 +--------
5 files changed, 34 insertions(+), 57 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index 6a984abe27..cb3a9eb746 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -362,7 +362,7 @@ def __init__(
self.message_cache = Cache(self.max_message_cache_size)
self.business_user_connection_cache = Cache(self.max_business_user_connection_cache_size)
- self.app_constant = Constant()
+ self.app_constant = Constant(client_instance=self)
# Sometimes, for some reason, the server will stop sending updates and will only respond to pings.
# This watchdog will invoke updates.GetState in order to wake up the server and enable it sending updates again
@@ -1245,46 +1245,44 @@ def __setitem__(self, key, value):
class Constant:
+ """Tuple of min, max, premium max lengths"""
+
# Text of the message to be sent, 1-4096 characters
- MAX_MESSAGE_LENGTH = (1, 4096)
+ _MAX_TEXT_LENGTH = (1, 4096, 0)
# Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
- MAX_CAPTION_LENGTH = (0, 1024)
+ _MAX_CAPTION_LENGTH = (0, 1024, 0)
- MAX_USER_FIRSTNAME_LENGTH = (1, 64)
- MAX_USER_LASTNAME_LENGTH = (0, 64)
- MAX_USERBIO_LENGTH = (0, 70)
- MAX_PREMIUM_USERBIO_LENGTH = (0, 140)
+ _MAX_FIRST_NAME_LENGTH = (1, 64, 0)
+ _MAX_LAST_NAME_LENGTH = (0, 64, 0)
- MAX_ADMIN_RANK_LENGTH = (0, 16)
+ # USER's BIO
+ _MAX_BIO_LENGTH = (0, 70, 140)
- # Use the InlineQuery.answer() method. No more than 50 results per query are allowed.
- MAX_INLINE_QUERY_RESULTS = (0, 50)
+ # ADMIN TITLE
+ _MAX_TITLE_LENGTH = (0, 16, 0)
- def __init__(self):
- super().__init__()
+ # Use the InlineQuery.answer() method. No more than 50 results per query are allowed.
+ _MAX_RESULTS_LENGTH = (0, 50, 0)
+ def __init__(self, client_instance: Client):
+ self.is_premium = client_instance.me.is_premium
- def check_valid_length(
- self,
- text: Union[List, str],
- arg_type: str,
- max_length_tye: str
- ):
- if not (
- isinstance(text, str) or
- isinstance(text, list)
- ):
+ def check_valid_length(self, text: Union[List, str], arg_type: str, ):
+ if not isinstance(text, (str, list)):
raise ValueError(f"Argument {arg_type} must be a str | list")
text_length = len(text)
- max_length = getattr(self, max_length_tye, (0, 0))
- assert (
- bool(max_length[0] < text_length <= max_length[1]),
- (
- f"Invalid length of {text_length} for arg {arg_type}\n"
- f"Valid Lengths: {max_length[0]}-{max_length[1]}"
- )
- )
+ attr_str = f"_max{arg_type}_length".upper()
+
+ # MIN, MAX, PREM-MAX
+ lengths: tuple[int, int, int] = getattr(self, attr_str, (0, 0, 0))
+
+ min_length = lengths[0]
+ # Check if client is premium and the premium value isn't 0
+ max_length = lengths[2] if self.is_premium and lengths[2] != 0 else lengths[1]
+
+ error_info = f"\nInvalid length of {text_length} for arg {arg_type}\nValid Lengths: {min_length}-{max_length}"
+ assert bool(min_length < text_length <= max_length), error_info
diff --git a/pyrogram/methods/bots/answer_inline_query.py b/pyrogram/methods/bots/answer_inline_query.py
index 1f15a889cb..31f524555c 100644
--- a/pyrogram/methods/bots/answer_inline_query.py
+++ b/pyrogram/methods/bots/answer_inline_query.py
@@ -96,7 +96,7 @@ async def answer_inline_query(
InputTextMessageContent("Message content"))])
"""
- self.app_constant.check_valid_length(text=results, arg_type="results", max_length_tye="MAX_INLINE_QUERY_RESULTS")
+ self.app_constant.check_valid_length(text=results, arg_type="results")
return await self.invoke(
raw.functions.messages.SetInlineBotResults(
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index aeb7d5d13b..767f6537d4 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -59,7 +59,7 @@ async def set_administrator_title(
"""
if title:
- self.app_constant.check_valid_length(text=title, arg_type="title", max_length_tye="MAX_ADMIN_RANK_LENGTH")
+ self.app_constant.check_valid_length(text=title, arg_type="title")
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index cacf2d0124..5b012c8a92 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -190,7 +190,7 @@ async def send_message(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- self.app_constant.check_valid_length(text=message, arg_type="text", max_length_tye="MAX_MESSAGE_LENGTH")
+ self.app_constant.check_valid_length(text=message, arg_type="text")
session = None
business_connection = None
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index 3398b78fe5..c49ac39010 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -63,30 +63,9 @@ async def update_profile(
await app.update_profile(last_name="")
"""
- if first_name:
- self.app_constant.check_valid_length(
- text=first_name,
- arg_type="first_name",
- max_length_tye="MAX_USER_FIRSTNAME_LENGTH"
- )
-
- if last_name:
- self.app_constant.check_valid_length(
- text=last_name,
- arg_type="last_name",
- max_length_tye="MAX_USER_LASTNAME_LENGTH"
- )
-
- if bio:
- self.app_constant.check_valid_length(
- text=bio,
- arg_type="bio",
- max_length_tye=(
- "MAX_PREMIUM_USERBIO_LENGTH"
- if self.me and self.me.is_premium
- else "MAX_USERBIO_LENGTH"
- )
- )
+ for var_name in ("first_name", "last_name", "bio"):
+ if var_value := locals()[var_name]:
+ self.app_constant.check_valid_length(text=var_value, arg_type=var_name)
return bool(
await self.invoke(
From b2fde7653feb4106ed2af3ffd6daadd7220e25f2 Mon Sep 17 00:00:00 2001
From: anonymousx97 <88324835+anonymousx97@users.noreply.github.com>
Date: Wed, 25 Dec 2024 12:36:58 +0530
Subject: [PATCH 10/14] adjustments to the new logic
---
pyrogram/client.py | 16 ++++++++--------
pyrogram/session/session.py | 4 ++--
2 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index cb3a9eb746..711edf04e1 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -1248,22 +1248,22 @@ class Constant:
"""Tuple of min, max, premium max lengths"""
# Text of the message to be sent, 1-4096 characters
- _MAX_TEXT_LENGTH = (1, 4096, 0)
+ MAX_TEXT_LENGTH = (1, 4096, 0)
# Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
- _MAX_CAPTION_LENGTH = (0, 1024, 0)
+ MAX_CAPTION_LENGTH = (0, 1024, 0)
- _MAX_FIRST_NAME_LENGTH = (1, 64, 0)
- _MAX_LAST_NAME_LENGTH = (0, 64, 0)
+ MAX_FIRST_NAME_LENGTH = (1, 64, 0)
+ MAX_LAST_NAME_LENGTH = (0, 64, 0)
# USER's BIO
- _MAX_BIO_LENGTH = (0, 70, 140)
+ MAX_BIO_LENGTH = (0, 70, 140)
# ADMIN TITLE
- _MAX_TITLE_LENGTH = (0, 16, 0)
+ MAX_TITLE_LENGTH = (0, 16, 0)
# Use the InlineQuery.answer() method. No more than 50 results per query are allowed.
- _MAX_RESULTS_LENGTH = (0, 50, 0)
+ MAX_RESULTS_LENGTH = (0, 50, 0)
def __init__(self, client_instance: Client):
self.is_premium = client_instance.me.is_premium
@@ -1274,7 +1274,7 @@ def check_valid_length(self, text: Union[List, str], arg_type: str, ):
text_length = len(text)
- attr_str = f"_max{arg_type}_length".upper()
+ attr_str = f"max_{arg_type}_length".upper()
# MIN, MAX, PREM-MAX
lengths: tuple[int, int, int] = getattr(self, attr_str, (0, 0, 0))
diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py
index c592d3673d..4234552f26 100644
--- a/pyrogram/session/session.py
+++ b/pyrogram/session/session.py
@@ -147,8 +147,8 @@ async def start(self):
timeout=self.START_TIMEOUT
)
if isinstance(cfg, raw.types.Config): # TODO
- self.client.app_constant.MAX_MESSAGE_LENGTH = (1, cfg.message_length_max)
- self.client.app_constant.MAX_CAPTION_LENGTH = (0, cfg.caption_length_max)
+ self.client.app_constant.MAX_TEXT_LENGTH = (1, cfg.message_length_max, cfg.message_length_max)
+ self.client.app_constant.MAX_CAPTION_LENGTH = (0, cfg.caption_length_max, cfg.caption_length_max)
self.ping_task = self.loop.create_task(self.ping_worker())
From f5511c2c0e4409d7db41f8de24c37a8878c1fdf2 Mon Sep 17 00:00:00 2001
From: Shrimadhav U K
Date: Tue, 18 Mar 2025 10:51:31 +0530
Subject: [PATCH 11/14] try add ClientConfigurationOption
---
pyrogram/types/__init__.py | 1 +
pyrogram/types/chat_topics/__init__.py | 2 +-
.../types/client_configuration/__init__.py | 24 ++++++++++
.../client_configuration_option.py | 46 +++++++++++++++++++
4 files changed, 72 insertions(+), 1 deletion(-)
create mode 100644 pyrogram/types/client_configuration/__init__.py
create mode 100644 pyrogram/types/client_configuration/client_configuration_option.py
diff --git a/pyrogram/types/__init__.py b/pyrogram/types/__init__.py
index a4dbe451ba..5ef845d88f 100644
--- a/pyrogram/types/__init__.py
+++ b/pyrogram/types/__init__.py
@@ -23,6 +23,7 @@
from .bots_and_keyboards import *
from .chat_drafts import *
from .chat_topics import *
+from .client_configuration import *
from .inline_mode import *
from .input_media import *
from .input_paid_media import *
diff --git a/pyrogram/types/chat_topics/__init__.py b/pyrogram/types/chat_topics/__init__.py
index 5546352284..2474bef682 100644
--- a/pyrogram/types/chat_topics/__init__.py
+++ b/pyrogram/types/chat_topics/__init__.py
@@ -1,5 +1,5 @@
# Pyrogram - Telegram MTProto API Client Library for Python
-# Copyright (C) 2017-present Dan
+# Copyright (C) 2017-present
#
# This file is part of Pyrogram.
#
diff --git a/pyrogram/types/client_configuration/__init__.py b/pyrogram/types/client_configuration/__init__.py
new file mode 100644
index 0000000000..ecac61b410
--- /dev/null
+++ b/pyrogram/types/client_configuration/__init__.py
@@ -0,0 +1,24 @@
+# Pyrogram - Telegram MTProto API Client Library for Python
+# Copyright (C) 2017-present
+#
+# This file is part of Pyrogram.
+#
+# Pyrogram is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Pyrogram is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with Pyrogram. If not, see .
+
+from .client_configuration_option import ClientConfigurationOption
+
+
+__all__ = [
+ "ClientConfigurationOption",
+]
diff --git a/pyrogram/types/client_configuration/client_configuration_option.py b/pyrogram/types/client_configuration/client_configuration_option.py
new file mode 100644
index 0000000000..a652441359
--- /dev/null
+++ b/pyrogram/types/client_configuration/client_configuration_option.py
@@ -0,0 +1,46 @@
+# Pyrogram - Telegram MTProto API Client Library for Python
+# Copyright (C) 2017-present
+#
+# This file is part of Pyrogram.
+#
+# Pyrogram is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Pyrogram is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with Pyrogram. If not, see .
+
+
+from typing import Optional, Union
+
+from ..object import Object
+
+
+class ClientConfigurationOption(Object):
+ """This object represents the value of an option.
+
+ Parameters:
+ key (``str``):
+ The name of the option.
+
+ value (``bool`` | ``int`` | ``str``, *optional*):
+ The value of the option. Can be None if it is an unknown option or an option which has a default value.
+
+ """
+
+ def __init__(
+ self,
+ *,
+ key: str = None,
+ value: Union[bool, int, str] = None,
+ ):
+ super().__init__()
+
+ self.key = key
+ self.value = value
From 836132d43455f7767b559c20524c2409a0466e7f Mon Sep 17 00:00:00 2001
From: Shrimadhav U K
Date: Tue, 6 May 2025 16:13:04 +0530
Subject: [PATCH 12/14] Try add admin_rights in Chat?
---
pyrogram/types/user_and_chats/chat.py | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/pyrogram/types/user_and_chats/chat.py b/pyrogram/types/user_and_chats/chat.py
index 9414f3d2fe..8cb450e2ab 100644
--- a/pyrogram/types/user_and_chats/chat.py
+++ b/pyrogram/types/user_and_chats/chat.py
@@ -117,6 +117,9 @@ class Chat(Object):
permissions (:obj:`~pyrogram.types.ChatPermissions` *optional*):
Default chat member permissions, for groups and supergroups.
+
+ privileges (:obj:`~pyrogram.types.ChatPrivileges`, *optional*):
+ Administrator Privileges of the current logged in user in the current chat. None if the current user is not an Administrator.
can_send_paid_media (``bool``, *optional*):
True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats.
@@ -276,6 +279,7 @@ def __init__(
members_count: int = None,
restrictions: list["types.Restriction"] = None,
permissions: "types.ChatPermissions" = None,
+ privileges: "types.ChatPrivileges" = None,
distance: int = None,
linked_chat: "types.Chat" = None,
send_as_chat: "types.Chat" = None,
@@ -339,6 +343,7 @@ def __init__(
self.members_count = members_count
self.restrictions = restrictions
self.permissions = permissions
+ self.privileges = privileges
self.distance = distance
self.linked_chat = linked_chat
self.send_as_chat = send_as_chat
@@ -530,6 +535,7 @@ def _parse_channel_chat(client, channel: raw.types.Channel) -> "Chat":
]
) or None,
permissions=types.ChatPermissions._parse(getattr(channel, "default_banned_rights", None)),
+ privileges=types.ChatPrivileges._parse(getattr(channel, "admin_rights", None)),
members_count=getattr(channel, "participants_count", 0),
dc_id=getattr(getattr(channel, "photo", None), "dc_id", None),
has_protected_content=getattr(channel, "noforwards", None),
From 1e74ec7dfaeae8921f2e678d51507415353ee648 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Sun, 11 May 2025 08:35:55 +0200
Subject: [PATCH 13/14] fixes
---
pyrogram/client.py | 46 +---------------
pyrogram/methods/bots/answer_inline_query.py | 2 +-
.../methods/chats/set_administrator_title.py | 2 +-
pyrogram/methods/messages/send_message.py | 2 +-
pyrogram/methods/users/update_profile.py | 6 ++-
pyrogram/session/session.py | 54 +++++++++++++++++--
pyrogram/utils.py | 19 +++++++
7 files changed, 78 insertions(+), 53 deletions(-)
diff --git a/pyrogram/client.py b/pyrogram/client.py
index 5d9277fdd4..874ccec5c9 100644
--- a/pyrogram/client.py
+++ b/pyrogram/client.py
@@ -362,7 +362,7 @@ def __init__(
self.message_cache = Cache(self.max_message_cache_size)
self.business_user_connection_cache = Cache(self.max_business_user_connection_cache_size)
- self.app_constant = Constant(client_instance=self)
+ self.app_constant: dict[str, "types.ClientConfigurationOption"] = {}
# Sometimes, for some reason, the server will stop sending updates and will only respond to pings.
# This watchdog will invoke updates.GetState in order to wake up the server and enable it sending updates again
@@ -1244,47 +1244,3 @@ def __setitem__(self, key, value):
if len(self.store) > self.capacity:
for _ in range(self.capacity // 2 + 1):
del self.store[next(iter(self.store))]
-
-
-class Constant:
- """Tuple of min, max, premium max lengths"""
-
- # Text of the message to be sent, 1-4096 characters
- MAX_TEXT_LENGTH = (1, 4096, 0)
-
- # Caption for the animation, audio, document, photo, video or voice, 0-1024 characters
- MAX_CAPTION_LENGTH = (0, 1024, 0)
-
- MAX_FIRST_NAME_LENGTH = (1, 64, 0)
- MAX_LAST_NAME_LENGTH = (0, 64, 0)
-
- # USER's BIO
- MAX_BIO_LENGTH = (0, 70, 140)
-
- # ADMIN TITLE
- MAX_TITLE_LENGTH = (0, 16, 0)
-
- # Use the InlineQuery.answer() method. No more than 50 results per query are allowed.
- MAX_RESULTS_LENGTH = (0, 50, 0)
-
- def __init__(self, client_instance: Client):
- self.is_premium = client_instance.me.is_premium
-
- def check_valid_length(self, text: Union[List, str], arg_type: str, ):
- if not isinstance(text, (str, list)):
- raise ValueError(f"Argument {arg_type} must be a str | list")
-
- text_length = len(text)
-
- attr_str = f"max_{arg_type}_length".upper()
-
- # MIN, MAX, PREM-MAX
- lengths: tuple[int, int, int] = getattr(self, attr_str, (0, 0, 0))
-
- min_length = lengths[0]
- # Check if client is premium and the premium value isn't 0
- max_length = lengths[2] if self.is_premium and lengths[2] != 0 else lengths[1]
-
- error_info = f"\nInvalid length of {text_length} for arg {arg_type}\nValid Lengths: {min_length}-{max_length}"
-
- assert bool(min_length < text_length <= max_length), error_info
diff --git a/pyrogram/methods/bots/answer_inline_query.py b/pyrogram/methods/bots/answer_inline_query.py
index 31f524555c..c8d851ab46 100644
--- a/pyrogram/methods/bots/answer_inline_query.py
+++ b/pyrogram/methods/bots/answer_inline_query.py
@@ -96,7 +96,7 @@ async def answer_inline_query(
InputTextMessageContent("Message content"))])
"""
- self.app_constant.check_valid_length(text=results, arg_type="results")
+ utils.check_valid_length(client=self, text=results, arg_type="inline_query_results_max")
return await self.invoke(
raw.functions.messages.SetInlineBotResults(
diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py
index 767f6537d4..8951d31fd9 100644
--- a/pyrogram/methods/chats/set_administrator_title.py
+++ b/pyrogram/methods/chats/set_administrator_title.py
@@ -59,7 +59,7 @@ async def set_administrator_title(
"""
if title:
- self.app_constant.check_valid_length(text=title, arg_type="title")
+ utils.check_valid_length(client=self, text=title, arg_type="administrator_title_length_max")
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py
index e850479a79..0397c6e95f 100644
--- a/pyrogram/methods/messages/send_message.py
+++ b/pyrogram/methods/messages/send_message.py
@@ -198,7 +198,7 @@ async def send_message(
message, entities = (await utils.parse_text_entities(self, text, parse_mode, entities)).values()
if message:
- self.app_constant.check_valid_length(text=message, arg_type="text")
+ utils.check_valid_length(client=self, text=message, arg_type="message_length_max")
session = None
business_connection = None
diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py
index dfd6987d6b..b347b05c67 100644
--- a/pyrogram/methods/users/update_profile.py
+++ b/pyrogram/methods/users/update_profile.py
@@ -63,9 +63,11 @@ async def update_profile(
await app.update_profile(last_name="")
"""
- for var_name in ("first_name", "last_name", "bio"):
+ for var_name in ("first_name", "last_name",):
if var_value := locals()[var_name]:
- self.app_constant.check_valid_length(text=var_value, arg_type=var_name)
+ utils.check_valid_length(client=self, text=var_value, arg_type="name_length_max")
+ if bio:
+ utils.check_valid_length(client=self, text=bio, arg_type="about_length_max")
return bool(
await self.invoke(
diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py
index 1e84255361..4dfc82ddab 100644
--- a/pyrogram/session/session.py
+++ b/pyrogram/session/session.py
@@ -24,7 +24,7 @@
from io import BytesIO
import pyrogram
-from pyrogram import raw
+from pyrogram import raw, types
from pyrogram.connection import Connection
from pyrogram.crypto import mtproto
from pyrogram.errors import (
@@ -147,8 +147,56 @@ async def start(self):
timeout=self.START_TIMEOUT
)
if isinstance(cfg, raw.types.Config): # TODO
- self.client.app_constant.MAX_TEXT_LENGTH = (1, cfg.message_length_max, cfg.message_length_max)
- self.client.app_constant.MAX_CAPTION_LENGTH = (0, cfg.caption_length_max, cfg.caption_length_max)
+ for key in [
+ "chat_size_max",
+ "megagroup_size_max",
+ "forwarded_count_max",
+ "online_update_period_ms",
+ "online_cloud_timeout_ms",
+ "edit_time_limit",
+ "revoke_time_limit",
+ "revoke_pm_time_limit",
+ "stickers_recent_limit",
+ "channels_read_media_period",
+ "me_url_prefix",
+ "caption_length_max",
+ "message_length_max",
+ "gif_search_username",
+ "venue_search_username",
+ "img_search_username",
+ "autologin_token",
+ ]:
+ self.client.app_constant[
+ key
+ ] = types.ClientConfigurationOption(
+ key=key,
+ value=getattr(cfg, key, None)
+ ) if getattr(cfg, key, None) else None
+ self.client.app_constant[
+ "name_length_max"
+ ] = types.ClientConfigurationOption(
+ key="name_length_max",
+ value=64
+ )
+ self.client.app_constant[
+ "administrator_title_length_max"
+ ] = types.ClientConfigurationOption(
+ key="administrator_title_length_max",
+ value=16
+ )
+ self.client.app_constant[
+ "inline_query_results_max"
+ ] = types.ClientConfigurationOption(
+ key="inline_query_results_max",
+ value=50
+ )
+ # TODO
+ self.client.app_constant[
+ "about_length_max"
+ ] = types.ClientConfigurationOption(
+ key="about_length_max",
+ value=70, # 140
+ )
self.ping_task = self.loop.create_task(self.ping_worker())
diff --git a/pyrogram/utils.py b/pyrogram/utils.py
index a75891ff64..fe07216f36 100644
--- a/pyrogram/utils.py
+++ b/pyrogram/utils.py
@@ -659,3 +659,22 @@ def is_list_like(obj):
Ported from https://github.com/LonamiWebs/Telethon/blob/1cb5ff1dd54ecfad41711fc5a4ecf36d2ad8eaf6/telethon/utils.py#L902
"""
return isinstance(obj, (list, tuple, set, dict, range))
+
+
+def check_valid_length(
+ client: "pyrogram.Client",
+ text: Union[list, str],
+ arg_type: str,
+):
+ if not isinstance(text, (str, list)):
+ raise ValueError(f"Argument {arg_type} must be a str | list")
+
+ text_length = len(text)
+ max_length = client.app_constant.get(arg_type)
+
+ if not max_length:
+ raise ValueError(f"Argument {arg_type} is not supported")
+
+ error_info = f"\nInvalid length of {text_length} for arg {arg_type}\nValid Length: {max_length.value}"
+
+ assert bool(text_length <= max_length.value), error_info
From 55782c6e087c36eb834825a54366063e99fe6125 Mon Sep 17 00:00:00 2001
From: shriMADhav U k
Date: Sun, 11 May 2025 08:45:23 +0200
Subject: [PATCH 14/14] revert
---
pyrogram/types/user_and_chats/chat.py | 6 ------
1 file changed, 6 deletions(-)
diff --git a/pyrogram/types/user_and_chats/chat.py b/pyrogram/types/user_and_chats/chat.py
index 774e4254f8..a12b82a88a 100644
--- a/pyrogram/types/user_and_chats/chat.py
+++ b/pyrogram/types/user_and_chats/chat.py
@@ -117,9 +117,6 @@ class Chat(Object):
permissions (:obj:`~pyrogram.types.ChatPermissions` *optional*):
Default chat member permissions, for groups and supergroups.
-
- privileges (:obj:`~pyrogram.types.ChatPrivileges`, *optional*):
- Administrator Privileges of the current logged in user in the current chat. None if the current user is not an Administrator.
can_send_paid_media (``bool``, *optional*):
True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats.
@@ -282,7 +279,6 @@ def __init__(
members_count: int = None,
restrictions: list["types.Restriction"] = None,
permissions: "types.ChatPermissions" = None,
- privileges: "types.ChatPrivileges" = None,
distance: int = None,
linked_chat: "types.Chat" = None,
send_as_chat: "types.Chat" = None,
@@ -347,7 +343,6 @@ def __init__(
self.members_count = members_count
self.restrictions = restrictions
self.permissions = permissions
- self.privileges = privileges
self.distance = distance
self.linked_chat = linked_chat
self.send_as_chat = send_as_chat
@@ -540,7 +535,6 @@ def _parse_channel_chat(client, channel: raw.types.Channel) -> "Chat":
]
) or None,
permissions=types.ChatPermissions._parse(getattr(channel, "default_banned_rights", None)),
- privileges=types.ChatPrivileges._parse(getattr(channel, "admin_rights", None)),
members_count=getattr(channel, "participants_count", 0),
dc_id=getattr(getattr(channel, "photo", None), "dc_id", None),
has_protected_content=getattr(channel, "noforwards", None),