diff --git a/README.rst b/README.rst index 50e848db..2bb0725b 100644 --- a/README.rst +++ b/README.rst @@ -32,7 +32,7 @@ Features - **Fast**: Crypto parts are boosted up by TgCrypto_, a high-performance library written in pure C. - **Documented**: Pyrogram API methods, types and public interfaces are well documented. - **Type-hinted**: Exposed Pyrogram types and method parameters are all type-hinted. -- **Updated**, to the latest Telegram API version, currently Layer 91 on top of `MTProto 2.0`_. +- **Updated**, to the latest Telegram API version, currently Layer 95 on top of `MTProto 2.0`_. - **Pluggable**: The Smart Plugin system allows to write components with minimal boilerplate code. - **Comprehensive**: Execute any advanced action an official client is able to do, and even more. @@ -107,7 +107,7 @@ Copyright & License
- Schema Layer @@ -122,7 +122,7 @@ Copyright & License .. |description| replace:: **Telegram MTProto API Framework for Python** -.. |schema| image:: https://img.shields.io/badge/schema-layer%2091-eda738.svg?longCache=true&colorA=262b30 +.. |schema| image:: https://img.shields.io/badge/schema-layer%2095-eda738.svg?longCache=true&colorA=262b30 :target: compiler/api/source/main_api.tl :alt: Schema Layer diff --git a/compiler/api/compiler.py b/compiler/api/compiler.py index 9e671e80..122ce843 100644 --- a/compiler/api/compiler.py +++ b/compiler/api/compiler.py @@ -171,8 +171,8 @@ def start(): shutil.rmtree("{}/functions".format(DESTINATION), ignore_errors=True) with open("{}/source/auth_key.tl".format(HOME), encoding="utf-8") as auth, \ - open("{}/source/sys_msgs.tl".format(HOME), encoding="utf-8") as system, \ - open("{}/source/main_api.tl".format(HOME), encoding="utf-8") as api: + open("{}/source/sys_msgs.tl".format(HOME), encoding="utf-8") as system, \ + open("{}/source/main_api.tl".format(HOME), encoding="utf-8") as api: schema = (auth.read() + system.read() + api.read()).splitlines() with open("{}/template/mtproto.txt".format(HOME), encoding="utf-8") as f: @@ -287,9 +287,11 @@ def start(): sorted_args = sort_args(c.args) - arguments = ", " + ", ".join( - [get_argument_type(i) for i in sorted_args if i != ("flags", "#")] - ) if c.args else "" + arguments = ( + ", " + + ("*, " if c.args else "") + + (", ".join([get_argument_type(i) for i in sorted_args if i != ("flags", "#")]) if c.args else "") + ) fields = "\n ".join( ["self.{0} = {0} # {1}".format(i[0], i[1]) for i in c.args if i != ("flags", "#")] @@ -456,7 +458,11 @@ def start(): fields=fields, read_types=read_types, write_types=write_types, - return_arguments=", ".join([i[0] for i in sorted_args if i != ("flags", "#")]) + return_arguments=", ".join( + ["{0}={0}".format(i[0]) for i in sorted_args if i != ("flags", "#")] + ), + slots=", ".join(['"{}"'.format(i[0]) for i in sorted_args if i != ("flags", "#")]), + qualname="{}{}".format("{}.".format(c.namespace) if c.namespace else "", c.name) ) ) diff --git a/compiler/api/template/mtproto.txt b/compiler/api/template/mtproto.txt index 9a65b52d..c63525d6 100644 --- a/compiler/api/template/mtproto.txt +++ b/compiler/api/template/mtproto.txt @@ -9,7 +9,10 @@ class {class_name}(Object): """{docstring_args} """ + __slots__ = [{slots}] + ID = {object_id} + QUALNAME = "{qualname}" def __init__(self{arguments}): {fields} diff --git a/compiler/error/compiler.py b/compiler/error/compiler.py index b86222e7..751db1bc 100644 --- a/compiler/error/compiler.py +++ b/compiler/error/compiler.py @@ -73,7 +73,7 @@ def start(): f_init.write("from .{}_{} import *\n".format(name.lower(), code)) with open("{}/source/{}".format(HOME, i), encoding="utf-8") as f_csv, \ - open("{}/{}_{}.py".format(DEST, name.lower(), code), "w", encoding="utf-8") as f_class: + open("{}/{}_{}.py".format(DEST, name.lower(), code), "w", encoding="utf-8") as f_class: reader = csv.reader(f_csv, delimiter="\t") super_class = caml(name) diff --git a/compiler/error/source/400_BAD_REQUEST.tsv b/compiler/error/source/400_BAD_REQUEST.tsv index 0b9804a7..a2bbd345 100644 --- a/compiler/error/source/400_BAD_REQUEST.tsv +++ b/compiler/error/source/400_BAD_REQUEST.tsv @@ -92,4 +92,5 @@ USERNAME_NOT_MODIFIED The username was not modified CALL_ALREADY_ACCEPTED The call is already accepted CALL_ALREADY_DECLINED The call is already declined PHOTO_EXT_INVALID The photo extension is invalid -EXTERNAL_URL_INVALID The external media URL is invalid \ No newline at end of file +EXTERNAL_URL_INVALID The external media URL is invalid +CHAT_NOT_MODIFIED The chat settings were not modified \ No newline at end of file diff --git a/docs/source/index.rst b/docs/source/index.rst index 4d913d23..6a333d6d 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -26,7 +26,7 @@ Welcome to Pyrogram
- Schema Layer @@ -67,7 +67,7 @@ Features - **Fast**: Crypto parts are boosted up by TgCrypto_, a high-performance library written in pure C. - **Documented**: Pyrogram API methods, types and public interfaces are well documented. - **Type-hinted**: Exposed Pyrogram types and method parameters are all type-hinted. -- **Updated**, to the latest Telegram API version, currently Layer 91 on top of `MTProto 2.0`_. +- **Updated**, to the latest Telegram API version, currently Layer 95 on top of `MTProto 2.0`_. - **Pluggable**: The Smart Plugin system allows to write components with minimal boilerplate code. - **Comprehensive**: Execute any advanced action an official client is able to do, and even more. diff --git a/docs/source/start/Installation.rst b/docs/source/start/Installation.rst index c5c6cb31..6a6ceef8 100644 --- a/docs/source/start/Installation.rst +++ b/docs/source/start/Installation.rst @@ -82,7 +82,7 @@ If no error shows up you are good to go. >>> import pyrogram >>> pyrogram.__version__ - '0.11.0' + '0.12.0' .. _TgCrypto: https://docs.pyrogram.ml/resources/TgCrypto .. _develop: http://github.com/pyrogram/pyrogram diff --git a/pyrogram/__init__.py b/pyrogram/__init__.py index 3caa38b2..0ea55c13 100644 --- a/pyrogram/__init__.py +++ b/pyrogram/__init__.py @@ -37,7 +37,7 @@ __copyright__ = "Copyright (C) 2017-2019 Dan Tès str: - return dumps(self, cls=Encoder, indent=4) + return dumps(self, indent=4, default=default, ensure_ascii=False) def __bool__(self) -> bool: return True @@ -62,29 +64,18 @@ def remove_none(obj): return obj -class Encoder(JSONEncoder): - def default(self, o: Object): - try: - content = o.__dict__ - except AttributeError: - if isinstance(o, datetime): - return o.strftime("%d-%b-%Y %H:%M:%S") - else: - return repr(o) +def default(o: "Object"): + try: + content = {i: getattr(o, i) for i in o.__slots__} - name = o.__class__.__name__ - o = objects.get(getattr(o, "ID", None), None) - - if o is not None: - if o.startswith("pyrogram.client"): - r = remove_none(OrderedDict([("_", "pyrogram:" + name)] + [i for i in content.items()])) - r.pop("_client", None) - - return r - else: - return OrderedDict( - [("_", o.replace("pyrogram.api.types.", "telegram:"))] - + [i for i in content.items()] - ) + return remove_none( + OrderedDict( + [("_", o.QUALNAME)] + + [i for i in content.items()] + ) + ) + except AttributeError: + if isinstance(o, datetime): + return o.strftime("%d-%b-%Y %H:%M:%S") else: - return None + return repr(o) diff --git a/pyrogram/api/errors/__init__.py b/pyrogram/api/errors/__init__.py index ca65619c..8a1dc699 100644 --- a/pyrogram/api/errors/__init__.py +++ b/pyrogram/api/errors/__init__.py @@ -16,5 +16,5 @@ # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see . -from .exceptions import * from .error import UnknownError +from .exceptions import * diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py index 6835fa61..bf0401da 100644 --- a/pyrogram/client/client.py +++ b/pyrogram/client/client.py @@ -632,9 +632,9 @@ class Client(Methods, BaseClient): try: r = await self.send( functions.auth.SignIn( - self.phone_number, - phone_code_hash, - self.phone_code + phone_number=self.phone_number, + phone_code_hash=phone_code_hash, + phone_code=self.phone_code ) ) except PhoneNumberUnoccupied: @@ -645,11 +645,11 @@ class Client(Methods, BaseClient): try: r = await self.send( functions.auth.SignUp( - self.phone_number, - phone_code_hash, - self.phone_code, - self.first_name, - self.last_name + phone_number=self.phone_number, + phone_code_hash=phone_code_hash, + phone_code=self.phone_code, + first_name=self.first_name, + last_name=self.last_name ) ) except PhoneNumberOccupied: @@ -743,7 +743,11 @@ class Client(Methods, BaseClient): break if terms_of_service: - assert await self.send(functions.help.AcceptTermsOfService(terms_of_service.id)) + assert await self.send( + functions.help.AcceptTermsOfService( + id=terms_of_service.id + ) + ) self.password = None self.user_id = r.user.id @@ -1035,10 +1039,10 @@ class Client(Methods, BaseClient): raise ConnectionError("Client has not been started") if self.no_updates: - data = functions.InvokeWithoutUpdates(data) + data = functions.InvokeWithoutUpdates(query=data) if self.takeout_id: - data = functions.InvokeWithTakeout(self.takeout_id, data) + data = functions.InvokeWithTakeout(takeout_id=self.takeout_id, query=data) r = await self.session.send(data, retries, timeout) @@ -1350,7 +1354,7 @@ class Client(Methods, BaseClient): self.fetch_peers( self.send( functions.users.GetUsers( - id=[types.InputUser(peer_id, 0)] + id=[types.InputUser(user_id=peer_id, access_hash=0)] ) ) ) @@ -1358,7 +1362,7 @@ class Client(Methods, BaseClient): if str(peer_id).startswith("-100"): self.send( functions.channels.GetChannels( - id=[types.InputChannel(int(str(peer_id)[4:]), 0)] + id=[types.InputChannel(channel_id=int(str(peer_id)[4:]), access_hash=0)] ) ) else: @@ -1686,8 +1690,8 @@ class Client(Methods, BaseClient): hashes = await session.send( functions.upload.GetCdnFileHashes( - r.file_token, - offset + file_token=r.file_token, + offset=offset ) ) diff --git a/pyrogram/client/ext/utils.py b/pyrogram/client/ext/utils.py index 3d7d9408..baf6fe94 100644 --- a/pyrogram/client/ext/utils.py +++ b/pyrogram/client/ext/utils.py @@ -79,10 +79,10 @@ def get_peer_id(input_peer) -> int: def get_input_peer(peer_id: int, access_hash: int): return ( - types.InputPeerUser(peer_id, access_hash) if peer_id > 0 - else types.InputPeerChannel(int(str(peer_id)[4:]), access_hash) + types.InputPeerUser(user_id=peer_id, access_hash=access_hash) if peer_id > 0 + else types.InputPeerChannel(channel_id=int(str(peer_id)[4:]), access_hash=access_hash) if (str(peer_id).startswith("-100") and access_hash) - else types.InputPeerChat(-peer_id) + else types.InputPeerChat(chat_id=-peer_id) ) diff --git a/pyrogram/client/methods/bots/answer_callback_query.py b/pyrogram/client/methods/bots/answer_callback_query.py index ba33f7c2..03e5918c 100644 --- a/pyrogram/client/methods/bots/answer_callback_query.py +++ b/pyrogram/client/methods/bots/answer_callback_query.py @@ -21,12 +21,14 @@ from pyrogram.client.ext import BaseClient class AnswerCallbackQuery(BaseClient): - async def answer_callback_query(self, - callback_query_id: str, - text: str = None, - show_alert: bool = None, - url: str = None, - cache_time: int = 0): + async def answer_callback_query( + self, + callback_query_id: str, + text: str = None, + show_alert: bool = None, + url: str = None, + cache_time: int = 0 + ): """Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. diff --git a/pyrogram/client/methods/bots/get_game_high_scores.py b/pyrogram/client/methods/bots/get_game_high_scores.py index e58bc17e..0899def5 100644 --- a/pyrogram/client/methods/bots/get_game_high_scores.py +++ b/pyrogram/client/methods/bots/get_game_high_scores.py @@ -24,10 +24,12 @@ from pyrogram.client.ext import BaseClient class GetGameHighScores(BaseClient): - async def get_game_high_scores(self, - user_id: Union[int, str], - chat_id: Union[int, str], - message_id: int = None): + async def get_game_high_scores( + self, + user_id: Union[int, str], + chat_id: Union[int, str], + message_id: int = None + ): """Use this method to get data for high score tables. Args: diff --git a/pyrogram/client/methods/bots/get_inline_bot_results.py b/pyrogram/client/methods/bots/get_inline_bot_results.py index 6c370794..58e477b1 100644 --- a/pyrogram/client/methods/bots/get_inline_bot_results.py +++ b/pyrogram/client/methods/bots/get_inline_bot_results.py @@ -24,12 +24,14 @@ from pyrogram.client.ext import BaseClient class GetInlineBotResults(BaseClient): - async def get_inline_bot_results(self, - bot: Union[int, str], - query: str, - offset: str = "", - latitude: float = None, - longitude: float = None): + async def get_inline_bot_results( + self, + bot: Union[int, str], + query: str, + offset: str = "", + latitude: float = None, + longitude: float = None + ): """Use this method to get bot results via inline queries. You can then send a result using :obj:`send_inline_bot_result ` diff --git a/pyrogram/client/methods/bots/request_callback_answer.py b/pyrogram/client/methods/bots/request_callback_answer.py index 68c971ad..4b9382c9 100644 --- a/pyrogram/client/methods/bots/request_callback_answer.py +++ b/pyrogram/client/methods/bots/request_callback_answer.py @@ -23,10 +23,12 @@ from pyrogram.client.ext import BaseClient class RequestCallbackAnswer(BaseClient): - async def request_callback_answer(self, - chat_id: Union[int, str], - message_id: int, - callback_data: bytes): + async def request_callback_answer( + self, + chat_id: Union[int, str], + message_id: int, + callback_data: bytes + ): """Use this method to request a callback answer from bots. This is the equivalent of clicking an inline button containing callback data. diff --git a/pyrogram/client/methods/bots/send_game.py b/pyrogram/client/methods/bots/send_game.py index 0f3593b0..d16a4758 100644 --- a/pyrogram/client/methods/bots/send_game.py +++ b/pyrogram/client/methods/bots/send_game.py @@ -24,15 +24,19 @@ from pyrogram.client.ext import BaseClient class SendGame(BaseClient): - async def send_game(self, - chat_id: Union[int, str], - game_short_name: str, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + async def send_game( + self, + chat_id: Union[int, str], + game_short_name: str, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send a game. Args: diff --git a/pyrogram/client/methods/bots/send_inline_bot_result.py b/pyrogram/client/methods/bots/send_inline_bot_result.py index b204c9f2..4013c0ce 100644 --- a/pyrogram/client/methods/bots/send_inline_bot_result.py +++ b/pyrogram/client/methods/bots/send_inline_bot_result.py @@ -23,13 +23,15 @@ from pyrogram.client.ext import BaseClient class SendInlineBotResult(BaseClient): - async def send_inline_bot_result(self, - chat_id: Union[int, str], - query_id: int, - result_id: str, - disable_notification: bool = None, - reply_to_message_id: int = None, - hide_via: bool = None): + async def send_inline_bot_result( + self, + chat_id: Union[int, str], + query_id: int, + result_id: str, + disable_notification: bool = None, + reply_to_message_id: int = None, + hide_via: bool = None + ): """Use this method to send an inline bot result. Bot results can be retrieved using :obj:`get_inline_bot_results ` diff --git a/pyrogram/client/methods/bots/set_game_score.py b/pyrogram/client/methods/bots/set_game_score.py index f90b7f46..546afde5 100644 --- a/pyrogram/client/methods/bots/set_game_score.py +++ b/pyrogram/client/methods/bots/set_game_score.py @@ -24,13 +24,15 @@ from pyrogram.client.ext import BaseClient class SetGameScore(BaseClient): - async def set_game_score(self, - user_id: Union[int, str], - score: int, - force: bool = None, - disable_edit_message: bool = None, - chat_id: Union[int, str] = None, - message_id: int = None): + async def set_game_score( + self, + user_id: Union[int, str], + score: int, + force: bool = None, + disable_edit_message: bool = None, + chat_id: Union[int, str] = None, + message_id: int = None + ): # inline_message_id: str = None): TODO Add inline_message_id """Use this method to set the score of the specified user in a game. diff --git a/pyrogram/client/methods/chats/__init__.py b/pyrogram/client/methods/chats/__init__.py index 961038a8..c708453f 100644 --- a/pyrogram/client/methods/chats/__init__.py +++ b/pyrogram/client/methods/chats/__init__.py @@ -31,6 +31,7 @@ from .kick_chat_member import KickChatMember from .leave_chat import LeaveChat from .pin_chat_message import PinChatMessage from .promote_chat_member import PromoteChatMember +from .restrict_chat import RestrictChat from .restrict_chat_member import RestrictChatMember from .set_chat_description import SetChatDescription from .set_chat_photo import SetChatPhoto @@ -62,6 +63,7 @@ class Chats( GetChatPreview, IterDialogs, IterChatMembers, - UpdateChatUsername + UpdateChatUsername, + RestrictChat ): pass diff --git a/pyrogram/client/methods/chats/delete_chat_photo.py b/pyrogram/client/methods/chats/delete_chat_photo.py index 58fb2f56..ee5a1ac2 100644 --- a/pyrogram/client/methods/chats/delete_chat_photo.py +++ b/pyrogram/client/methods/chats/delete_chat_photo.py @@ -23,8 +23,10 @@ from ...ext import BaseClient class DeleteChatPhoto(BaseClient): - async def delete_chat_photo(self, - chat_id: Union[int, str]) -> bool: + async def delete_chat_photo( + self, + chat_id: Union[int, str] + ) -> bool: """Use this method to delete a chat photo. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/pyrogram/client/methods/chats/export_chat_invite_link.py b/pyrogram/client/methods/chats/export_chat_invite_link.py index 10ab8747..a034d184 100644 --- a/pyrogram/client/methods/chats/export_chat_invite_link.py +++ b/pyrogram/client/methods/chats/export_chat_invite_link.py @@ -23,8 +23,10 @@ from ...ext import BaseClient class ExportChatInviteLink(BaseClient): - async def export_chat_invite_link(self, - chat_id: Union[int, str]) -> str: + async def export_chat_invite_link( + self, + chat_id: Union[int, str] + ) -> str: """Use this method to generate a new invite link for a chat; any previously generated link is revoked. You must be an administrator in the chat for this to work and have the appropriate admin rights. @@ -45,7 +47,7 @@ class ExportChatInviteLink(BaseClient): if isinstance(peer, types.InputPeerChat): return await self.send( functions.messages.ExportChatInvite( - chat_id=peer.chat_id + peer=peer.chat_id ) ).link elif isinstance(peer, types.InputPeerChannel): diff --git a/pyrogram/client/methods/chats/get_chat.py b/pyrogram/client/methods/chats/get_chat.py index 422cc34d..bcacb1b8 100644 --- a/pyrogram/client/methods/chats/get_chat.py +++ b/pyrogram/client/methods/chats/get_chat.py @@ -24,8 +24,10 @@ from ...ext import BaseClient class GetChat(BaseClient): - async def get_chat(self, - chat_id: Union[int, str]) -> "pyrogram.Chat": + async def get_chat( + self, + chat_id: Union[int, str] + ) -> "pyrogram.Chat": """Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.) @@ -67,10 +69,10 @@ class GetChat(BaseClient): peer = await self.resolve_peer(chat_id) if isinstance(peer, types.InputPeerChannel): - r = await self.send(functions.channels.GetFullChannel(peer)) + r = await self.send(functions.channels.GetFullChannel(channel=peer)) elif isinstance(peer, (types.InputPeerUser, types.InputPeerSelf)): - r = await self.send(functions.users.GetFullUser(peer)) + r = await self.send(functions.users.GetFullUser(id=peer)) else: - r = await self.send(functions.messages.GetFullChat(peer.chat_id)) + r = await self.send(functions.messages.GetFullChat(chat_id=peer.chat_id)) return await pyrogram.Chat._parse_full(self, r) diff --git a/pyrogram/client/methods/chats/get_chat_member.py b/pyrogram/client/methods/chats/get_chat_member.py index eb54428c..ef8495cf 100644 --- a/pyrogram/client/methods/chats/get_chat_member.py +++ b/pyrogram/client/methods/chats/get_chat_member.py @@ -24,9 +24,11 @@ from ...ext import BaseClient class GetChatMember(BaseClient): - async def get_chat_member(self, - chat_id: Union[int, str], - user_id: Union[int, str]) -> "pyrogram.ChatMember": + async def get_chat_member( + self, + chat_id: Union[int, str], + user_id: Union[int, str] + ) -> "pyrogram.ChatMember": """Use this method to get information about one member of a chat. Args: diff --git a/pyrogram/client/methods/chats/get_chat_members.py b/pyrogram/client/methods/chats/get_chat_members.py index b0273c81..0daf399f 100644 --- a/pyrogram/client/methods/chats/get_chat_members.py +++ b/pyrogram/client/methods/chats/get_chat_members.py @@ -33,12 +33,14 @@ class Filters: class GetChatMembers(BaseClient): - async def get_chat_members(self, - chat_id: Union[int, str], - offset: int = 0, - limit: int = 200, - query: str = "", - filter: str = Filters.ALL) -> "pyrogram.ChatMembers": + async def get_chat_members( + self, + chat_id: Union[int, str], + offset: int = 0, + limit: int = 200, + query: str = "", + filter: str = Filters.ALL + ) -> "pyrogram.ChatMembers": """Use this method to get a chunk of the members list of a chat. You can get up to 200 chat members at once. @@ -92,7 +94,7 @@ class GetChatMembers(BaseClient): self, await self.send( functions.messages.GetFullChat( - peer.chat_id + chat_id=peer.chat_id ) ) ) diff --git a/pyrogram/client/methods/chats/get_chat_members_count.py b/pyrogram/client/methods/chats/get_chat_members_count.py index 227e4255..717b2289 100644 --- a/pyrogram/client/methods/chats/get_chat_members_count.py +++ b/pyrogram/client/methods/chats/get_chat_members_count.py @@ -23,8 +23,10 @@ from ...ext import BaseClient class GetChatMembersCount(BaseClient): - async def get_chat_members_count(self, - chat_id: Union[int, str]) -> int: + async def get_chat_members_count( + self, + chat_id: Union[int, str] + ) -> int: """Use this method to get the number of members in a chat. Args: diff --git a/pyrogram/client/methods/chats/get_chat_preview.py b/pyrogram/client/methods/chats/get_chat_preview.py index 434c385b..28e84c79 100644 --- a/pyrogram/client/methods/chats/get_chat_preview.py +++ b/pyrogram/client/methods/chats/get_chat_preview.py @@ -22,8 +22,10 @@ from ...ext import BaseClient class GetChatPreview(BaseClient): - def get_chat_preview(self, - invite_link: str): + def get_chat_preview( + self, + invite_link: str + ): """Use this method to get the preview of a chat using the invite link. This method only returns a chat preview, if you want to join a chat use :meth:`join_chat` diff --git a/pyrogram/client/methods/chats/get_dialogs.py b/pyrogram/client/methods/chats/get_dialogs.py index aa6ca912..2a7b1f7b 100644 --- a/pyrogram/client/methods/chats/get_dialogs.py +++ b/pyrogram/client/methods/chats/get_dialogs.py @@ -28,10 +28,12 @@ log = logging.getLogger(__name__) class GetDialogs(BaseClient): - async def get_dialogs(self, - offset_date: int = 0, - limit: int = 100, - pinned_only: bool = False) -> "pyrogram.Dialogs": + async def get_dialogs( + self, + offset_date: int = 0, + limit: int = 100, + pinned_only: bool = False + ) -> "pyrogram.Dialogs": """Use this method to get a chunk of the user's dialogs You can get up to 100 dialogs at once. diff --git a/pyrogram/client/methods/chats/iter_chat_members.py b/pyrogram/client/methods/chats/iter_chat_members.py index f9e3294f..b1d54325 100644 --- a/pyrogram/client/methods/chats/iter_chat_members.py +++ b/pyrogram/client/methods/chats/iter_chat_members.py @@ -41,11 +41,13 @@ QUERYABLE_FILTERS = (Filters.ALL, Filters.KICKED, Filters.RESTRICTED) class IterChatMembers(BaseClient): @async_generator - async def iter_chat_members(self, - chat_id: Union[int, str], - limit: int = 0, - query: str = "", - filter: str = Filters.ALL) -> Optional[AsyncGenerator["pyrogram.ChatMember", None]]: + async def iter_chat_members( + self, + chat_id: Union[int, str], + limit: int = 0, + query: str = "", + filter: str = Filters.ALL + ) -> Optional[AsyncGenerator["pyrogram.ChatMember", None]]: """Use this method to iterate through the members of a chat sequentially. This convenience method does the same as repeatedly calling :meth:`get_chat_members` in a loop, thus saving you diff --git a/pyrogram/client/methods/chats/iter_dialogs.py b/pyrogram/client/methods/chats/iter_dialogs.py index 712254e9..f8012787 100644 --- a/pyrogram/client/methods/chats/iter_dialogs.py +++ b/pyrogram/client/methods/chats/iter_dialogs.py @@ -26,9 +26,11 @@ from ...ext import BaseClient class IterDialogs(BaseClient): @async_generator - async def iter_dialogs(self, - limit: int = 0, - offset_date: int = 0) -> Optional[AsyncGenerator["pyrogram.Dialog", None]]: + async def iter_dialogs( + self, + limit: int = 0, + offset_date: int = 0 + ) -> Optional[AsyncGenerator["pyrogram.Dialog", None]]: """Use this method to iterate through a user's dialogs sequentially. This convenience method does the same as repeatedly calling :meth:`get_dialogs` in a loop, thus saving you from diff --git a/pyrogram/client/methods/chats/join_chat.py b/pyrogram/client/methods/chats/join_chat.py index 65300445..1d0314c3 100644 --- a/pyrogram/client/methods/chats/join_chat.py +++ b/pyrogram/client/methods/chats/join_chat.py @@ -22,8 +22,10 @@ from ...ext import BaseClient class JoinChat(BaseClient): - async def join_chat(self, - chat_id: str): + async def join_chat( + self, + chat_id: str + ): """Use this method to join a group chat or channel. Args: diff --git a/pyrogram/client/methods/chats/kick_chat_member.py b/pyrogram/client/methods/chats/kick_chat_member.py index 096480a0..24b424e6 100644 --- a/pyrogram/client/methods/chats/kick_chat_member.py +++ b/pyrogram/client/methods/chats/kick_chat_member.py @@ -24,10 +24,12 @@ from ...ext import BaseClient class KickChatMember(BaseClient): - async def kick_chat_member(self, - chat_id: Union[int, str], - user_id: Union[int, str], - until_date: int = 0) -> Union["pyrogram.Message", bool]: + async def kick_chat_member( + self, + chat_id: Union[int, str], + user_id: Union[int, str], + until_date: int = 0 + ) -> Union["pyrogram.Message", bool]: """Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. You must be an administrator in the chat for this to work and must diff --git a/pyrogram/client/methods/chats/leave_chat.py b/pyrogram/client/methods/chats/leave_chat.py index aad3f802..14e18f32 100644 --- a/pyrogram/client/methods/chats/leave_chat.py +++ b/pyrogram/client/methods/chats/leave_chat.py @@ -23,9 +23,11 @@ from ...ext import BaseClient class LeaveChat(BaseClient): - async def leave_chat(self, - chat_id: Union[int, str], - delete: bool = False): + async def leave_chat( + self, + chat_id: Union[int, str], + delete: bool = False + ): """Use this method to leave a group chat or channel. Args: diff --git a/pyrogram/client/methods/chats/pin_chat_message.py b/pyrogram/client/methods/chats/pin_chat_message.py index 6e01f77a..7acee925 100644 --- a/pyrogram/client/methods/chats/pin_chat_message.py +++ b/pyrogram/client/methods/chats/pin_chat_message.py @@ -23,10 +23,12 @@ from ...ext import BaseClient class PinChatMessage(BaseClient): - async def pin_chat_message(self, - chat_id: Union[int, str], - message_id: int, - disable_notification: bool = None) -> bool: + async def pin_chat_message( + self, + chat_id: Union[int, str], + message_id: int, + disable_notification: bool = None + ) -> bool: """Use this method to pin a message in a group, channel or your own chat. You must be an administrator in the chat for this to work and must have the "can_pin_messages" admin right in the supergroup or "can_edit_messages" admin right in the channel. @@ -55,3 +57,5 @@ class PinChatMessage(BaseClient): silent=disable_notification or None ) ) + + return True diff --git a/pyrogram/client/methods/chats/promote_chat_member.py b/pyrogram/client/methods/chats/promote_chat_member.py index e847321b..f1791846 100644 --- a/pyrogram/client/methods/chats/promote_chat_member.py +++ b/pyrogram/client/methods/chats/promote_chat_member.py @@ -23,17 +23,19 @@ from ...ext import BaseClient class PromoteChatMember(BaseClient): - async def promote_chat_member(self, - chat_id: Union[int, str], - user_id: Union[int, str], - can_change_info: bool = True, - can_post_messages: bool = False, - can_edit_messages: bool = False, - can_delete_messages: bool = True, - can_restrict_members: bool = True, - can_invite_users: bool = True, - can_pin_messages: bool = False, - can_promote_members: bool = False) -> bool: + async def promote_chat_member( + self, + chat_id: Union[int, str], + user_id: Union[int, str], + can_change_info: bool = True, + can_post_messages: bool = False, + can_edit_messages: bool = False, + can_delete_messages: bool = True, + can_restrict_members: bool = True, + can_invite_users: bool = True, + can_pin_messages: bool = False, + can_promote_members: bool = False + ) -> bool: """Use this method to promote or demote a user in a supergroup or a channel. You must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/pyrogram/client/methods/chats/restrict_chat.py b/pyrogram/client/methods/chats/restrict_chat.py new file mode 100644 index 00000000..ca3e8055 --- /dev/null +++ b/pyrogram/client/methods/chats/restrict_chat.py @@ -0,0 +1,143 @@ +# Pyrogram - Telegram MTProto API Client Library for Python +# Copyright (C) 2017-2019 Dan Tès +# +# 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 Union + +from pyrogram.api import functions, types +from ...ext import BaseClient +from ...types.user_and_chats import Chat + + +class RestrictChat(BaseClient): + def restrict_chat( + self, + chat_id: Union[int, str], + can_send_messages: bool = False, + can_send_media_messages: bool = False, + can_send_other_messages: bool = False, + can_add_web_page_previews: bool = False, + can_send_polls: bool = False, + can_change_info: bool = False, + can_invite_users: bool = False, + can_pin_messages: bool = False + ) -> Chat: + """Use this method to restrict a chat. + Pass True for all boolean parameters to lift restrictions from a chat. + + Args: + chat_id (``int`` | ``str``): + Unique identifier (int) or username (str) of the target chat. + + can_send_messages (``bool``, *optional*): + Pass True, if the user can send text messages, contacts, locations and venues. + + can_send_media_messages (``bool``, *optional*): + Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, + implies can_send_messages. + + can_send_other_messages (``bool``, *optional*): + Pass True, if the user can send animations, games, stickers and use inline bots, + implies can_send_media_messages. + + can_add_web_page_previews (``bool``, *optional*): + Pass True, if the user may add web page previews to their messages, implies can_send_media_messages. + + can_send_polls (``bool``, *optional*): + Pass True, if the user can send polls, implies can_send_media_messages. + + can_change_info (``bool``, *optional*): + Pass True, if the user can change the chat title, photo and other settings. + + can_invite_users (``bool``, *optional*): + Pass True, if the user can invite new users to the chat. + + can_pin_messages (``bool``, *optional*): + Pass True, if the user can pin messages. + + Returns: + On success, a :obj:`Chat ` object is returned. + + Raises: + :class:`Error ` in case of a Telegram RPC error. + """ + send_messages = True + send_media = True + send_stickers = True + send_gifs = True + send_games = True + send_inline = True + embed_links = True + send_polls = True + change_info = True + invite_users = True + pin_messages = True + + if can_send_messages: + send_messages = None + + if can_send_media_messages: + send_messages = None + send_media = None + + if can_send_other_messages: + send_messages = None + send_media = None + send_stickers = None + send_gifs = None + send_games = None + send_inline = None + + if can_add_web_page_previews: + send_messages = None + send_media = None + embed_links = None + + if can_send_polls: + send_messages = None + send_polls = None + + if can_change_info: + change_info = None + + if can_invite_users: + invite_users = None + + if can_pin_messages: + pin_messages = None + + r = self.send( + functions.messages.EditChatDefaultBannedRights( + peer=self.resolve_peer(chat_id), + banned_rights=types.ChatBannedRights( + until_date=0, + send_messages=send_messages, + send_media=send_media, + send_stickers=send_stickers, + send_gifs=send_gifs, + send_games=send_games, + send_inline=send_inline, + embed_links=embed_links, + send_polls=send_polls, + change_info=change_info, + invite_users=invite_users, + pin_messages=pin_messages + ) + ) + ) + + return Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/client/methods/chats/restrict_chat_member.py b/pyrogram/client/methods/chats/restrict_chat_member.py index c42869c8..7b33f37a 100644 --- a/pyrogram/client/methods/chats/restrict_chat_member.py +++ b/pyrogram/client/methods/chats/restrict_chat_member.py @@ -20,17 +20,24 @@ from typing import Union from pyrogram.api import functions, types from ...ext import BaseClient +from ...types.user_and_chats import Chat class RestrictChatMember(BaseClient): - async def restrict_chat_member(self, - chat_id: Union[int, str], - user_id: Union[int, str], - until_date: int = 0, - can_send_messages: bool = False, - can_send_media_messages: bool = False, - can_send_other_messages: bool = False, - can_add_web_page_previews: bool = False) -> bool: + async def restrict_chat_member( + self, + chat_id: Union[int, str], + user_id: Union[int, str], + until_date: int = 0, + can_send_messages: bool = False, + can_send_media_messages: bool = False, + can_send_other_messages: bool = False, + can_add_web_page_previews: bool = False, + can_send_polls: bool = False, + can_change_info: bool = False, + can_invite_users: bool = False, + can_pin_messages: bool = False + ) -> Chat: """Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. @@ -60,10 +67,22 @@ class RestrictChatMember(BaseClient): implies can_send_media_messages. can_add_web_page_previews (``bool``, *optional*): - Pass True, if the user may add web page previews to their messages, implies can_send_media_messages + Pass True, if the user may add web page previews to their messages, implies can_send_media_messages. + + can_send_polls (``bool``, *optional*): + Pass True, if the user can send polls, implies can_send_media_messages. + + can_change_info (``bool``, *optional*): + Pass True, if the user can change the chat title, photo and other settings. + + can_invite_users (``bool``, *optional*): + Pass True, if the user can invite new users to the chat. + + can_pin_messages (``bool``, *optional*): + Pass True, if the user can pin messages. Returns: - True on success. + On success, a :obj:`Chat ` object is returned. Raises: :class:`Error ` in case of a Telegram RPC error. @@ -75,6 +94,10 @@ class RestrictChatMember(BaseClient): send_games = True send_inline = True embed_links = True + send_polls = True + change_info = True + invite_users = True + pin_messages = True if can_send_messages: send_messages = None @@ -84,6 +107,7 @@ class RestrictChatMember(BaseClient): send_media = None if can_send_other_messages: + send_messages = None send_media = None send_stickers = None send_gifs = None @@ -91,10 +115,24 @@ class RestrictChatMember(BaseClient): send_inline = None if can_add_web_page_previews: + send_messages = None send_media = None embed_links = None - await self.send( + if can_send_polls: + send_messages = None + send_polls = None + + if can_change_info: + change_info = None + + if can_invite_users: + invite_users = None + + if can_pin_messages: + pin_messages = None + + r = await self.send( functions.channels.EditBanned( channel=await self.resolve_peer(chat_id), user_id=await self.resolve_peer(user_id), @@ -106,9 +144,13 @@ class RestrictChatMember(BaseClient): send_gifs=send_gifs, send_games=send_games, send_inline=send_inline, - embed_links=embed_links + embed_links=embed_links, + send_polls=send_polls, + change_info=change_info, + invite_users=invite_users, + pin_messages=pin_messages ) ) ) - return True + return Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/client/methods/chats/set_chat_description.py b/pyrogram/client/methods/chats/set_chat_description.py index cacbb06e..3c388303 100644 --- a/pyrogram/client/methods/chats/set_chat_description.py +++ b/pyrogram/client/methods/chats/set_chat_description.py @@ -23,9 +23,11 @@ from ...ext import BaseClient class SetChatDescription(BaseClient): - async def set_chat_description(self, - chat_id: Union[int, str], - description: str) -> bool: + async def set_chat_description( + self, + chat_id: Union[int, str], + description: str + ) -> bool: """Use this method to change the description of a supergroup or a channel. You must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/pyrogram/client/methods/chats/set_chat_photo.py b/pyrogram/client/methods/chats/set_chat_photo.py index 9f5c1d3a..ce4fbb18 100644 --- a/pyrogram/client/methods/chats/set_chat_photo.py +++ b/pyrogram/client/methods/chats/set_chat_photo.py @@ -26,9 +26,11 @@ from ...ext import BaseClient class SetChatPhoto(BaseClient): - async def set_chat_photo(self, - chat_id: Union[int, str], - photo: str) -> bool: + async def set_chat_photo( + self, + chat_id: Union[int, str], + photo: str + ) -> bool: """Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/pyrogram/client/methods/chats/set_chat_title.py b/pyrogram/client/methods/chats/set_chat_title.py index bf247484..09b53d7e 100644 --- a/pyrogram/client/methods/chats/set_chat_title.py +++ b/pyrogram/client/methods/chats/set_chat_title.py @@ -23,9 +23,11 @@ from ...ext import BaseClient class SetChatTitle(BaseClient): - async def set_chat_title(self, - chat_id: Union[int, str], - title: str) -> bool: + async def set_chat_title( + self, + chat_id: Union[int, str], + title: str + ) -> bool: """Use this method to change the title of a chat. Titles can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights. diff --git a/pyrogram/client/methods/chats/unban_chat_member.py b/pyrogram/client/methods/chats/unban_chat_member.py index e4b8f61e..e34ea14d 100644 --- a/pyrogram/client/methods/chats/unban_chat_member.py +++ b/pyrogram/client/methods/chats/unban_chat_member.py @@ -23,9 +23,11 @@ from ...ext import BaseClient class UnbanChatMember(BaseClient): - async def unban_chat_member(self, - chat_id: Union[int, str], - user_id: Union[int, str]) -> bool: + async def unban_chat_member( + self, + chat_id: Union[int, str], + user_id: Union[int, str] + ) -> bool: """Use this method to unban a previously kicked user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, etc. You must be an administrator for this to work. diff --git a/pyrogram/client/methods/chats/unpin_chat_message.py b/pyrogram/client/methods/chats/unpin_chat_message.py index 89e214c0..259cd8a1 100644 --- a/pyrogram/client/methods/chats/unpin_chat_message.py +++ b/pyrogram/client/methods/chats/unpin_chat_message.py @@ -23,8 +23,10 @@ from ...ext import BaseClient class UnpinChatMessage(BaseClient): - async def unpin_chat_message(self, - chat_id: Union[int, str]) -> bool: + async def unpin_chat_message( + self, + chat_id: Union[int, str] + ) -> bool: """Use this method to unpin a message in a group, channel or your own chat. You must be an administrator in the chat for this to work and must have the "can_pin_messages" admin right in the supergroup or "can_edit_messages" admin right in the channel. diff --git a/pyrogram/client/methods/chats/update_chat_username.py b/pyrogram/client/methods/chats/update_chat_username.py index 156ee6f8..cc6416a9 100644 --- a/pyrogram/client/methods/chats/update_chat_username.py +++ b/pyrogram/client/methods/chats/update_chat_username.py @@ -23,9 +23,11 @@ from ...ext import BaseClient class UpdateChatUsername(BaseClient): - def update_chat_username(self, - chat_id: Union[int, str], - username: Union[str, None]) -> bool: + def update_chat_username( + self, + chat_id: Union[int, str], + username: Union[str, None] + ) -> bool: """Use this method to update a channel or a supergroup username. To update your own username (for users only, not bots) you can use :meth:`update_username`. @@ -45,7 +47,7 @@ class UpdateChatUsername(BaseClient): """ peer = self.resolve_peer(chat_id) - + if isinstance(peer, types.InputPeerChannel): return bool( self.send( diff --git a/pyrogram/client/methods/contacts/add_contacts.py b/pyrogram/client/methods/contacts/add_contacts.py index cf78c2ac..a0db8fa9 100644 --- a/pyrogram/client/methods/contacts/add_contacts.py +++ b/pyrogram/client/methods/contacts/add_contacts.py @@ -24,8 +24,10 @@ from ...ext import BaseClient class AddContacts(BaseClient): - async def add_contacts(self, - contacts: List["pyrogram.InputPhoneContact"]): + async def add_contacts( + self, + contacts: List["pyrogram.InputPhoneContact"] + ): """Use this method to add contacts to your Telegram address book. Args: diff --git a/pyrogram/client/methods/contacts/delete_contacts.py b/pyrogram/client/methods/contacts/delete_contacts.py index d8da0e1e..1934b22c 100644 --- a/pyrogram/client/methods/contacts/delete_contacts.py +++ b/pyrogram/client/methods/contacts/delete_contacts.py @@ -24,8 +24,10 @@ from ...ext import BaseClient class DeleteContacts(BaseClient): - async def delete_contacts(self, - ids: List[int]): + async def delete_contacts( + self, + ids: List[int] + ): """Use this method to delete contacts from your Telegram address book Args: diff --git a/pyrogram/client/methods/contacts/get_contacts.py b/pyrogram/client/methods/contacts/get_contacts.py index 0451683f..92185f28 100644 --- a/pyrogram/client/methods/contacts/get_contacts.py +++ b/pyrogram/client/methods/contacts/get_contacts.py @@ -39,7 +39,7 @@ class GetContacts(BaseClient): """ while True: try: - contacts = await self.send(functions.contacts.GetContacts(0)) + contacts = await self.send(functions.contacts.GetContacts(hash=0)) except FloodWait as e: log.warning("get_contacts flood: waiting {} seconds".format(e.x)) await asyncio.sleep(e.x) diff --git a/pyrogram/client/methods/decorators/on_callback_query.py b/pyrogram/client/methods/decorators/on_callback_query.py index bf0a823a..f030f929 100644 --- a/pyrogram/client/methods/decorators/on_callback_query.py +++ b/pyrogram/client/methods/decorators/on_callback_query.py @@ -25,9 +25,11 @@ from ...ext import BaseClient class OnCallbackQuery(BaseClient): - def on_callback_query(self=None, - filters=None, - group: int = 0) -> callable: + def on_callback_query( + self=None, + filters=None, + group: int = 0 + ) -> callable: """Use this decorator to automatically register a function for handling callback queries. This does the same thing as :meth:`add_handler` using the :class:`CallbackQueryHandler`. diff --git a/pyrogram/client/methods/decorators/on_deleted_messages.py b/pyrogram/client/methods/decorators/on_deleted_messages.py index 1b1a602b..b5a95381 100644 --- a/pyrogram/client/methods/decorators/on_deleted_messages.py +++ b/pyrogram/client/methods/decorators/on_deleted_messages.py @@ -25,9 +25,11 @@ from ...ext import BaseClient class OnDeletedMessages(BaseClient): - def on_deleted_messages(self=None, - filters=None, - group: int = 0) -> callable: + def on_deleted_messages( + self=None, + filters=None, + group: int = 0 + ) -> callable: """Use this decorator to automatically register a function for handling deleted messages. This does the same thing as :meth:`add_handler` using the :class:`DeletedMessagesHandler`. diff --git a/pyrogram/client/methods/decorators/on_message.py b/pyrogram/client/methods/decorators/on_message.py index c2f35a19..41eb73e5 100644 --- a/pyrogram/client/methods/decorators/on_message.py +++ b/pyrogram/client/methods/decorators/on_message.py @@ -25,9 +25,11 @@ from ...ext import BaseClient class OnMessage(BaseClient): - def on_message(self=None, - filters=None, - group: int = 0) -> callable: + def on_message( + self=None, + filters=None, + group: int = 0 + ) -> callable: """Use this decorator to automatically register a function for handling messages. This does the same thing as :meth:`add_handler` using the :class:`MessageHandler`. diff --git a/pyrogram/client/methods/decorators/on_raw_update.py b/pyrogram/client/methods/decorators/on_raw_update.py index 2deedb00..a176ab50 100644 --- a/pyrogram/client/methods/decorators/on_raw_update.py +++ b/pyrogram/client/methods/decorators/on_raw_update.py @@ -24,8 +24,10 @@ from ...ext import BaseClient class OnRawUpdate(BaseClient): - def on_raw_update(self=None, - group: int = 0) -> callable: + def on_raw_update( + self=None, + group: int = 0 + ) -> callable: """Use this decorator to automatically register a function for handling raw updates. This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`. diff --git a/pyrogram/client/methods/decorators/on_user_status.py b/pyrogram/client/methods/decorators/on_user_status.py index 6198c9cd..580dc498 100644 --- a/pyrogram/client/methods/decorators/on_user_status.py +++ b/pyrogram/client/methods/decorators/on_user_status.py @@ -25,9 +25,11 @@ from ...ext import BaseClient class OnUserStatus(BaseClient): - def on_user_status(self=None, - filters=None, - group: int = 0) -> callable: + def on_user_status( + self=None, + filters=None, + group: int = 0 + ) -> callable: """Use this decorator to automatically register a function for handling user status updates. This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`. diff --git a/pyrogram/client/methods/messages/close_poll.py b/pyrogram/client/methods/messages/close_poll.py index c2d2706b..ac4fc197 100644 --- a/pyrogram/client/methods/messages/close_poll.py +++ b/pyrogram/client/methods/messages/close_poll.py @@ -23,9 +23,11 @@ from pyrogram.client.ext import BaseClient class ClosePoll(BaseClient): - def close_poll(self, - chat_id: Union[int, str], - message_id: id) -> bool: + def close_poll( + self, + chat_id: Union[int, str], + message_id: id + ) -> bool: """Use this method to close (stop) a poll. Closed polls can't be reopened and nobody will be able to vote in it anymore. diff --git a/pyrogram/client/methods/messages/delete_messages.py b/pyrogram/client/methods/messages/delete_messages.py index e7c48e43..981d99af 100644 --- a/pyrogram/client/methods/messages/delete_messages.py +++ b/pyrogram/client/methods/messages/delete_messages.py @@ -23,10 +23,12 @@ from pyrogram.client.ext import BaseClient class DeleteMessages(BaseClient): - async def delete_messages(self, - chat_id: Union[int, str], - message_ids: Iterable[int], - revoke: bool = True) -> bool: + async def delete_messages( + self, + chat_id: Union[int, str], + message_ids: Iterable[int], + revoke: bool = True + ) -> bool: """Use this method to delete messages, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. diff --git a/pyrogram/client/methods/messages/download_media.py b/pyrogram/client/methods/messages/download_media.py index a3b1fe95..9b3b93fc 100644 --- a/pyrogram/client/methods/messages/download_media.py +++ b/pyrogram/client/methods/messages/download_media.py @@ -24,12 +24,14 @@ from pyrogram.client.ext import BaseClient class DownloadMedia(BaseClient): - async def download_media(self, - message: Union["pyrogram.Message", str], - file_name: str = "", - block: bool = True, - progress: callable = None, - progress_args: tuple = ()) -> Union[str, None]: + async def download_media( + self, + message: Union["pyrogram.Message", str], + file_name: str = "", + block: bool = True, + progress: callable = None, + progress_args: tuple = () + ) -> Union[str, None]: """Use this method to download the media from a Message. Args: @@ -106,15 +108,15 @@ class DownloadMedia(BaseClient): else: raise ValueError(error_message) elif isinstance(message, ( - pyrogram.Photo, - pyrogram.PhotoSize, - pyrogram.Audio, - pyrogram.Document, - pyrogram.Video, - pyrogram.Voice, - pyrogram.VideoNote, - pyrogram.Sticker, - pyrogram.Animation + pyrogram.Photo, + pyrogram.PhotoSize, + pyrogram.Audio, + pyrogram.Document, + pyrogram.Video, + pyrogram.Voice, + pyrogram.VideoNote, + pyrogram.Sticker, + pyrogram.Animation )): if isinstance(message, pyrogram.Photo): media = pyrogram.Document( diff --git a/pyrogram/client/methods/messages/edit_message_caption.py b/pyrogram/client/methods/messages/edit_message_caption.py index 310b56aa..3aea6022 100644 --- a/pyrogram/client/methods/messages/edit_message_caption.py +++ b/pyrogram/client/methods/messages/edit_message_caption.py @@ -24,12 +24,14 @@ from pyrogram.client.ext import BaseClient class EditMessageCaption(BaseClient): - async def edit_message_caption(self, - chat_id: Union[int, str], - message_id: int, - caption: str, - parse_mode: str = "", - reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "pyrogram.Message": + async def edit_message_caption( + self, + chat_id: Union[int, str], + message_id: int, + caption: str, + parse_mode: str = "", + reply_markup: "pyrogram.InlineKeyboardMarkup" = None + ) -> "pyrogram.Message": """Use this method to edit captions of messages. Args: diff --git a/pyrogram/client/methods/messages/edit_message_media.py b/pyrogram/client/methods/messages/edit_message_media.py index 6c921968..dd5e2185 100644 --- a/pyrogram/client/methods/messages/edit_message_media.py +++ b/pyrogram/client/methods/messages/edit_message_media.py @@ -33,11 +33,13 @@ from pyrogram.client.types.input_media import InputMedia class EditMessageMedia(BaseClient): - async def edit_message_media(self, - chat_id: Union[int, str], - message_id: int, - media: InputMedia, - reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "pyrogram.Message": + async def edit_message_media( + self, + chat_id: Union[int, str], + message_id: int, + media: InputMedia, + reply_markup: "pyrogram.InlineKeyboardMarkup" = None + ) -> "pyrogram.Message": """Use this method to edit audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, @@ -131,7 +133,9 @@ class EditMessageMedia(BaseClient): w=media.width, h=media.height ), - types.DocumentAttributeFilename(os.path.basename(media.media)) + types.DocumentAttributeFilename( + file_name=os.path.basename(media.media) + ) ] ) ) @@ -187,7 +191,9 @@ class EditMessageMedia(BaseClient): performer=media.performer, title=media.title ), - types.DocumentAttributeFilename(os.path.basename(media.media)) + types.DocumentAttributeFilename( + file_name=os.path.basename(media.media) + ) ] ) ) @@ -244,7 +250,9 @@ class EditMessageMedia(BaseClient): w=media.width, h=media.height ), - types.DocumentAttributeFilename(os.path.basename(media.media)), + types.DocumentAttributeFilename( + file_name=os.path.basename(media.media) + ), types.DocumentAttributeAnimated() ] ) @@ -296,7 +304,9 @@ class EditMessageMedia(BaseClient): thumb=None if media.thumb is None else self.save_file(media.thumb), file=await self.save_file(media.media), attributes=[ - types.DocumentAttributeFilename(os.path.basename(media.media)) + types.DocumentAttributeFilename( + file_name=os.path.basename(media.media) + ) ] ) ) diff --git a/pyrogram/client/methods/messages/edit_message_reply_markup.py b/pyrogram/client/methods/messages/edit_message_reply_markup.py index 01c8254a..3fb52e8b 100644 --- a/pyrogram/client/methods/messages/edit_message_reply_markup.py +++ b/pyrogram/client/methods/messages/edit_message_reply_markup.py @@ -24,10 +24,12 @@ from pyrogram.client.ext import BaseClient class EditMessageReplyMarkup(BaseClient): - async def edit_message_reply_markup(self, - chat_id: Union[int, str], - message_id: int, - reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "pyrogram.Message": + async def edit_message_reply_markup( + self, + chat_id: Union[int, str], + message_id: int, + reply_markup: "pyrogram.InlineKeyboardMarkup" = None + ) -> "pyrogram.Message": """Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). Args: diff --git a/pyrogram/client/methods/messages/edit_message_text.py b/pyrogram/client/methods/messages/edit_message_text.py index d850c09f..48028bd5 100644 --- a/pyrogram/client/methods/messages/edit_message_text.py +++ b/pyrogram/client/methods/messages/edit_message_text.py @@ -24,13 +24,15 @@ from pyrogram.client.ext import BaseClient class EditMessageText(BaseClient): - async def edit_message_text(self, - chat_id: Union[int, str], - message_id: int, - text: str, - parse_mode: str = "", - disable_web_page_preview: bool = None, - reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "pyrogram.Message": + async def edit_message_text( + self, + chat_id: Union[int, str], + message_id: int, + text: str, + parse_mode: str = "", + disable_web_page_preview: bool = None, + reply_markup: "pyrogram.InlineKeyboardMarkup" = None + ) -> "pyrogram.Message": """Use this method to edit text messages. Args: diff --git a/pyrogram/client/methods/messages/forward_messages.py b/pyrogram/client/methods/messages/forward_messages.py index 77bd2b3c..cad6167f 100644 --- a/pyrogram/client/methods/messages/forward_messages.py +++ b/pyrogram/client/methods/messages/forward_messages.py @@ -24,11 +24,13 @@ from ...ext import BaseClient class ForwardMessages(BaseClient): - async def forward_messages(self, - chat_id: Union[int, str], - from_chat_id: Union[int, str], - message_ids: Iterable[int], - disable_notification: bool = None) -> "pyrogram.Messages": + async def forward_messages( + self, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_ids: Iterable[int], + disable_notification: bool = None + ) -> "pyrogram.Messages": """Use this method to forward messages of any kind. Args: diff --git a/pyrogram/client/methods/messages/get_history.py b/pyrogram/client/methods/messages/get_history.py index 88e69244..961d7ecb 100644 --- a/pyrogram/client/methods/messages/get_history.py +++ b/pyrogram/client/methods/messages/get_history.py @@ -29,13 +29,15 @@ log = logging.getLogger(__name__) class GetHistory(BaseClient): - async def get_history(self, - chat_id: Union[int, str], - limit: int = 100, - offset: int = 0, - offset_id: int = 0, - offset_date: int = 0, - reverse: bool = False): + async def get_history( + self, + chat_id: Union[int, str], + limit: int = 100, + offset: int = 0, + offset_id: int = 0, + offset_date: int = 0, + reverse: bool = False + ): """Use this method to retrieve a chunk of the history of a chat. You can get up to 100 messages at once. diff --git a/pyrogram/client/methods/messages/get_messages.py b/pyrogram/client/methods/messages/get_messages.py index a7b9b751..f4b3a3e2 100644 --- a/pyrogram/client/methods/messages/get_messages.py +++ b/pyrogram/client/methods/messages/get_messages.py @@ -29,11 +29,13 @@ log = logging.getLogger(__name__) class GetMessages(BaseClient): - async def get_messages(self, - chat_id: Union[int, str], - message_ids: Union[int, Iterable[int]] = None, - reply_to_message_ids: Union[int, Iterable[int]] = None, - replies: int = 1) -> Union["pyrogram.Message", "pyrogram.Messages"]: + async def get_messages( + self, + chat_id: Union[int, str], + message_ids: Union[int, Iterable[int]] = None, + reply_to_message_ids: Union[int, Iterable[int]] = None, + replies: int = 1 + ) -> Union["pyrogram.Message", "pyrogram.Messages"]: """Use this method to get one or more messages that belong to a specific chat. You can retrieve up to 200 messages at once. @@ -76,7 +78,7 @@ class GetMessages(BaseClient): is_iterable = not isinstance(ids, int) ids = list(ids) if is_iterable else [ids] - ids = [ids_type(i) for i in ids] + ids = [ids_type(id=i) for i in ids] if isinstance(peer, types.InputPeerChannel): rpc = functions.channels.GetMessages(channel=peer, id=ids) diff --git a/pyrogram/client/methods/messages/iter_history.py b/pyrogram/client/methods/messages/iter_history.py index 1a977998..89836927 100644 --- a/pyrogram/client/methods/messages/iter_history.py +++ b/pyrogram/client/methods/messages/iter_history.py @@ -26,13 +26,15 @@ from ...ext import BaseClient class IterHistory(BaseClient): @async_generator - async def iter_history(self, - chat_id: Union[int, str], - limit: int = 0, - offset: int = 0, - offset_id: int = 0, - offset_date: int = 0, - reverse: bool = False) -> Optional[AsyncGenerator["pyrogram.Message", None]]: + async def iter_history( + self, + chat_id: Union[int, str], + limit: int = 0, + offset: int = 0, + offset_id: int = 0, + offset_date: int = 0, + reverse: bool = False + ) -> Optional[AsyncGenerator["pyrogram.Message", None]]: """Use this method to iterate through a chat history sequentially. This convenience method does the same as repeatedly calling :meth:`get_history` in a loop, thus saving you from diff --git a/pyrogram/client/methods/messages/retract_vote.py b/pyrogram/client/methods/messages/retract_vote.py index 7893f768..e7ffe19b 100644 --- a/pyrogram/client/methods/messages/retract_vote.py +++ b/pyrogram/client/methods/messages/retract_vote.py @@ -23,9 +23,11 @@ from pyrogram.client.ext import BaseClient class RetractVote(BaseClient): - def retract_vote(self, - chat_id: Union[int, str], - message_id: id) -> bool: + def retract_vote( + self, + chat_id: Union[int, str], + message_id: id + ) -> bool: """Use this method to retract your vote in a poll. Args: diff --git a/pyrogram/client/methods/messages/send_animation.py b/pyrogram/client/methods/messages/send_animation.py index 09db4bf0..352bc8e8 100644 --- a/pyrogram/client/methods/messages/send_animation.py +++ b/pyrogram/client/methods/messages/send_animation.py @@ -28,23 +28,27 @@ from pyrogram.client.ext import BaseClient, utils class SendAnimation(BaseClient): - async def send_animation(self, - chat_id: Union[int, str], - animation: str, - caption: str = "", - parse_mode: str = "", - duration: int = 0, - width: int = 0, - height: int = 0, - thumb: str = None, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_animation( + self, + chat_id: Union[int, str], + animation: str, + caption: str = "", + parse_mode: str = "", + duration: int = 0, + width: int = 0, + height: int = 0, + thumb: str = None, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send animation files (animation or H.264/MPEG-4 AVC video without sound). Args: @@ -141,7 +145,7 @@ class SendAnimation(BaseClient): w=width, h=height ), - types.DocumentAttributeFilename(os.path.basename(animation)), + types.DocumentAttributeFilename(file_name=os.path.basename(animation)), types.DocumentAttributeAnimated() ] ) diff --git a/pyrogram/client/methods/messages/send_audio.py b/pyrogram/client/methods/messages/send_audio.py index 3d67a222..cfd6d412 100644 --- a/pyrogram/client/methods/messages/send_audio.py +++ b/pyrogram/client/methods/messages/send_audio.py @@ -28,22 +28,26 @@ from pyrogram.client.ext import BaseClient, utils class SendAudio(BaseClient): - async def send_audio(self, - chat_id: Union[int, str], - audio: str, - caption: str = "", - parse_mode: str = "", - duration: int = 0, - performer: str = None, - title: str = None, - thumb: str = None, disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_audio( + self, + chat_id: Union[int, str], + audio: str, + caption: str = "", + parse_mode: str = "", + duration: int = 0, + performer: str = None, + title: str = None, + thumb: str = None, disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send audio files. For sending voice messages, use the :obj:`send_voice()` method instead. @@ -141,7 +145,7 @@ class SendAudio(BaseClient): performer=performer, title=title ), - types.DocumentAttributeFilename(os.path.basename(audio)) + types.DocumentAttributeFilename(file_name=os.path.basename(audio)) ] ) elif audio.startswith("http"): diff --git a/pyrogram/client/methods/messages/send_cached_media.py b/pyrogram/client/methods/messages/send_cached_media.py index afcde68d..42516a5a 100644 --- a/pyrogram/client/methods/messages/send_cached_media.py +++ b/pyrogram/client/methods/messages/send_cached_media.py @@ -28,19 +28,19 @@ from pyrogram.client.ext import BaseClient, utils class SendCachedMedia(BaseClient): async def send_cached_media( - self, - chat_id: Union[int, str], - file_id: str, - caption: str = "", - parse_mode: str = "", - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union[ - "pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply" - ] = None + self, + chat_id: Union[int, str], + file_id: str, + caption: str = "", + parse_mode: str = "", + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None ) -> Union["pyrogram.Message", None]: """Use this method to send any media stored on the Telegram servers using a file_id. diff --git a/pyrogram/client/methods/messages/send_chat_action.py b/pyrogram/client/methods/messages/send_chat_action.py index 1a4e2e8c..7d2a0eb0 100644 --- a/pyrogram/client/methods/messages/send_chat_action.py +++ b/pyrogram/client/methods/messages/send_chat_action.py @@ -23,10 +23,12 @@ from pyrogram.client.ext import BaseClient, ChatAction class SendChatAction(BaseClient): - async def send_chat_action(self, - chat_id: Union[int, str], - action: Union[ChatAction, str], - progress: int = 0): + async def send_chat_action( + self, + chat_id: Union[int, str], + action: Union[ChatAction, str], + progress: int = 0 + ): """Use this method when you need to tell the other party that something is happening on your side. Args: diff --git a/pyrogram/client/methods/messages/send_contact.py b/pyrogram/client/methods/messages/send_contact.py index 5e25b6ae..bb1a42fd 100644 --- a/pyrogram/client/methods/messages/send_contact.py +++ b/pyrogram/client/methods/messages/send_contact.py @@ -24,17 +24,21 @@ from pyrogram.client.ext import BaseClient class SendContact(BaseClient): - async def send_contact(self, - chat_id: Union[int, str], - phone_number: str, - first_name: str, - last_name: str = "", - vcard: str = "", disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + async def send_contact( + self, + chat_id: Union[int, str], + phone_number: str, + first_name: str, + last_name: str = "", + vcard: str = "", disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send phone contacts. Args: diff --git a/pyrogram/client/methods/messages/send_document.py b/pyrogram/client/methods/messages/send_document.py index cef89c22..d2586d45 100644 --- a/pyrogram/client/methods/messages/send_document.py +++ b/pyrogram/client/methods/messages/send_document.py @@ -28,19 +28,23 @@ from pyrogram.client.ext import BaseClient, utils class SendDocument(BaseClient): - async def send_document(self, - chat_id: Union[int, str], - document: str, - thumb: str = None, caption: str = "", - parse_mode: str = "", - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_document( + self, + chat_id: Union[int, str], + document: str, + thumb: str = None, caption: str = "", + parse_mode: str = "", + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send general files. Args: @@ -122,7 +126,7 @@ class SendDocument(BaseClient): file=file, thumb=thumb, attributes=[ - types.DocumentAttributeFilename(os.path.basename(document)) + types.DocumentAttributeFilename(file_name=os.path.basename(document)) ] ) elif document.startswith("http"): diff --git a/pyrogram/client/methods/messages/send_location.py b/pyrogram/client/methods/messages/send_location.py index 8140147a..d1856a42 100644 --- a/pyrogram/client/methods/messages/send_location.py +++ b/pyrogram/client/methods/messages/send_location.py @@ -24,16 +24,20 @@ from pyrogram.client.ext import BaseClient class SendLocation(BaseClient): - async def send_location(self, - chat_id: Union[int, str], - latitude: float, - longitude: float, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + async def send_location( + self, + chat_id: Union[int, str], + latitude: float, + longitude: float, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send points on the map. Args: @@ -69,9 +73,9 @@ class SendLocation(BaseClient): functions.messages.SendMedia( peer=await self.resolve_peer(chat_id), media=types.InputMediaGeoPoint( - types.InputGeoPoint( - latitude, - longitude + geo_point=types.InputGeoPoint( + lat=latitude, + long=longitude ) ), message="", diff --git a/pyrogram/client/methods/messages/send_media_group.py b/pyrogram/client/methods/messages/send_media_group.py index a6584a00..d4f5529d 100644 --- a/pyrogram/client/methods/messages/send_media_group.py +++ b/pyrogram/client/methods/messages/send_media_group.py @@ -34,11 +34,13 @@ log = logging.getLogger(__name__) class SendMediaGroup(BaseClient): # TODO: Add progress parameter # TODO: Figure out how to send albums using URLs - async def send_media_group(self, - chat_id: Union[int, str], - media: List[Union["pyrogram.InputMediaPhoto", "pyrogram.InputMediaVideo"]], - disable_notification: bool = None, - reply_to_message_id: int = None): + async def send_media_group( + self, + chat_id: Union[int, str], + media: List[Union["pyrogram.InputMediaPhoto", "pyrogram.InputMediaVideo"]], + disable_notification: bool = None, + reply_to_message_id: int = None + ): """Use this method to send a group of photos or videos as an album. Args: @@ -137,7 +139,7 @@ class SendMediaGroup(BaseClient): w=i.width, h=i.height ), - types.DocumentAttributeFilename(os.path.basename(i.media)) + types.DocumentAttributeFilename(file_name=os.path.basename(i.media)) ] ) ) diff --git a/pyrogram/client/methods/messages/send_message.py b/pyrogram/client/methods/messages/send_message.py index 3836dddd..d517180a 100644 --- a/pyrogram/client/methods/messages/send_message.py +++ b/pyrogram/client/methods/messages/send_message.py @@ -24,17 +24,21 @@ from ...ext import BaseClient class SendMessage(BaseClient): - async def send_message(self, - chat_id: Union[int, str], - text: str, - parse_mode: str = "", - disable_web_page_preview: bool = None, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + async def send_message( + self, + chat_id: Union[int, str], + text: str, + parse_mode: str = "", + disable_web_page_preview: bool = None, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send text messages. Args: diff --git a/pyrogram/client/methods/messages/send_photo.py b/pyrogram/client/methods/messages/send_photo.py index 267a7136..7c74c205 100644 --- a/pyrogram/client/methods/messages/send_photo.py +++ b/pyrogram/client/methods/messages/send_photo.py @@ -28,20 +28,24 @@ from pyrogram.client.ext import BaseClient, utils class SendPhoto(BaseClient): - async def send_photo(self, - chat_id: Union[int, str], - photo: str, - caption: str = "", - parse_mode: str = "", - ttl_seconds: int = None, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_photo( + self, + chat_id: Union[int, str], + photo: str, + caption: str = "", + parse_mode: str = "", + ttl_seconds: int = None, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send photos. Args: diff --git a/pyrogram/client/methods/messages/send_poll.py b/pyrogram/client/methods/messages/send_poll.py index 8e938a1a..423f962d 100644 --- a/pyrogram/client/methods/messages/send_poll.py +++ b/pyrogram/client/methods/messages/send_poll.py @@ -24,16 +24,20 @@ from pyrogram.client.ext import BaseClient class SendPoll(BaseClient): - def send_poll(self, - chat_id: Union[int, str], - question: str, - options: List[str], - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + def send_poll \ + (self, + chat_id: Union[int, str], + question: str, + options: List[str], + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send a new poll. Args: diff --git a/pyrogram/client/methods/messages/send_sticker.py b/pyrogram/client/methods/messages/send_sticker.py index 7525e2f9..5e3340e2 100644 --- a/pyrogram/client/methods/messages/send_sticker.py +++ b/pyrogram/client/methods/messages/send_sticker.py @@ -28,17 +28,21 @@ from pyrogram.client.ext import BaseClient, utils class SendSticker(BaseClient): - async def send_sticker(self, - chat_id: Union[int, str], - sticker: str, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_sticker( + self, + chat_id: Union[int, str], + sticker: str, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send .webp stickers. Args: @@ -103,7 +107,7 @@ class SendSticker(BaseClient): mime_type="image/webp", file=file, attributes=[ - types.DocumentAttributeFilename(os.path.basename(sticker)) + types.DocumentAttributeFilename(file_name=os.path.basename(sticker)) ] ) elif sticker.startswith("http"): diff --git a/pyrogram/client/methods/messages/send_venue.py b/pyrogram/client/methods/messages/send_venue.py index c7a4f139..25223dc2 100644 --- a/pyrogram/client/methods/messages/send_venue.py +++ b/pyrogram/client/methods/messages/send_venue.py @@ -24,19 +24,24 @@ from pyrogram.client.ext import BaseClient class SendVenue(BaseClient): - async def send_venue(self, - chat_id: Union[int, str], - latitude: float, - longitude: float, - title: str, - address: str, - foursquare_id: str = "", - foursquare_type: str = "", disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None) -> "pyrogram.Message": + async def send_venue( + self, + chat_id: Union[int, str], + latitude: float, + longitude: float, + title: str, + address: str, + foursquare_id: str = "", + foursquare_type: str = "", + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ) -> "pyrogram.Message": """Use this method to send information about a venue. Args: diff --git a/pyrogram/client/methods/messages/send_video.py b/pyrogram/client/methods/messages/send_video.py index 4d54f0f3..d6dcd164 100644 --- a/pyrogram/client/methods/messages/send_video.py +++ b/pyrogram/client/methods/messages/send_video.py @@ -28,24 +28,28 @@ from pyrogram.client.ext import BaseClient, utils class SendVideo(BaseClient): - async def send_video(self, - chat_id: Union[int, str], - video: str, - caption: str = "", - parse_mode: str = "", - duration: int = 0, - width: int = 0, - height: int = 0, - thumb: str = None, - supports_streaming: bool = True, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_video( + self, + chat_id: Union[int, str], + video: str, + caption: str = "", + parse_mode: str = "", + duration: int = 0, + width: int = 0, + height: int = 0, + thumb: str = None, + supports_streaming: bool = True, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send video files. Args: @@ -145,7 +149,7 @@ class SendVideo(BaseClient): w=width, h=height ), - types.DocumentAttributeFilename(os.path.basename(video)) + types.DocumentAttributeFilename(file_name=os.path.basename(video)) ] ) elif video.startswith("http"): diff --git a/pyrogram/client/methods/messages/send_video_note.py b/pyrogram/client/methods/messages/send_video_note.py index c3a7c568..5306dc94 100644 --- a/pyrogram/client/methods/messages/send_video_note.py +++ b/pyrogram/client/methods/messages/send_video_note.py @@ -28,19 +28,24 @@ from pyrogram.client.ext import BaseClient, utils class SendVideoNote(BaseClient): - async def send_video_note(self, - chat_id: Union[int, str], - video_note: str, - duration: int = 0, - length: int = 1, - thumb: str = None, disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_video_note( + self, + chat_id: Union[int, str], + video_note: str, + duration: int = 0, + length: int = 1, + thumb: str = None, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send video messages. Args: diff --git a/pyrogram/client/methods/messages/send_voice.py b/pyrogram/client/methods/messages/send_voice.py index 35e8a7c6..e3683e84 100644 --- a/pyrogram/client/methods/messages/send_voice.py +++ b/pyrogram/client/methods/messages/send_voice.py @@ -28,20 +28,24 @@ from pyrogram.client.ext import BaseClient, utils class SendVoice(BaseClient): - async def send_voice(self, - chat_id: Union[int, str], - voice: str, - caption: str = "", - parse_mode: str = "", - duration: int = 0, - disable_notification: bool = None, - reply_to_message_id: int = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None, - progress: callable = None, - progress_args: tuple = ()) -> Union["pyrogram.Message", None]: + async def send_voice( + self, + chat_id: Union[int, str], + voice: str, + caption: str = "", + parse_mode: str = "", + duration: int = 0, + disable_notification: bool = None, + reply_to_message_id: int = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None, + progress: callable = None, + progress_args: tuple = () + ) -> Union["pyrogram.Message", None]: """Use this method to send audio files. Args: diff --git a/pyrogram/client/methods/messages/vote_poll.py b/pyrogram/client/methods/messages/vote_poll.py index 9e400e62..bf44c831 100644 --- a/pyrogram/client/methods/messages/vote_poll.py +++ b/pyrogram/client/methods/messages/vote_poll.py @@ -23,10 +23,12 @@ from pyrogram.client.ext import BaseClient class VotePoll(BaseClient): - def vote_poll(self, - chat_id: Union[int, str], - message_id: id, - option: int) -> bool: + def vote_poll( + self, + chat_id: Union[int, str], + message_id: id, + option: int + ) -> bool: """Use this method to vote a poll. Args: diff --git a/pyrogram/client/methods/password/change_cloud_password.py b/pyrogram/client/methods/password/change_cloud_password.py index 139d5b9f..4b68d13e 100644 --- a/pyrogram/client/methods/password/change_cloud_password.py +++ b/pyrogram/client/methods/password/change_cloud_password.py @@ -24,10 +24,12 @@ from ...ext import BaseClient class ChangeCloudPassword(BaseClient): - async def change_cloud_password(self, - current_password: str, - new_password: str, - new_hint: str = "") -> bool: + async def change_cloud_password( + self, + current_password: str, + new_password: str, + new_hint: str = "" + ) -> bool: """Use this method to change your Two-Step Verification password (Cloud Password) with a new one. Args: diff --git a/pyrogram/client/methods/password/enable_cloud_password.py b/pyrogram/client/methods/password/enable_cloud_password.py index b14d85ef..2290da5a 100644 --- a/pyrogram/client/methods/password/enable_cloud_password.py +++ b/pyrogram/client/methods/password/enable_cloud_password.py @@ -24,10 +24,12 @@ from ...ext import BaseClient class EnableCloudPassword(BaseClient): - async def enable_cloud_password(self, - password: str, - hint: str = "", - email: str = None) -> bool: + async def enable_cloud_password( + self, + password: str, + hint: str = "", + email: str = None + ) -> bool: """Use this method to enable the Two-Step Verification security feature (Cloud Password) on your account. This password will be asked when you log-in on a new device in addition to the SMS code. diff --git a/pyrogram/client/methods/password/remove_cloud_password.py b/pyrogram/client/methods/password/remove_cloud_password.py index 444457df..9cd998f6 100644 --- a/pyrogram/client/methods/password/remove_cloud_password.py +++ b/pyrogram/client/methods/password/remove_cloud_password.py @@ -22,8 +22,10 @@ from ...ext import BaseClient class RemoveCloudPassword(BaseClient): - async def remove_cloud_password(self, - password: str) -> bool: + async def remove_cloud_password( + self, + password: str + ) -> bool: """Use this method to turn off the Two-Step Verification security feature (Cloud Password) on your account. Args: diff --git a/pyrogram/client/methods/password/utils.py b/pyrogram/client/methods/password/utils.py index 24c4dd28..3a29976a 100644 --- a/pyrogram/client/methods/password/utils.py +++ b/pyrogram/client/methods/password/utils.py @@ -101,4 +101,4 @@ def compute_check(r: types.account.Password, password: str) -> types.InputCheckP + K_bytes ) - return types.InputCheckPasswordSRP(srp_id, A_bytes, M1_bytes) + return types.InputCheckPasswordSRP(srp_id=srp_id, A=A_bytes, M1=M1_bytes) diff --git a/pyrogram/client/methods/users/delete_user_profile_photos.py b/pyrogram/client/methods/users/delete_user_profile_photos.py index 057b74f4..bcb4f9da 100644 --- a/pyrogram/client/methods/users/delete_user_profile_photos.py +++ b/pyrogram/client/methods/users/delete_user_profile_photos.py @@ -25,8 +25,10 @@ from ...ext import BaseClient class DeleteUserProfilePhotos(BaseClient): - async def delete_user_profile_photos(self, - id: Union[str, List[str]]) -> bool: + async def delete_user_profile_photos( + self, + id: Union[str, List[str]] + ) -> bool: """Use this method to delete your own profile photos Args: diff --git a/pyrogram/client/methods/users/get_me.py b/pyrogram/client/methods/users/get_me.py index 09caabf7..5a37bb54 100644 --- a/pyrogram/client/methods/users/get_me.py +++ b/pyrogram/client/methods/users/get_me.py @@ -35,7 +35,7 @@ class GetMe(BaseClient): self, (await self.send( functions.users.GetFullUser( - types.InputPeerSelf() + id=types.InputPeerSelf() ) )).user ) diff --git a/pyrogram/client/methods/users/get_user_profile_photos.py b/pyrogram/client/methods/users/get_user_profile_photos.py index 0d0d90bf..c672a6c7 100644 --- a/pyrogram/client/methods/users/get_user_profile_photos.py +++ b/pyrogram/client/methods/users/get_user_profile_photos.py @@ -24,10 +24,12 @@ from ...ext import BaseClient class GetUserProfilePhotos(BaseClient): - async def get_user_profile_photos(self, - user_id: Union[int, str], - offset: int = 0, - limit: int = 100) -> "pyrogram.UserProfilePhotos": + async def get_user_profile_photos( + self, + user_id: Union[int, str], + offset: int = 0, + limit: int = 100 + ) -> "pyrogram.UserProfilePhotos": """Use this method to get a list of profile pictures for a user. Args: diff --git a/pyrogram/client/methods/users/get_users.py b/pyrogram/client/methods/users/get_users.py index 6b9fbd45..03ac8f13 100644 --- a/pyrogram/client/methods/users/get_users.py +++ b/pyrogram/client/methods/users/get_users.py @@ -25,8 +25,10 @@ from ...ext import BaseClient class GetUsers(BaseClient): - async def get_users(self, - user_ids: Iterable[Union[int, str]]) -> Union["pyrogram.User", List["pyrogram.User"]]: + async def get_users( + self, + user_ids: Iterable[Union[int, str]] + ) -> Union["pyrogram.User", List["pyrogram.User"]]: """Use this method to get information about a user. You can retrieve up to 200 users at once. diff --git a/pyrogram/client/methods/users/set_user_profile_photo.py b/pyrogram/client/methods/users/set_user_profile_photo.py index 0863c695..705631fd 100644 --- a/pyrogram/client/methods/users/set_user_profile_photo.py +++ b/pyrogram/client/methods/users/set_user_profile_photo.py @@ -21,8 +21,10 @@ from ...ext import BaseClient class SetUserProfilePhoto(BaseClient): - def set_user_profile_photo(self, - photo: str) -> bool: + def set_user_profile_photo( + self, + photo: str + ) -> bool: """Use this method to set a new profile photo. This method only works for Users. @@ -43,7 +45,7 @@ class SetUserProfilePhoto(BaseClient): return bool( self.send( functions.photos.UploadProfilePhoto( - self.save_file(photo) + file=self.save_file(photo) ) ) ) diff --git a/pyrogram/client/methods/users/update_username.py b/pyrogram/client/methods/users/update_username.py index 9a4feb23..5fd1a711 100644 --- a/pyrogram/client/methods/users/update_username.py +++ b/pyrogram/client/methods/users/update_username.py @@ -23,8 +23,10 @@ from ...ext import BaseClient class UpdateUsername(BaseClient): - def update_username(self, - username: Union[str, None]) -> bool: + def update_username( + self, + username: Union[str, None] + ) -> bool: """Use this method to update your own username. This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating diff --git a/pyrogram/client/style/html.py b/pyrogram/client/style/html.py index 9a72a565..040e770b 100644 --- a/pyrogram/client/style/html.py +++ b/pyrogram/client/style/html.py @@ -55,20 +55,20 @@ class HTML: input_user = self.peers_by_id.get(user_id, None) entity = ( - Mention(start, len(body), input_user) - if input_user else MentionInvalid(start, len(body), user_id) + Mention(offset=start, length=len(body), user_id=input_user) + if input_user else MentionInvalid(offset=start, length=len(body), user_id=user_id) ) else: - entity = Url(start, len(body), url) + entity = Url(offset=start, length=len(body), url=url) else: if style == "b" or style == "strong": - entity = Bold(start, len(body)) + entity = Bold(offset=start, length=len(body)) elif style == "i" or style == "em": - entity = Italic(start, len(body)) + entity = Italic(offset=start, length=len(body)) elif style == "code": - entity = Code(start, len(body)) + entity = Code(offset=start, length=len(body)) elif style == "pre": - entity = Pre(start, len(body), "") + entity = Pre(offset=start, length=len(body), language="") else: continue diff --git a/pyrogram/client/style/markdown.py b/pyrogram/client/style/markdown.py index 05a11a25..04ce95c8 100644 --- a/pyrogram/client/style/markdown.py +++ b/pyrogram/client/style/markdown.py @@ -72,24 +72,24 @@ class Markdown: input_user = self.peers_by_id.get(user_id, None) entity = ( - Mention(start, len(text), input_user) + Mention(offset=start, length=len(text), user_id=input_user) if input_user - else MentionInvalid(start, len(text), user_id) + else MentionInvalid(offset=start, length=len(text), user_id=user_id) ) else: - entity = Url(start, len(text), url) + entity = Url(offset=start, length=len(text), url=url) body = text offset += len(url) + 4 else: if style == self.BOLD_DELIMITER: - entity = Bold(start, len(body)) + entity = Bold(offset=start, length=len(body)) elif style == self.ITALIC_DELIMITER: - entity = Italic(start, len(body)) + entity = Italic(offset=start, length=len(body)) elif style == self.CODE_DELIMITER: - entity = Code(start, len(body)) + entity = Code(offset=start, length=len(body)) elif style == self.PRE_DELIMITER: - entity = Pre(start, len(body), "") + entity = Pre(offset=start, length=len(body), language="") else: continue diff --git a/pyrogram/client/types/bots/callback_game.py b/pyrogram/client/types/bots/callback_game.py index be026360..fc2d9884 100644 --- a/pyrogram/client/types/bots/callback_game.py +++ b/pyrogram/client/types/bots/callback_game.py @@ -25,5 +25,7 @@ class CallbackGame(PyrogramType): Use BotFather to set up your game. """ + __slots__ = [] + def __init__(self): super().__init__(None) diff --git a/pyrogram/client/types/bots/callback_query.py b/pyrogram/client/types/bots/callback_query.py index 8eda4c33..30a5333f 100644 --- a/pyrogram/client/types/bots/callback_query.py +++ b/pyrogram/client/types/bots/callback_query.py @@ -58,16 +58,20 @@ class CallbackQuery(PyrogramType, Update): """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: str, - from_user: User, - chat_instance: str, - message: "pyrogram.Message" = None, - inline_message_id: str = None, - data: bytes = None, - game_short_name: str = None): + __slots__ = ["id", "from_user", "chat_instance", "message", "inline_message_id", "data", "game_short_name"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: str, + from_user: User, + chat_instance: str, + message: "pyrogram.Message" = None, + inline_message_id: str = None, + data: bytes = None, + game_short_name: str = None + ): super().__init__(client) self.id = id diff --git a/pyrogram/client/types/bots/force_reply.py b/pyrogram/client/types/bots/force_reply.py index 2e5c2f42..fca2c061 100644 --- a/pyrogram/client/types/bots/force_reply.py +++ b/pyrogram/client/types/bots/force_reply.py @@ -33,8 +33,12 @@ class ForceReply(PyrogramType): 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. """ - def __init__(self, - selective: bool = None): + __slots__ = ["selective"] + + def __init__( + self, + selective: bool = None + ): super().__init__(None) self.selective = selective diff --git a/pyrogram/client/types/bots/game_high_score.py b/pyrogram/client/types/bots/game_high_score.py index 0541c18c..da6b2881 100644 --- a/pyrogram/client/types/bots/game_high_score.py +++ b/pyrogram/client/types/bots/game_high_score.py @@ -37,12 +37,16 @@ class GameHighScore(PyrogramType): Position in high score table for the game. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - user: User, - score: int, - position: int = None): + __slots__ = ["user", "score", "position"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + user: User, + score: int, + position: int = None + ): super().__init__(client) self.user = user diff --git a/pyrogram/client/types/bots/game_high_scores.py b/pyrogram/client/types/bots/game_high_scores.py index 1717effa..3c197969 100644 --- a/pyrogram/client/types/bots/game_high_scores.py +++ b/pyrogram/client/types/bots/game_high_scores.py @@ -35,11 +35,15 @@ class GameHighScores(PyrogramType): Game scores. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - total_count: int, - game_high_scores: List[GameHighScore]): + __slots__ = ["total_count", "game_high_scores"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + total_count: int, + game_high_scores: List[GameHighScore] + ): super().__init__(client) self.total_count = total_count diff --git a/pyrogram/client/types/bots/inline_keyboard_button.py b/pyrogram/client/types/bots/inline_keyboard_button.py index cc829cb1..ff6f3cdb 100644 --- a/pyrogram/client/types/bots/inline_keyboard_button.py +++ b/pyrogram/client/types/bots/inline_keyboard_button.py @@ -54,13 +54,19 @@ class InlineKeyboardButton(PyrogramType): # TODO: Add callback_game and pay fields - def __init__(self, - text: str, - callback_data: bytes = None, - url: str = None, - switch_inline_query: str = None, - switch_inline_query_current_chat: str = None, - callback_game: CallbackGame = None): + __slots__ = [ + "text", "url", "callback_data", "switch_inline_query", "switch_inline_query_current_chat", "callback_game" + ] + + def __init__( + self, + text: str, + callback_data: bytes = None, + url: str = None, + switch_inline_query: str = None, + switch_inline_query_current_chat: str = None, + callback_game: CallbackGame = None + ): super().__init__(None) self.text = str(text) @@ -105,16 +111,20 @@ class InlineKeyboardButton(PyrogramType): def write(self): if self.callback_data: - return KeyboardButtonCallback(self.text, self.callback_data) + return KeyboardButtonCallback(text=self.text, data=self.callback_data) if self.url: - return KeyboardButtonUrl(self.text, self.url) + return KeyboardButtonUrl(text=self.text, url=self.url) if self.switch_inline_query: - return KeyboardButtonSwitchInline(self.text, self.switch_inline_query) + return KeyboardButtonSwitchInline(text=self.text, query=self.switch_inline_query) if self.switch_inline_query_current_chat: - return KeyboardButtonSwitchInline(self.text, self.switch_inline_query_current_chat, same_peer=True) + return KeyboardButtonSwitchInline( + text=self.text, + query=self.switch_inline_query_current_chat, + same_peer=True + ) if self.callback_game: - return KeyboardButtonGame(self.text) + return KeyboardButtonGame(text=self.text) diff --git a/pyrogram/client/types/bots/inline_keyboard_markup.py b/pyrogram/client/types/bots/inline_keyboard_markup.py index f18bd605..54476c5e 100644 --- a/pyrogram/client/types/bots/inline_keyboard_markup.py +++ b/pyrogram/client/types/bots/inline_keyboard_markup.py @@ -31,8 +31,12 @@ class InlineKeyboardMarkup(PyrogramType): List of button rows, each represented by a List of InlineKeyboardButton objects. """ - def __init__(self, - inline_keyboard: List[List[InlineKeyboardButton]]): + __slots__ = ["inline_keyboard"] + + def __init__( + self, + inline_keyboard: List[List[InlineKeyboardButton]] + ): super().__init__(None) self.inline_keyboard = inline_keyboard @@ -55,7 +59,7 @@ class InlineKeyboardMarkup(PyrogramType): def write(self): return ReplyInlineMarkup( - [KeyboardButtonRow( - [j.write() for j in i] + rows=[KeyboardButtonRow( + buttons=[j.write() for j in i] ) for i in self.inline_keyboard] ) diff --git a/pyrogram/client/types/bots/keyboard_button.py b/pyrogram/client/types/bots/keyboard_button.py index 3c7c2bd6..477442cc 100644 --- a/pyrogram/client/types/bots/keyboard_button.py +++ b/pyrogram/client/types/bots/keyboard_button.py @@ -40,10 +40,14 @@ class KeyboardButton(PyrogramType): Available in private chats only. """ - def __init__(self, - text: str, - request_contact: bool = None, - request_location: bool = None): + __slots__ = ["text", "request_contact", "request_location"] + + def __init__( + self, + text: str, + request_contact: bool = None, + request_location: bool = None + ): super().__init__(None) self.text = str(text) @@ -71,8 +75,8 @@ class KeyboardButton(PyrogramType): # TODO: Enforce optional args mutual exclusiveness if self.request_contact: - return KeyboardButtonRequestPhone(self.text) + return KeyboardButtonRequestPhone(text=self.text) elif self.request_location: - return KeyboardButtonRequestGeoLocation(self.text) + return KeyboardButtonRequestGeoLocation(text=self.text) else: - return RawKeyboardButton(self.text) + return RawKeyboardButton(text=self.text) diff --git a/pyrogram/client/types/bots/reply_keyboard_markup.py b/pyrogram/client/types/bots/reply_keyboard_markup.py index afae236d..b0216803 100644 --- a/pyrogram/client/types/bots/reply_keyboard_markup.py +++ b/pyrogram/client/types/bots/reply_keyboard_markup.py @@ -49,11 +49,15 @@ class ReplyKeyboardMarkup(PyrogramType): select the new language. Other users in the group don't see the keyboard. """ - def __init__(self, - keyboard: List[List[Union[KeyboardButton, str]]], - resize_keyboard: bool = None, - one_time_keyboard: bool = None, - selective: bool = None): + __slots__ = ["keyboard", "resize_keyboard", "one_time_keyboard", "selective"] + + def __init__( + self, + keyboard: List[List[Union[KeyboardButton, str]]], + resize_keyboard: bool = None, + one_time_keyboard: bool = None, + selective: bool = None + ): super().__init__(None) self.keyboard = keyboard @@ -83,9 +87,11 @@ class ReplyKeyboardMarkup(PyrogramType): def write(self): return RawReplyKeyboardMarkup( rows=[KeyboardButtonRow( - [KeyboardButton(j).write() - if isinstance(j, str) else j.write() - for j in i] + buttons=[ + KeyboardButton(j).write() + if isinstance(j, str) else j.write() + for j in i + ] ) for i in self.keyboard], resize=self.resize_keyboard or None, single_use=self.one_time_keyboard or None, diff --git a/pyrogram/client/types/bots/reply_keyboard_remove.py b/pyrogram/client/types/bots/reply_keyboard_remove.py index 5b67fbb4..3298ab6f 100644 --- a/pyrogram/client/types/bots/reply_keyboard_remove.py +++ b/pyrogram/client/types/bots/reply_keyboard_remove.py @@ -35,8 +35,12 @@ class ReplyKeyboardRemove(PyrogramType): keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet. """ - def __init__(self, - selective: bool = None): + __slots__ = ["selective"] + + def __init__( + self, + selective: bool = None + ): super().__init__(None) self.selective = selective diff --git a/pyrogram/client/types/input_media/input_media.py b/pyrogram/client/types/input_media/input_media.py index f55d8aa0..aeeef350 100644 --- a/pyrogram/client/types/input_media/input_media.py +++ b/pyrogram/client/types/input_media/input_media.py @@ -18,10 +18,14 @@ class InputMedia: - def __init__(self, - media: str, - caption: str, - parse_mode: str): + __slots__ = ["media", "caption", "parse_mode"] + + def __init__( + self, + media: str, + caption: str, + parse_mode: str + ): self.media = media self.caption = caption self.parse_mode = parse_mode diff --git a/pyrogram/client/types/input_media/input_media_animation.py b/pyrogram/client/types/input_media/input_media_animation.py index af0c2b2a..e77499b5 100644 --- a/pyrogram/client/types/input_media/input_media_animation.py +++ b/pyrogram/client/types/input_media/input_media_animation.py @@ -52,14 +52,18 @@ class InputMediaAnimation(InputMedia): Animation duration. """ - def __init__(self, - media: str, - thumb: str = None, - caption: str = "", - parse_mode: str = "", - width: int = 0, - height: int = 0, - duration: int = 0): + __slots__ = ["thumb", "width", "height", "duration"] + + def __init__( + self, + media: str, + thumb: str = None, + caption: str = "", + parse_mode: str = "", + width: int = 0, + height: int = 0, + duration: int = 0 + ): super().__init__(media, caption, parse_mode) self.thumb = thumb diff --git a/pyrogram/client/types/input_media/input_media_audio.py b/pyrogram/client/types/input_media/input_media_audio.py index a2dc18db..e8f1c257 100644 --- a/pyrogram/client/types/input_media/input_media_audio.py +++ b/pyrogram/client/types/input_media/input_media_audio.py @@ -53,14 +53,18 @@ class InputMediaAudio(InputMedia): Title of the audio """ - def __init__(self, - media: str, - thumb: str = None, - caption: str = "", - parse_mode: str = "", - duration: int = 0, - performer: int = "", - title: str = ""): + __slots__ = ["thumb", "duration", "performer", "title"] + + def __init__( + self, + media: str, + thumb: str = None, + caption: str = "", + parse_mode: str = "", + duration: int = 0, + performer: int = "", + title: str = "" + ): super().__init__(media, caption, parse_mode) self.thumb = thumb diff --git a/pyrogram/client/types/input_media/input_media_document.py b/pyrogram/client/types/input_media/input_media_document.py index 25e17d0f..9391e7d8 100644 --- a/pyrogram/client/types/input_media/input_media_document.py +++ b/pyrogram/client/types/input_media/input_media_document.py @@ -43,11 +43,15 @@ class InputMediaDocument(InputMedia): Defaults to Markdown. """ - def __init__(self, - media: str, - thumb: str = None, - caption: str = "", - parse_mode: str = ""): + __slots__ = ["thumb"] + + def __init__( + self, + media: str, + thumb: str = None, + caption: str = "", + parse_mode: str = "" + ): super().__init__(media, caption, parse_mode) self.thumb = thumb diff --git a/pyrogram/client/types/input_media/input_media_photo.py b/pyrogram/client/types/input_media/input_media_photo.py index 5917fbf0..e6bba03b 100644 --- a/pyrogram/client/types/input_media/input_media_photo.py +++ b/pyrogram/client/types/input_media/input_media_photo.py @@ -39,8 +39,12 @@ class InputMediaPhoto(InputMedia): Defaults to Markdown. """ - def __init__(self, - media: str, - caption: str = "", - parse_mode: str = ""): + __slots__ = [] + + def __init__( + self, + media: str, + caption: str = "", + parse_mode: str = "" + ): super().__init__(media, caption, parse_mode) diff --git a/pyrogram/client/types/input_media/input_media_video.py b/pyrogram/client/types/input_media/input_media_video.py index 6fa7936e..5c918f13 100644 --- a/pyrogram/client/types/input_media/input_media_video.py +++ b/pyrogram/client/types/input_media/input_media_video.py @@ -57,15 +57,19 @@ class InputMediaVideo(InputMedia): Pass True, if the uploaded video is suitable for streaming. """ - def __init__(self, - media: str, - thumb: str = None, - caption: str = "", - parse_mode: str = "", - width: int = 0, - height: int = 0, - duration: int = 0, - supports_streaming: bool = True): + __slots__ = ["thumb", "width", "height", "duration", "supports_streaming"] + + def __init__( + self, + media: str, + thumb: str = None, + caption: str = "", + parse_mode: str = "", + width: int = 0, + height: int = 0, + duration: int = 0, + supports_streaming: bool = True + ): super().__init__(media, caption, parse_mode) self.thumb = thumb diff --git a/pyrogram/client/types/input_media/input_phone_contact.py b/pyrogram/client/types/input_media/input_phone_contact.py index 1a89759a..4fe7ee60 100644 --- a/pyrogram/client/types/input_media/input_phone_contact.py +++ b/pyrogram/client/types/input_media/input_phone_contact.py @@ -35,10 +35,14 @@ class InputPhoneContact: Contact's last name """ - def __init__(self, - phone: str, - first_name: str, - last_name: str = ""): + __slots__ = [] + + def __init__( + self, + phone: str, + first_name: str, + last_name: str = "" + ): pass def __new__(cls, diff --git a/pyrogram/client/types/messages_and_media/animation.py b/pyrogram/client/types/messages_and_media/animation.py index 9f3ba886..21a01e0f 100644 --- a/pyrogram/client/types/messages_and_media/animation.py +++ b/pyrogram/client/types/messages_and_media/animation.py @@ -57,18 +57,22 @@ class Animation(PyrogramType): Date the animation was sent in Unix time. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - width: int, - height: int, - duration: int, - thumb: PhotoSize = None, - file_name: str = None, - mime_type: str = None, - file_size: int = None, - date: int = None): + __slots__ = ["file_id", "thumb", "file_name", "mime_type", "file_size", "date", "width", "height", "duration"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + width: int, + height: int, + duration: int, + thumb: PhotoSize = None, + file_name: str = None, + mime_type: str = None, + file_size: int = None, + date: int = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/audio.py b/pyrogram/client/types/messages_and_media/audio.py index 9c5698f1..db49f2eb 100644 --- a/pyrogram/client/types/messages_and_media/audio.py +++ b/pyrogram/client/types/messages_and_media/audio.py @@ -57,18 +57,22 @@ class Audio(PyrogramType): Title of the audio as defined by sender or by audio tags. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - duration: int, - thumb: PhotoSize = None, - file_name: str = None, - mime_type: str = None, - file_size: int = None, - date: int = None, - performer: str = None, - title: str = None): + __slots__ = ["file_id", "thumb", "file_name", "mime_type", "file_size", "date", "duration", "performer", "title"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + duration: int, + thumb: PhotoSize = None, + file_name: str = None, + mime_type: str = None, + file_size: int = None, + date: int = None, + performer: str = None, + title: str = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/contact.py b/pyrogram/client/types/messages_and_media/contact.py index 51acb59f..5abe5319 100644 --- a/pyrogram/client/types/messages_and_media/contact.py +++ b/pyrogram/client/types/messages_and_media/contact.py @@ -42,14 +42,18 @@ class Contact(PyrogramType): Additional data about the contact in the form of a vCard. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - phone_number: str, - first_name: str, - last_name: str = None, - user_id: int = None, - vcard: str = None): + __slots__ = ["phone_number", "first_name", "last_name", "user_id", "vcard"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + phone_number: str, + first_name: str, + last_name: str = None, + user_id: int = None, + vcard: str = None + ): super().__init__(client) self.phone_number = phone_number diff --git a/pyrogram/client/types/messages_and_media/document.py b/pyrogram/client/types/messages_and_media/document.py index 5cd01a92..f3ccc4f8 100644 --- a/pyrogram/client/types/messages_and_media/document.py +++ b/pyrogram/client/types/messages_and_media/document.py @@ -48,15 +48,19 @@ class Document(PyrogramType): Date the document was sent in Unix time. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - thumb: PhotoSize = None, - file_name: str = None, - mime_type: str = None, - file_size: int = None, - date: int = None): + __slots__ = ["file_id", "thumb", "file_name", "mime_type", "file_size", "date"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + thumb: PhotoSize = None, + file_name: str = None, + mime_type: str = None, + file_size: int = None, + date: int = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/game.py b/pyrogram/client/types/messages_and_media/game.py index 01af7226..cf0b4fa6 100644 --- a/pyrogram/client/types/messages_and_media/game.py +++ b/pyrogram/client/types/messages_and_media/game.py @@ -48,15 +48,19 @@ class Game(PyrogramType): Upload via BotFather. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: int, - title: str, - short_name: str, - description: str, - photo: Photo, - animation: Animation = None): + __slots__ = ["id", "title", "short_name", "description", "photo", "animation"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: int, + title: str, + short_name: str, + description: str, + photo: Photo, + animation: Animation = None + ): super().__init__(client) self.id = id diff --git a/pyrogram/client/types/messages_and_media/location.py b/pyrogram/client/types/messages_and_media/location.py index 64acdbf5..3a7f6d38 100644 --- a/pyrogram/client/types/messages_and_media/location.py +++ b/pyrogram/client/types/messages_and_media/location.py @@ -33,11 +33,15 @@ class Location(PyrogramType): Latitude as defined by sender. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - longitude: float, - latitude: float): + __slots__ = ["longitude", "latitude"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + longitude: float, + latitude: float + ): super().__init__(client) self.longitude = longitude diff --git a/pyrogram/client/types/messages_and_media/message.py b/pyrogram/client/types/messages_and_media/message.py index bd27f9b1..b6e9ea7e 100644 --- a/pyrogram/client/types/messages_and_media/message.py +++ b/pyrogram/client/types/messages_and_media/message.py @@ -234,65 +234,80 @@ class Message(PyrogramType, Update): # TODO: Add game missing field. Also invoice, successful_payment, connected_website - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - message_id: int, - date: int = None, - chat: Chat = None, - from_user: User = None, - forward_from: User = None, - forward_from_chat: Chat = None, - forward_from_message_id: int = None, - forward_signature: str = None, - forward_date: int = None, - reply_to_message: "Message" = None, - mentioned: bool = None, - empty: bool = None, - service: bool = None, - media: bool = None, - edit_date: int = None, - media_group_id: str = None, - author_signature: str = None, - text: str = None, - entities: List["pyrogram.MessageEntity"] = None, - caption_entities: List["pyrogram.MessageEntity"] = None, - audio: "pyrogram.Audio" = None, - document: "pyrogram.Document" = None, - photo: "pyrogram.Photo" = None, - sticker: "pyrogram.Sticker" = None, - animation: "pyrogram.Animation" = None, - game: "pyrogram.Game" = None, - video: "pyrogram.Video" = None, - voice: "pyrogram.Voice" = None, - video_note: "pyrogram.VideoNote" = None, - caption: str = None, - contact: "pyrogram.Contact" = None, - location: "pyrogram.Location" = None, - venue: "pyrogram.Venue" = None, - web_page: bool = None, - poll: "pyrogram.Poll" = None, - new_chat_members: List[User] = None, - left_chat_member: User = None, - new_chat_title: str = None, - new_chat_photo: "pyrogram.Photo" = None, - delete_chat_photo: bool = None, - group_chat_created: bool = None, - supergroup_chat_created: bool = None, - channel_chat_created: bool = None, - migrate_to_chat_id: int = None, - migrate_from_chat_id: int = None, - pinned_message: "Message" = None, - game_high_score: int = None, - views: int = None, - via_bot: User = None, - outgoing: bool = None, - matches: List[Match] = None, - command: List[str] = None, - reply_markup: Union["pyrogram.InlineKeyboardMarkup", - "pyrogram.ReplyKeyboardMarkup", - "pyrogram.ReplyKeyboardRemove", - "pyrogram.ForceReply"] = None): + __slots__ = [ + "message_id", "date", "chat", "from_user", "forward_from", "forward_from_chat", "forward_from_message_id", + "forward_signature", "forward_date", "reply_to_message", "mentioned", "empty", "service", "media", "edit_date", + "media_group_id", "author_signature", "text", "entities", "caption_entities", "audio", "document", "photo", + "sticker", "animation", "game", "video", "voice", "video_note", "caption", "contact", "location", "venue", + "web_page", "poll", "new_chat_members", "left_chat_member", "new_chat_title", "new_chat_photo", + "delete_chat_photo", "group_chat_created", "supergroup_chat_created", "channel_chat_created", + "migrate_to_chat_id", "migrate_from_chat_id", "pinned_message", "game_high_score", "views", "via_bot", + "outgoing", "matches", "command", "reply_markup" + ] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + message_id: int, + date: int = None, + chat: Chat = None, + from_user: User = None, + forward_from: User = None, + forward_from_chat: Chat = None, + forward_from_message_id: int = None, + forward_signature: str = None, + forward_date: int = None, + reply_to_message: "Message" = None, + mentioned: bool = None, + empty: bool = None, + service: bool = None, + media: bool = None, + edit_date: int = None, + media_group_id: str = None, + author_signature: str = None, + text: str = None, + entities: List["pyrogram.MessageEntity"] = None, + caption_entities: List["pyrogram.MessageEntity"] = None, + audio: "pyrogram.Audio" = None, + document: "pyrogram.Document" = None, + photo: "pyrogram.Photo" = None, + sticker: "pyrogram.Sticker" = None, + animation: "pyrogram.Animation" = None, + game: "pyrogram.Game" = None, + video: "pyrogram.Video" = None, + voice: "pyrogram.Voice" = None, + video_note: "pyrogram.VideoNote" = None, + caption: str = None, + contact: "pyrogram.Contact" = None, + location: "pyrogram.Location" = None, + venue: "pyrogram.Venue" = None, + web_page: bool = None, + poll: "pyrogram.Poll" = None, + new_chat_members: List[User] = None, + left_chat_member: User = None, + new_chat_title: str = None, + new_chat_photo: "pyrogram.Photo" = None, + delete_chat_photo: bool = None, + group_chat_created: bool = None, + supergroup_chat_created: bool = None, + channel_chat_created: bool = None, + migrate_to_chat_id: int = None, + migrate_from_chat_id: int = None, + pinned_message: "Message" = None, + game_high_score: int = None, + views: int = None, + via_bot: User = None, + outgoing: bool = None, + matches: List[Match] = None, + command: List[str] = None, + reply_markup: Union[ + "pyrogram.InlineKeyboardMarkup", + "pyrogram.ReplyKeyboardMarkup", + "pyrogram.ReplyKeyboardRemove", + "pyrogram.ForceReply" + ] = None + ): super().__init__(client) self.message_id = message_id diff --git a/pyrogram/client/types/messages_and_media/message_entity.py b/pyrogram/client/types/messages_and_media/message_entity.py index 88beeb2f..160d0d1e 100644 --- a/pyrogram/client/types/messages_and_media/message_entity.py +++ b/pyrogram/client/types/messages_and_media/message_entity.py @@ -47,6 +47,8 @@ class MessageEntity(PyrogramType): For "text_mention" only, the mentioned user. """ + __slots__ = ["type", "offset", "length", "url", "user"] + ENTITIES = { types.MessageEntityMention.ID: "mention", types.MessageEntityHashtag.ID: "hashtag", @@ -63,14 +65,16 @@ class MessageEntity(PyrogramType): types.MessageEntityPhone.ID: "phone_number" } - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - type: str, - offset: int, - length: int, - url: str = None, - user: User = None): + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + type: str, + offset: int, + length: int, + url: str = None, + user: User = None + ): super().__init__(client) self.type = type diff --git a/pyrogram/client/types/messages_and_media/messages.py b/pyrogram/client/types/messages_and_media/messages.py index a48b6acf..0516f0a0 100644 --- a/pyrogram/client/types/messages_and_media/messages.py +++ b/pyrogram/client/types/messages_and_media/messages.py @@ -37,11 +37,15 @@ class Messages(PyrogramType, Update): Requested messages. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - total_count: int, - messages: List[Message]): + __slots__ = ["total_count", "messages"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + total_count: int, + messages: List[Message] + ): super().__init__(client) self.total_count = total_count diff --git a/pyrogram/client/types/messages_and_media/photo.py b/pyrogram/client/types/messages_and_media/photo.py index aa2b3a26..6f1852fb 100644 --- a/pyrogram/client/types/messages_and_media/photo.py +++ b/pyrogram/client/types/messages_and_media/photo.py @@ -41,12 +41,16 @@ class Photo(PyrogramType): Available sizes of this photo. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: str, - date: int, - sizes: List[PhotoSize]): + __slots__ = ["id", "date", "sizes"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: str, + date: int, + sizes: List[PhotoSize] + ): super().__init__(client) self.id = id diff --git a/pyrogram/client/types/messages_and_media/photo_size.py b/pyrogram/client/types/messages_and_media/photo_size.py index 116b564c..10d00a86 100644 --- a/pyrogram/client/types/messages_and_media/photo_size.py +++ b/pyrogram/client/types/messages_and_media/photo_size.py @@ -42,13 +42,17 @@ class PhotoSize(PyrogramType): File size. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - width: int, - height: int, - file_size: int): + __slots__ = ["file_id", "width", "height", "file_size"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + width: int, + height: int, + file_size: int + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/poll.py b/pyrogram/client/types/messages_and_media/poll.py index 72735c28..68667334 100644 --- a/pyrogram/client/types/messages_and_media/poll.py +++ b/pyrogram/client/types/messages_and_media/poll.py @@ -47,15 +47,19 @@ class Poll(PyrogramType): The index of your chosen option (in case you voted already), None otherwise. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: int, - closed: bool, - question: str, - options: List[PollOption], - total_voters: int, - option_chosen: int = None): + __slots__ = ["id", "closed", "question", "options", "total_voters", "option_chosen"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: int, + closed: bool, + question: str, + options: List[PollOption], + total_voters: int, + option_chosen: int = None + ): super().__init__(client) self.id = id diff --git a/pyrogram/client/types/messages_and_media/poll_option.py b/pyrogram/client/types/messages_and_media/poll_option.py index 227fe74f..a2be866e 100644 --- a/pyrogram/client/types/messages_and_media/poll_option.py +++ b/pyrogram/client/types/messages_and_media/poll_option.py @@ -34,12 +34,16 @@ class PollOption(PyrogramType): Unique data that identifies this option among all the other options in a poll. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - text: str, - voters: int, - data: bytes): + __slots__ = ["text", "voters", "data"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + text: str, + voters: int, + data: bytes + ): super().__init__(client) self.text = text diff --git a/pyrogram/client/types/messages_and_media/sticker.py b/pyrogram/client/types/messages_and_media/sticker.py index d0dc8cf6..b114bc7b 100644 --- a/pyrogram/client/types/messages_and_media/sticker.py +++ b/pyrogram/client/types/messages_and_media/sticker.py @@ -65,19 +65,25 @@ class Sticker(PyrogramType): # TODO: Add mask position - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - width: int, - height: int, - thumb: PhotoSize = None, - file_name: str = None, - mime_type: str = None, - file_size: int = None, - date: int = None, - emoji: str = None, - set_name: str = None): + __slots__ = [ + "file_id", "thumb", "file_name", "mime_type", "file_size", "date", "width", "height", "emoji", "set_name" + ] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + width: int, + height: int, + thumb: PhotoSize = None, + file_name: str = None, + mime_type: str = None, + file_size: int = None, + date: int = None, + emoji: str = None, + set_name: str = None + ): super().__init__(client) self.file_id = file_id @@ -98,7 +104,10 @@ class Sticker(PyrogramType): try: return (await send( functions.messages.GetStickerSet( - types.InputStickerSetID(*input_sticker_set_id) + stickerset=types.InputStickerSetID( + id=input_sticker_set_id[0], + access_hash=input_sticker_set_id[1] + ) ) )).set.short_name except StickersetInvalid: diff --git a/pyrogram/client/types/messages_and_media/user_profile_photos.py b/pyrogram/client/types/messages_and_media/user_profile_photos.py index 8f8525cc..f162b077 100644 --- a/pyrogram/client/types/messages_and_media/user_profile_photos.py +++ b/pyrogram/client/types/messages_and_media/user_profile_photos.py @@ -34,11 +34,15 @@ class UserProfilePhotos(PyrogramType): Requested profile pictures. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - total_count: int, - photos: List[Photo]): + __slots__ = ["total_count", "photos"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + total_count: int, + photos: List[Photo] + ): super().__init__(client) self.total_count = total_count diff --git a/pyrogram/client/types/messages_and_media/venue.py b/pyrogram/client/types/messages_and_media/venue.py index 91b3455a..97829142 100644 --- a/pyrogram/client/types/messages_and_media/venue.py +++ b/pyrogram/client/types/messages_and_media/venue.py @@ -44,14 +44,18 @@ class Venue(PyrogramType): """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - location: Location, - title: str, - address: str, - foursquare_id: str = None, - foursquare_type: str = None): + __slots__ = ["location", "title", "address", "foursquare_id", "foursquare_type"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + location: Location, + title: str, + address: str, + foursquare_id: str = None, + foursquare_type: str = None + ): super().__init__(client) self.location = location diff --git a/pyrogram/client/types/messages_and_media/video.py b/pyrogram/client/types/messages_and_media/video.py index 2ec9a947..caf34ce9 100644 --- a/pyrogram/client/types/messages_and_media/video.py +++ b/pyrogram/client/types/messages_and_media/video.py @@ -57,18 +57,22 @@ class Video(PyrogramType): Date the video was sent in Unix time. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - width: int, - height: int, - duration: int, - thumb: PhotoSize = None, - file_name: str = None, - mime_type: str = None, - file_size: int = None, - date: int = None): + __slots__ = ["file_id", "thumb", "file_name", "mime_type", "file_size", "date", "width", "height", "duration"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + width: int, + height: int, + duration: int, + thumb: PhotoSize = None, + file_name: str = None, + mime_type: str = None, + file_size: int = None, + date: int = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/video_note.py b/pyrogram/client/types/messages_and_media/video_note.py index 73bb85dc..a1b3856c 100644 --- a/pyrogram/client/types/messages_and_media/video_note.py +++ b/pyrogram/client/types/messages_and_media/video_note.py @@ -51,16 +51,20 @@ class VideoNote(PyrogramType): Date the video note was sent in Unix time. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - length: int, - duration: int, - thumb: PhotoSize = None, - mime_type: str = None, - file_size: int = None, - date: int = None): + __slots__ = ["file_id", "thumb", "mime_type", "file_size", "date", "length", "duration"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + length: int, + duration: int, + thumb: PhotoSize = None, + mime_type: str = None, + file_size: int = None, + date: int = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/messages_and_media/voice.py b/pyrogram/client/types/messages_and_media/voice.py index e6bba45b..b4063088 100644 --- a/pyrogram/client/types/messages_and_media/voice.py +++ b/pyrogram/client/types/messages_and_media/voice.py @@ -47,15 +47,19 @@ class Voice(PyrogramType): Date the voice was sent in Unix time. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - file_id: str, - duration: int, - waveform: bytes = None, - mime_type: str = None, - file_size: int = None, - date: int = None): + __slots__ = ["file_id", "duration", "waveform", "mime_type", "file_size", "date"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + file_id: str, + duration: int, + waveform: bytes = None, + mime_type: str = None, + file_size: int = None, + date: int = None + ): super().__init__(client) self.file_id = file_id diff --git a/pyrogram/client/types/pyrogram_type.py b/pyrogram/client/types/pyrogram_type.py index 3708cdc5..d746e6a7 100644 --- a/pyrogram/client/types/pyrogram_type.py +++ b/pyrogram/client/types/pyrogram_type.py @@ -17,15 +17,17 @@ # along with Pyrogram. If not, see . from collections import OrderedDict -from json import dumps, JSONEncoder +from json import dumps class PyrogramType: + __slots__ = ["_client"] + def __init__(self, client): self._client = client def __str__(self): - return dumps(self, cls=Encoder, indent=4) + return dumps(self, indent=4, default=default, ensure_ascii=False) def __getitem__(self, item): return getattr(self, item) @@ -40,15 +42,9 @@ def remove_none(obj): return obj -class Encoder(JSONEncoder): - def default(self, o: PyrogramType): - try: - content = { - i: getattr(o, i) - for i in filter(lambda x: not x.startswith("_"), o.__dict__) - } - except AttributeError: - return repr(o) +def default(o: PyrogramType): + try: + content = {i: getattr(o, i) for i in o.__slots__} return remove_none( OrderedDict( @@ -56,3 +52,5 @@ class Encoder(JSONEncoder): + [i for i in content.items()] ) ) + except AttributeError: + return repr(o) diff --git a/pyrogram/client/types/update.py b/pyrogram/client/types/update.py index 37307111..f129b4ce 100644 --- a/pyrogram/client/types/update.py +++ b/pyrogram/client/types/update.py @@ -26,6 +26,8 @@ class ContinuePropagation(StopAsyncIteration): class Update: + __slots__ = [] + def stop_propagation(self): raise StopPropagation diff --git a/pyrogram/client/types/user_and_chats/chat.py b/pyrogram/client/types/user_and_chats/chat.py index 8914a2cf..040c76bc 100644 --- a/pyrogram/client/types/user_and_chats/chat.py +++ b/pyrogram/client/types/user_and_chats/chat.py @@ -16,6 +16,8 @@ # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see . +from typing import Union + import pyrogram from pyrogram.api import types from .chat_permissions import ChatPermissions @@ -73,26 +75,37 @@ class Chat(PyrogramType): restriction_reason (``str``, *optional*): The reason why this chat might be unavailable to some users. + + permissions (:obj:`ChatPermissions ` *optional*): + Information about the chat default permissions. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: int, - type: str, - title: str = None, - username: str = None, - first_name: str = None, - last_name: str = None, - photo: ChatPhoto = None, - description: str = None, - invite_link: str = None, - pinned_message=None, - sticker_set_name: str = None, - can_set_sticker_set: bool = None, - members_count: int = None, - restriction_reason: str = None, - default_permissions: "pyrogram.ChatPermissions" = None): + __slots__ = [ + "id", "type", "title", "username", "first_name", "last_name", "photo", "description", "invite_link", + "pinned_message", "sticker_set_name", "can_set_sticker_set", "members_count", "restriction_reason", + "permissions" + ] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: int, + type: str, + title: str = None, + username: str = None, + first_name: str = None, + last_name: str = None, + photo: ChatPhoto = None, + description: str = None, + invite_link: str = None, + pinned_message=None, + sticker_set_name: str = None, + can_set_sticker_set: bool = None, + members_count: int = None, + restriction_reason: str = None, + permissions: "pyrogram.ChatPermissions" = None + ): super().__init__(client) self.id = id @@ -109,7 +122,7 @@ class Chat(PyrogramType): self.can_set_sticker_set = can_set_sticker_set self.members_count = members_count self.restriction_reason = restriction_reason - self.default_permissions = default_permissions + self.permissions = permissions @staticmethod def _parse_user_chat(client, user: types.User) -> "Chat": @@ -131,7 +144,7 @@ class Chat(PyrogramType): type="group", title=chat.title, photo=ChatPhoto._parse(client, getattr(chat, "photo", None)), - default_permissions=ChatPermissions._parse(chat.default_banned_rights), + permissions=ChatPermissions._parse(chat.default_banned_rights), client=client ) @@ -144,7 +157,7 @@ class Chat(PyrogramType): username=getattr(channel, "username", None), photo=ChatPhoto._parse(client, getattr(channel, "photo", None)), restriction_reason=getattr(channel, "restriction_reason", None), - default_permissions=ChatPermissions._parse(channel.default_banned_rights), + permissions=ChatPermissions._parse(channel.default_banned_rights), client=client ) @@ -205,9 +218,7 @@ class Chat(PyrogramType): return parsed_chat @staticmethod - def _parse_chat(client, chat): - # A wrapper around each entity parser: User, Chat and Channel. - # Currently unused, might become useful in future. + def _parse_chat(client, chat: Union[types.Chat, types.User, types.Channel]) -> "Chat": if isinstance(chat, types.Chat): return Chat._parse_chat_chat(client, chat) elif isinstance(chat, types.User): diff --git a/pyrogram/client/types/user_and_chats/chat_member.py b/pyrogram/client/types/user_and_chats/chat_member.py index 5769b3f8..35911210 100644 --- a/pyrogram/client/types/user_and_chats/chat_member.py +++ b/pyrogram/client/types/user_and_chats/chat_member.py @@ -51,16 +51,20 @@ class ChatMember(PyrogramType): Information about the member permissions. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - user: "pyrogram.User", - status: str, - date: int = None, - invited_by: "pyrogram.User" = None, - promoted_by: "pyrogram.User" = None, - restricted_by: "pyrogram.User" = None, - permissions: "pyrogram.ChatPermissions" = None): + __slots__ = ["user", "status", "date", "invited_by", "promoted_by", "restricted_by", "permissions"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + user: "pyrogram.User", + status: str, + date: int = None, + invited_by: "pyrogram.User" = None, + promoted_by: "pyrogram.User" = None, + restricted_by: "pyrogram.User" = None, + permissions: "pyrogram.ChatPermissions" = None + ): super().__init__(client) self.user = user diff --git a/pyrogram/client/types/user_and_chats/chat_members.py b/pyrogram/client/types/user_and_chats/chat_members.py index 39d69089..3c89b124 100644 --- a/pyrogram/client/types/user_and_chats/chat_members.py +++ b/pyrogram/client/types/user_and_chats/chat_members.py @@ -21,7 +21,6 @@ from typing import List import pyrogram from pyrogram.api import types from .chat_member import ChatMember -from .user import User from ..pyrogram_type import PyrogramType @@ -36,11 +35,15 @@ class ChatMembers(PyrogramType): Requested chat members. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - total_count: int, - chat_members: List[ChatMember]): + __slots__ = ["total_count", "chat_members"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + total_count: int, + chat_members: List[ChatMember] + ): super().__init__(client) self.total_count = total_count diff --git a/pyrogram/client/types/user_and_chats/chat_permissions.py b/pyrogram/client/types/user_and_chats/chat_permissions.py index a931cd7a..7b35b1d0 100644 --- a/pyrogram/client/types/user_and_chats/chat_permissions.py +++ b/pyrogram/client/types/user_and_chats/chat_permissions.py @@ -94,28 +94,35 @@ class ChatPermissions(PyrogramType): True, if polls can be sent, implies can_send_media_messages. """ + __slots__ = [ + "until_date", "can_be_edited", "can_change_info", "can_post_messages", "can_edit_messages", + "can_delete_messages", "can_restrict_members", "can_invite_users", "can_pin_messages", "can_promote_members", + "can_send_messages", "can_send_media_messages", "can_send_other_messages", "can_add_web_page_previews", + "can_send_polls" + ] + def __init__( - self, - *, - until_date: int = None, + self, + *, + until_date: int = None, - # Admin permissions - can_be_edited: bool = None, - can_change_info: bool = None, - can_post_messages: bool = None, # Channels only - can_edit_messages: bool = None, # Channels only - can_delete_messages: bool = None, - can_restrict_members: bool = None, - can_invite_users: bool = None, - can_pin_messages: bool = None, # Supergroups only - can_promote_members: bool = None, + # Admin permissions + can_be_edited: bool = None, + can_change_info: bool = None, + can_post_messages: bool = None, # Channels only + can_edit_messages: bool = None, # Channels only + can_delete_messages: bool = None, + can_restrict_members: bool = None, + can_invite_users: bool = None, + can_pin_messages: bool = None, # Supergroups only + can_promote_members: bool = None, - # Restricted user permissions - can_send_messages: bool = None, # Text, contacts, locations and venues - can_send_media_messages: bool = None, # Audios, documents, photos, videos, video notes and voice notes - can_send_other_messages: bool = None, # Animations (GIFs), games, stickers, inline bot results - can_add_web_page_previews: bool = None, - can_send_polls: bool = None + # Restricted user permissions + can_send_messages: bool = None, # Text, contacts, locations and venues + can_send_media_messages: bool = None, # Audios, documents, photos, videos, video notes and voice notes + can_send_other_messages: bool = None, # Animations (GIFs), games, stickers, inline bot results + can_add_web_page_previews: bool = None, + can_send_polls: bool = None ): super().__init__(None) @@ -139,11 +146,11 @@ class ChatPermissions(PyrogramType): @staticmethod def _parse( - entity: Union[ - types.ChannelParticipantAdmin, - types.ChannelParticipantBanned, - types.ChatBannedRights - ] + entity: Union[ + types.ChannelParticipantAdmin, + types.ChannelParticipantBanned, + types.ChatBannedRights + ] ) -> "ChatPermissions": if isinstance(entity, types.ChannelParticipantAdmin): permissions = entity.admin_rights @@ -171,8 +178,8 @@ class ChatPermissions(PyrogramType): can_send_messages=not denied_permissions.send_messages, can_send_media_messages=not denied_permissions.send_media, can_send_other_messages=( - not denied_permissions.send_stickers or not denied_permissions.send_gifs or - not denied_permissions.send_games or not denied_permissions.send_inline + not denied_permissions.send_stickers or not denied_permissions.send_gifs or + not denied_permissions.send_games or not denied_permissions.send_inline ), can_add_web_page_previews=not denied_permissions.embed_links, can_send_polls=not denied_permissions.send_polls, diff --git a/pyrogram/client/types/user_and_chats/chat_photo.py b/pyrogram/client/types/user_and_chats/chat_photo.py index 848f7250..6fbc779d 100644 --- a/pyrogram/client/types/user_and_chats/chat_photo.py +++ b/pyrogram/client/types/user_and_chats/chat_photo.py @@ -35,11 +35,15 @@ class ChatPhoto(PyrogramType): Unique file identifier of big (640x640) chat photo. This file_id can be used only for photo download. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - small_file_id: str, - big_file_id: str): + __slots__ = ["small_file_id", "big_file_id"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + small_file_id: str, + big_file_id: str + ): super().__init__(client) self.small_file_id = small_file_id diff --git a/pyrogram/client/types/user_and_chats/chat_preview.py b/pyrogram/client/types/user_and_chats/chat_preview.py index 45048637..ddd84b09 100644 --- a/pyrogram/client/types/user_and_chats/chat_preview.py +++ b/pyrogram/client/types/user_and_chats/chat_preview.py @@ -45,14 +45,18 @@ class ChatPreview(PyrogramType): Preview of some of the chat members. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - title: str, - photo: ChatPhoto, - type: str, - members_count: int, - members: List[User] = None): + __slots__ = ["title", "photo", "type", "members_count", "members"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + title: str, + photo: ChatPhoto, + type: str, + members_count: int, + members: List[User] = None + ): super().__init__(client) self.title = title diff --git a/pyrogram/client/types/user_and_chats/dialog.py b/pyrogram/client/types/user_and_chats/dialog.py index b71caba7..1bbd3b4b 100644 --- a/pyrogram/client/types/user_and_chats/dialog.py +++ b/pyrogram/client/types/user_and_chats/dialog.py @@ -46,15 +46,19 @@ class Dialog(PyrogramType): True, if the dialog is pinned. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - chat: Chat, - top_message: "pyrogram.Message", - unread_messages_count: int, - unread_mentions_count: int, - unread_mark: bool, - is_pinned: bool): + __slots__ = ["chat", "top_message", "unread_messages_count", "unread_mentions_count", "unread_mark", "is_pinned"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + chat: Chat, + top_message: "pyrogram.Message", + unread_messages_count: int, + unread_mentions_count: int, + unread_mark: bool, + is_pinned: bool + ): super().__init__(client) self.chat = chat diff --git a/pyrogram/client/types/user_and_chats/dialogs.py b/pyrogram/client/types/user_and_chats/dialogs.py index b3c2d773..878f73f1 100644 --- a/pyrogram/client/types/user_and_chats/dialogs.py +++ b/pyrogram/client/types/user_and_chats/dialogs.py @@ -36,11 +36,15 @@ class Dialogs(PyrogramType): Requested dialogs. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - total_count: int, - dialogs: List[Dialog]): + __slots__ = ["total_count", "dialogs"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + total_count: int, + dialogs: List[Dialog] + ): super().__init__(client) self.total_count = total_count diff --git a/pyrogram/client/types/user_and_chats/user.py b/pyrogram/client/types/user_and_chats/user.py index c6ee03e8..5718b917 100644 --- a/pyrogram/client/types/user_and_chats/user.py +++ b/pyrogram/client/types/user_and_chats/user.py @@ -70,23 +70,30 @@ class User(PyrogramType): The reason why this bot might be unavailable to some users. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - id: int, - is_self: bool, - is_contact: bool, - is_mutual_contact: bool, - is_deleted: bool, - is_bot: bool, - first_name: str, - last_name: str = None, - status: UserStatus = None, - username: str = None, - language_code: str = None, - phone_number: str = None, - photo: ChatPhoto = None, - restriction_reason: str = None): + __slots__ = [ + "id", "is_self", "is_contact", "is_mutual_contact", "is_deleted", "is_bot", "first_name", "last_name", "status", + "username", "language_code", "phone_number", "photo", "restriction_reason" + ] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + id: int, + is_self: bool, + is_contact: bool, + is_mutual_contact: bool, + is_deleted: bool, + is_bot: bool, + first_name: str, + last_name: str = None, + status: UserStatus = None, + username: str = None, + language_code: str = None, + phone_number: str = None, + photo: ChatPhoto = None, + restriction_reason: str = None + ): super().__init__(client) self.id = id diff --git a/pyrogram/client/types/user_and_chats/user_status.py b/pyrogram/client/types/user_and_chats/user_status.py index 8c936f8e..170ce373 100644 --- a/pyrogram/client/types/user_and_chats/user_status.py +++ b/pyrogram/client/types/user_and_chats/user_status.py @@ -65,17 +65,21 @@ class UserStatus(PyrogramType, Update): always shown to blocked users), None otherwise. """ - def __init__(self, - *, - client: "pyrogram.client.ext.BaseClient", - user_id: int, - online: bool = None, - offline: bool = None, - date: int = None, - recently: bool = None, - within_week: bool = None, - within_month: bool = None, - long_time_ago: bool = None): + __slots__ = ["user_id", "online", "offline", "date", "recently", "within_week", "within_month", "long_time_ago"] + + def __init__( + self, + *, + client: "pyrogram.client.ext.BaseClient", + user_id: int, + online: bool = None, + offline: bool = None, + date: int = None, + recently: bool = None, + within_week: bool = None, + within_month: bool = None, + long_time_ago: bool = None + ): super().__init__(client) self.user_id = user_id diff --git a/pyrogram/connection/transport/tcp/tcp_abridged_o.py b/pyrogram/connection/transport/tcp/tcp_abridged_o.py index 541cd458..3ec6a002 100644 --- a/pyrogram/connection/transport/tcp/tcp_abridged_o.py +++ b/pyrogram/connection/transport/tcp/tcp_abridged_o.py @@ -40,9 +40,7 @@ class TCPAbridgedO(TCP): while True: nonce = bytearray(os.urandom(64)) - if (nonce[0] != b"\xef" - and nonce[:4] not in self.RESERVED - and nonce[4:4] != b"\x00" * 4): + if nonce[0] != b"\xef" and nonce[:4] not in self.RESERVED and nonce[4:4] != b"\x00" * 4: nonce[56] = nonce[57] = nonce[58] = nonce[59] = 0xef break diff --git a/pyrogram/connection/transport/tcp/tcp_intermediate_o.py b/pyrogram/connection/transport/tcp/tcp_intermediate_o.py index a6fe92cd..8d7113a5 100644 --- a/pyrogram/connection/transport/tcp/tcp_intermediate_o.py +++ b/pyrogram/connection/transport/tcp/tcp_intermediate_o.py @@ -41,9 +41,7 @@ class TCPIntermediateO(TCP): while True: nonce = bytearray(os.urandom(64)) - if (nonce[0] != b"\xef" - and nonce[:4] not in self.RESERVED - and nonce[4:4] != b"\x00" * 4): + if nonce[0] != b"\xef" and nonce[:4] not in self.RESERVED and nonce[4:4] != b"\x00" * 4: nonce[56] = nonce[57] = nonce[58] = nonce[59] = 0xee break diff --git a/pyrogram/session/auth.py b/pyrogram/session/auth.py index f966705f..026c295d 100644 --- a/pyrogram/session/auth.py +++ b/pyrogram/session/auth.py @@ -84,7 +84,7 @@ class Auth: # Step 1; Step 2 nonce = int.from_bytes(urandom(16), "little", signed=True) log.debug("Send req_pq: {}".format(nonce)) - res_pq = await self.send(functions.ReqPqMulti(nonce)) + res_pq = await self.send(functions.ReqPqMulti(nonce=nonce)) log.debug("Got ResPq: {}".format(res_pq.server_nonce)) log.debug("Server public key fingerprints: {}".format(res_pq.server_public_key_fingerprints)) @@ -111,12 +111,12 @@ class Auth: new_nonce = int.from_bytes(urandom(32), "little", signed=True) data = types.PQInnerData( - res_pq.pq, - p.to_bytes(4, "big"), - q.to_bytes(4, "big"), - nonce, - server_nonce, - new_nonce, + pq=res_pq.pq, + p=p.to_bytes(4, "big"), + q=q.to_bytes(4, "big"), + nonce=nonce, + server_nonce=server_nonce, + new_nonce=new_nonce, ).write() sha = sha1(data).digest() @@ -130,12 +130,12 @@ class Auth: log.debug("Send req_DH_params") server_dh_params = await self.send( functions.ReqDHParams( - nonce, - server_nonce, - p.to_bytes(4, "big"), - q.to_bytes(4, "big"), - public_key_fingerprint, - encrypted_data + nonce=nonce, + server_nonce=server_nonce, + p=p.to_bytes(4, "big"), + q=q.to_bytes(4, "big"), + public_key_fingerprint=public_key_fingerprint, + encrypted_data=encrypted_data ) ) @@ -176,10 +176,10 @@ class Auth: retry_id = 0 data = types.ClientDHInnerData( - nonce, - server_nonce, - retry_id, - g_b + nonce=nonce, + server_nonce=server_nonce, + retry_id=retry_id, + g_b=g_b ).write() sha = sha1(data).digest() @@ -190,9 +190,9 @@ class Auth: log.debug("Send set_client_DH_params") set_client_dh_params_answer = await self.send( functions.SetClientDHParams( - nonce, - server_nonce, - encrypted_data + nonce=nonce, + server_nonce=server_nonce, + encrypted_data=encrypted_data ) ) diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py index c4404abd..bc7b89de 100644 --- a/pyrogram/session/session.py +++ b/pyrogram/session/session.py @@ -122,19 +122,19 @@ class Session: self.current_salt = FutureSalt( 0, 0, (await self._send( - functions.Ping(0), + functions.Ping(ping_id=0), timeout=self.START_TIMEOUT )).new_server_salt ) - self.current_salt = (await self._send(functions.GetFutureSalts(1), timeout=self.START_TIMEOUT)).salts[0] + self.current_salt = (await self._send(functions.GetFutureSalts(num=1), timeout=self.START_TIMEOUT)).salts[0] self.next_salt_task = asyncio.ensure_future(self.next_salt()) if not self.is_cdn: await self._send( functions.InvokeWithLayer( - layer, - functions.InitConnection( + layer=layer, + query=functions.InitConnection( api_id=self.client.api_id, app_version=self.client.app_version, device_model=self.client.device_model, @@ -266,7 +266,7 @@ class Session: log.info("Send {} acks".format(len(self.pending_acks))) try: - await self._send(types.MsgsAck(list(self.pending_acks)), False) + await self._send(types.MsgsAck(msg_ids=list(self.pending_acks)), False) except (OSError, TimeoutError): pass else: @@ -290,7 +290,7 @@ class Session: try: await self._send( functions.PingDelayDisconnect( - 0, self.WAIT_TIMEOUT + 10 + ping_id=0, disconnect_delay=self.WAIT_TIMEOUT + 10 ), False ) except (OSError, TimeoutError, Error): @@ -321,7 +321,7 @@ class Session: break try: - self.current_salt = (await self._send(functions.GetFutureSalts(1))).salts[0] + self.current_salt = (await self._send(functions.GetFutureSalts(num=1))).salts[0] except (OSError, TimeoutError, Error): self.connection.close() break diff --git a/pyrogram/vendor/typing/typing.py b/pyrogram/vendor/typing/typing.py index 2189cd48..16888d3f 100644 --- a/pyrogram/vendor/typing/typing.py +++ b/pyrogram/vendor/typing/typing.py @@ -1,17 +1,18 @@ import abc -from abc import abstractmethod, abstractproperty import collections import contextlib import functools import re as stdlib_re # Avoid confusion with the re we export. import sys import types +from abc import abstractmethod, abstractproperty + try: import collections.abc as collections_abc except ImportError: import collections as collections_abc # Fallback for PY3.2. if sys.version_info[:2] >= (3, 6): - import _collections_abc # Needed for private function _check_methods # noqa + pass try: from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType except ImportError: @@ -19,7 +20,6 @@ except ImportError: MethodWrapperType = type(object().__str__) MethodDescriptorType = type(str.join) - # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. @@ -36,7 +36,7 @@ __all__ = [ # ABCs (from collections.abc). 'AbstractSet', # collections.abc.Set. 'GenericMeta', # subclass of abc.ABCMeta and a metaclass - # for 'Generic' and ABCs below. + # for 'Generic' and ABCs below. 'ByteString', 'Container', 'ContextManager', @@ -96,6 +96,7 @@ __all__ = [ 'TYPE_CHECKING', ] + # The pseudo-submodules 're' and 'io' are part of the public # namespace, but excluded from __all__ because they might stomp on # legitimate imports of those modules. @@ -173,8 +174,8 @@ class _TypingBase(metaclass=TypingMeta, _root=True): someone tries to subclass a special typing object (not a good idea). """ if (len(args) == 3 and - isinstance(args[0], str) and - isinstance(args[1], tuple)): + isinstance(args[0], str) and + isinstance(args[1], tuple)): # Close enough. raise TypeError("Cannot subclass %r" % cls) return super().__new__(cls) @@ -396,7 +397,7 @@ def _type_repr(obj): return _qualname(obj) return '%s.%s' % (obj.__module__, _qualname(obj)) if obj is ...: - return('...') + return ('...') if isinstance(obj, types.FunctionType): return obj.__name__ return repr(obj) @@ -681,6 +682,7 @@ def _tp_cache(func): except TypeError: pass # All real errors (not unhashable args) are raised below. return func(*args, **kwds) + return inner @@ -948,7 +950,7 @@ class GenericMeta(TypingMeta, abc.ABCMeta): if base is Generic: raise TypeError("Cannot inherit from plain Generic") if (isinstance(base, GenericMeta) and - base.__origin__ is Generic): + base.__origin__ is Generic): if gvars is not None: raise TypeError( "Cannot inherit from Generic[...] multiple types.") @@ -1183,14 +1185,14 @@ def _generic_new(base_cls, cls, *args, **kwds): # but attempt to store it in __orig_class__ if cls.__origin__ is None: if (base_cls.__new__ is object.__new__ and - cls.__init__ is not object.__init__): + cls.__init__ is not object.__init__): return base_cls.__new__(cls) else: return base_cls.__new__(cls, *args, **kwds) else: origin = cls._gorg if (base_cls.__new__ is object.__new__ and - cls.__init__ is not object.__init__): + cls.__init__ is not object.__init__): obj = base_cls.__new__(origin) else: obj = base_cls.__new__(origin, *args, **kwds) @@ -1399,7 +1401,7 @@ class _ClassVar(_FinalTypingBase, _root=True): cls = type(self) if self.__type__ is None: return cls(_type_check(item, - '{} accepts only single type.'.format(cls.__name__[1:])), + '{} accepts only single type.'.format(cls.__name__[1:])), _root=True) raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) @@ -1671,26 +1673,26 @@ class _ProtocolMeta(GenericMeta): # Include attributes not defined in any non-protocol bases. for c in self.__mro__: if (c is not base and attr in c.__dict__ and - not getattr(c, '_is_protocol', False)): + not getattr(c, '_is_protocol', False)): break else: if (not attr.startswith('_abc_') and - attr != '__abstractmethods__' and - attr != '__annotations__' and - attr != '__weakref__' and - attr != '_is_protocol' and - attr != '_gorg' and - attr != '__dict__' and - attr != '__args__' and - attr != '__slots__' and - attr != '_get_protocol_attrs' and - attr != '__next_in_mro__' and - attr != '__parameters__' and - attr != '__origin__' and - attr != '__orig_bases__' and - attr != '__extra__' and - attr != '__tree_hash__' and - attr != '__module__'): + attr != '__abstractmethods__' and + attr != '__annotations__' and + attr != '__weakref__' and + attr != '_is_protocol' and + attr != '_gorg' and + attr != '__dict__' and + attr != '__args__' and + attr != '__slots__' and + attr != '_get_protocol_attrs' and + attr != '__next_in_mro__' and + attr != '__parameters__' and + attr != '__origin__' and + attr != '__orig_bases__' and + attr != '__extra__' and + attr != '__tree_hash__' and + attr != '__module__'): attrs.add(attr) return attrs @@ -1714,31 +1716,31 @@ class _Protocol(metaclass=_ProtocolMeta): Hashable = collections_abc.Hashable # Not generic. - if hasattr(collections_abc, 'Awaitable'): class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): __slots__ = () - __all__.append('Awaitable') + __all__.append('Awaitable') if hasattr(collections_abc, 'Coroutine'): class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co], extra=collections_abc.Coroutine): __slots__ = () + __all__.append('Coroutine') - if hasattr(collections_abc, 'AsyncIterable'): - class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): __slots__ = () + class AsyncIterator(AsyncIterable[T_co], extra=collections_abc.AsyncIterator): __slots__ = () + __all__.append('AsyncIterable') __all__.append('AsyncIterator') @@ -1810,7 +1812,6 @@ else: def __reversed__(self) -> 'Iterator[T_co]': pass - Sized = collections_abc.Sized # Not generic. @@ -1823,8 +1824,8 @@ if hasattr(collections_abc, 'Collection'): extra=collections_abc.Collection): __slots__ = () - __all__.append('Collection') + __all__.append('Collection') # Callable was defined earlier. @@ -1881,7 +1882,6 @@ class ByteString(Sequence[int], extra=collections_abc.ByteString): class List(list, MutableSequence[T], extra=list): - __slots__ = () def __new__(cls, *args, **kwds): @@ -1892,7 +1892,6 @@ class List(list, MutableSequence[T], extra=list): class Deque(collections.deque, MutableSequence[T], extra=collections.deque): - __slots__ = () def __new__(cls, *args, **kwds): @@ -1902,7 +1901,6 @@ class Deque(collections.deque, MutableSequence[T], extra=collections.deque): class Set(set, MutableSet[T], extra=set): - __slots__ = () def __new__(cls, *args, **kwds): @@ -1969,12 +1967,12 @@ else: return True return NotImplemented - if hasattr(contextlib, 'AbstractAsyncContextManager'): class AsyncContextManager(Generic[T_co], extra=contextlib.AbstractAsyncContextManager): __slots__ = () + __all__.append('AsyncContextManager') elif sys.version_info[:2] >= (3, 5): exec(""" @@ -2003,7 +2001,6 @@ __all__.append('AsyncContextManager') class Dict(dict, MutableMapping[KT, VT], extra=dict): - __slots__ = () def __new__(cls, *args, **kwds): @@ -2015,7 +2012,6 @@ class Dict(dict, MutableMapping[KT, VT], extra=dict): class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], extra=collections.defaultdict): - __slots__ = () def __new__(cls, *args, **kwds): @@ -2025,7 +2021,6 @@ class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], class Counter(collections.Counter, Dict[T, int], extra=collections.Counter): - __slots__ = () def __new__(cls, *args, **kwds): @@ -2038,6 +2033,7 @@ if hasattr(collections, 'ChainMap'): # ChainMap only exists in 3.3+ __all__.append('ChainMap') + class ChainMap(collections.ChainMap, MutableMapping[KT, VT], extra=collections.ChainMap): @@ -2048,7 +2044,6 @@ if hasattr(collections, 'ChainMap'): return collections.ChainMap(*args, **kwds) return _generic_new(collections.ChainMap, cls, *args, **kwds) - # Determine what base class to use for Generator. if hasattr(collections_abc, 'Generator'): # Sufficiently recent versions of 3.5 have a Generator ABC. @@ -2074,8 +2069,8 @@ if hasattr(collections_abc, 'AsyncGenerator'): extra=collections_abc.AsyncGenerator): __slots__ = () - __all__.append('AsyncGenerator') + __all__.append('AsyncGenerator') # Internal type variable used for Type[]. CT_co = TypeVar('CT_co', covariant=True, bound=type) @@ -2237,7 +2232,6 @@ def NewType(name, tp): # Python-version-specific alias (Python 2: unicode; Python 3: str) Text = str - # Constant that's True when type checking, but False here. TYPE_CHECKING = False @@ -2394,7 +2388,6 @@ class io: io.__name__ = __name__ + '.io' sys.modules[io.__name__] = io - Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), lambda p: p.pattern) Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),