diff --git a/.github/workflows/docs_gen.yml b/.github/workflows/docs_gen.yml index 87c7adff..47161998 100644 --- a/.github/workflows/docs_gen.yml +++ b/.github/workflows/docs_gen.yml @@ -7,9 +7,7 @@ on: jobs: build: - - runs-on: ubuntu-22.04 - + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build diff --git a/.github/workflows/error_scrape.yml b/.github/workflows/error_scrape.yml index 86a44723..bb972f5d 100644 --- a/.github/workflows/error_scrape.yml +++ b/.github/workflows/error_scrape.yml @@ -4,6 +4,8 @@ on: jobs: build: + permissions: + id-token: write name: scrape-errors runs-on: ubuntu-latest steps: diff --git a/.github/workflows/format_and_test.yml b/.github/workflows/format_and_test.yml index 05fd6062..c7a2bc9e 100644 --- a/.github/workflows/format_and_test.yml +++ b/.github/workflows/format_and_test.yml @@ -1,4 +1,4 @@ -name: Format and Test Code with Rye +name: Format and test code with uv on: push: @@ -20,20 +20,24 @@ jobs: with: python-version: "3.13" - - name: Install the latest version of rye - uses: eifinger/setup-rye@v4 + - name: Install the latest version of uv + uses: astral-sh/setup-uv@v3 with: - version: 'latest' + version: "latest" - name: Install dependencies run: | - rye pin 3.12 - rye sync + uv python install 3.13 + uv run -m ensurepip --upgrade + uv run -m pip install --upgrade pip + uv tool install pytest + uv run -m pip install pytest + uv lock --upgrade - name: Run ruff to lint and format code run: | - rye run ruff check . --exit-zero - rye fmt + uv tool run ruff check . --exit-zero + uv tool run ruff format . git add -u - name: Commit and push changes @@ -49,8 +53,5 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GX_TOKEN }} - - name: Generate API - run: rye run api - - name: Run tests - run: rye run python -m pytest + run: uv run -m pytest \ No newline at end of file diff --git a/.github/workflows/tag_and_publish.yml b/.github/workflows/tag_and_publish.yml index 6772b0f9..552c3e06 100644 --- a/.github/workflows/tag_and_publish.yml +++ b/.github/workflows/tag_and_publish.yml @@ -52,13 +52,13 @@ jobs: release_name: Release ${{ env.VERSION }} body_path: ./release_notes.txt - - name: Build + - name: Build and publish if: env.RELEASE_EXISTS == 'false' run: | python -m pip install --upgrade pip pip install -e '.[dev]' hatch build - - - name: Publish - if: env.RELEASE_EXISTS == 'false' - uses: pypa/gh-action-pypi-publish@release/v1 + hatch publish + env: + HATCH_INDEX_USER: __token__ + HATCH_INDEX_AUTH: ${{ secrets.PYPI_API_TOKEN }} \ No newline at end of file diff --git a/README.md b/README.md index 5fab59b7..7fcb20f5 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,7 @@ This repository is a personal clone of Pyrogram, created specifically for my pro Please understand that any issues, modifications, or deviations from the original project are solely my responsibility. Do not hold me accountable for any problems or discrepancies that may arise from using this repository. Thank you for your understanding. + + +## Recent activity [![Time period](https://images.repography.com/58464391/AeonOrg/Electrogram/recent-activity/gf9SHLZa6sqXRpReIT2U07ZtsB7JysNRXMyhy4b2tgE/9c16LtrRR82Ubh9Kw6CMclKpbhDemGuBCxkZUuGJjts_badge.svg)](https://repography.com) +[![Timeline graph](https://images.repography.com/58464391/AeonOrg/Electrogram/recent-activity/gf9SHLZa6sqXRpReIT2U07ZtsB7JysNRXMyhy4b2tgE/9c16LtrRR82Ubh9Kw6CMclKpbhDemGuBCxkZUuGJjts_timeline.svg)](https://github.com/AeonOrg/Electrogram/commits) diff --git a/compiler/api/compiler.py b/compiler/api/compiler.py index 19dfc787..c1cea073 100644 --- a/compiler/api/compiler.py +++ b/compiler/api/compiler.py @@ -16,7 +16,8 @@ SECTION_RE = re.compile(r"---(\w+)---") LAYER_RE = re.compile(r"//\sLAYER\s(\d+)") COMBINATOR_RE = re.compile( - r"^([\w.]+)#([0-9a-f]+)\s(?:.*)=\s([\w<>.]+);$", re.MULTILINE + r"^([\w.]+)#([0-9a-f]+)\s(?:.*)=\s([\w<>.]+);$", + re.MULTILINE, ) ARGS_RE = re.compile(r"[^{](\w+):([\w?!.<>#]+)") FLAGS_RE = re.compile(r"flags(\d?)\.(\d+)\?") @@ -183,7 +184,7 @@ def get_references(t: str, kind: str): return ("\n ".join(items), len(items)) if items else (None, 0) -def start() -> None: +def start() -> None: # noqa: C901 shutil.rmtree(DESTINATION_PATH / "types", ignore_errors=True) shutil.rmtree(DESTINATION_PATH / "functions", ignore_errors=True) shutil.rmtree(DESTINATION_PATH / "base", ignore_errors=True) @@ -327,7 +328,7 @@ def start() -> None: qualname=qualtype, types=", ".join([f'"raw.types.{c}"' for c in constructors]), doc_name=snake(type).replace("_", "-"), - ) + ), ) for c in combinators: @@ -341,7 +342,7 @@ def start() -> None: fields = ( "\n ".join( - [f"self.{i[0]} = {i[0]} # {i[1]}" for i in sorted_args] + [f"self.{i[0]} = {i[0]} # {i[1]}" for i in sorted_args], ) if sorted_args else "pass" @@ -364,7 +365,7 @@ def start() -> None: arg_docs = arg_docs["params"].get(arg_name, "N/A") if arg_docs else "N/A" docstring_args.append( - f'{arg_name} ({get_docstring_arg_type(arg_type)}{", *optional*" if is_optional else ""}):\n {arg_docs}\n' + f'{arg_name} ({get_docstring_arg_type(arg_type)}{", *optional*" if is_optional else ""}):\n {arg_docs}\n', ) if c.section == "types": @@ -393,7 +394,7 @@ def start() -> None: if c.section == "functions": docstring += "\n Returns:\n " + get_docstring_arg_type( - c.qualtype + c.qualtype, ) else: references, count = get_references(c.qualname, "constructors") @@ -417,14 +418,14 @@ def start() -> None: continue if flag.group(3) == "true" or flag.group(3).startswith( - "Vector" + "Vector", ): write_flags.append( - f"{arg_name} |= (1 << {flag.group(2)}) if self.{i[0]} else 0" + f"{arg_name} |= (1 << {flag.group(2)}) if self.{i[0]} else 0", ) else: write_flags.append( - f"{arg_name} |= (1 << {flag.group(2)}) if self.{i[0]} is not None else 0" + f"{arg_name} |= (1 << {flag.group(2)}) if self.{i[0]} is not None else 0", ) write_flags = "\n ".join( @@ -432,7 +433,7 @@ def start() -> None: f"{arg_name} = 0", "\n ".join(write_flags), f"b.write(Int({arg_name}))\n ", - ] + ], ) write_types += write_flags @@ -555,7 +556,7 @@ def start() -> None: if not namespace: f.write( - f"from . import {', '.join(filter(bool, namespaces_to_types))}" + f"from . import {', '.join(filter(bool, namespaces_to_types))}", ) all.extend(filter(bool, namespaces_to_types)) @@ -583,7 +584,7 @@ def start() -> None: if not namespace: f.write( - f"from . import {', '.join(filter(bool, namespaces_to_constructors))}\n" + f"from . import {', '.join(filter(bool, namespaces_to_constructors))}\n", ) all.extend(filter(bool, namespaces_to_constructors)) @@ -595,7 +596,8 @@ def start() -> None: for namespace, types in namespaces_to_functions.items(): with open( - DESTINATION_PATH / "functions" / namespace / "__init__.py", "w" + DESTINATION_PATH / "functions" / namespace / "__init__.py", + "w", ) as f: f.write(f"{WARNING}\n\n") @@ -613,7 +615,7 @@ def start() -> None: if not namespace: f.write( - f"from . import {', '.join(filter(bool, namespaces_to_functions))}" + f"from . import {', '.join(filter(bool, namespaces_to_functions))}", ) all.extend(filter(bool, namespaces_to_functions)) diff --git a/compiler/api/source/main_api.tl b/compiler/api/source/main_api.tl index 3cd31184..c97ccfe5 100644 --- a/compiler/api/source/main_api.tl +++ b/compiler/api/source/main_api.tl @@ -1,5 +1,9 @@ ---types--- +int ? = Int; +long ? = Long; +double ? = Double; +string ? = String; bytes = Bytes; @@ -14,6 +18,14 @@ bytes = Bytes; // null#56730bcc = Null; // Parsed manually +ipPort#d433ad73 ipv4:int port:int = IpPort; +ipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort; +accessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule; +help.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple; + +inputPeerPhotoFileLocationLegacy#27d69997 flags:# big:flags.0?true peer:InputPeer volume_id:long local_id:int = InputFileLocation; +inputStickerSetThumbLegacy#dbaeae9 stickerset:InputStickerSet volume_id:long local_id:int = InputFileLocation; + inputPeerEmpty#7f3b18ea = InputPeer; inputPeerSelf#7da07ec9 = InputPeer; inputPeerChat#35a95cb9 chat_id:long = InputPeer; @@ -89,7 +101,7 @@ storage.fileMp4#b3cea0e4 = storage.FileType; storage.fileWebp#1081464c = storage.FileType; userEmpty#d3bc4b7a id:long = User; -user#83314fca flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true bot_attach_menu:flags.27?true premium:flags.28?true attach_menu_enabled:flags.29?true flags2:# bot_can_edit:flags2.1?true close_friend:flags2.2?true stories_hidden:flags2.3?true stories_unavailable:flags2.4?true contact_require_premium:flags2.10?true bot_business:flags2.11?true bot_has_main_app:flags2.13?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string emoji_status:flags.30?EmojiStatus usernames:flags2.0?Vector stories_max_id:flags2.5?int color:flags2.8?PeerColor profile_color:flags2.9?PeerColor bot_active_users:flags2.12?int = User; +user#4b46c37e flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true bot_attach_menu:flags.27?true premium:flags.28?true attach_menu_enabled:flags.29?true flags2:# bot_can_edit:flags2.1?true close_friend:flags2.2?true stories_hidden:flags2.3?true stories_unavailable:flags2.4?true contact_require_premium:flags2.10?true bot_business:flags2.11?true bot_has_main_app:flags2.13?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string emoji_status:flags.30?EmojiStatus usernames:flags2.0?Vector stories_max_id:flags2.5?int color:flags2.8?PeerColor profile_color:flags2.9?PeerColor bot_active_users:flags2.12?int bot_verification_icon:flags2.14?long = User; userProfilePhotoEmpty#4f11bae1 = UserProfilePhoto; userProfilePhoto#82d1f706 flags:# has_video:flags.0?true personal:flags.2?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto; @@ -104,11 +116,11 @@ userStatusLastMonth#65899777 flags:# by_me:flags.0?true = UserStatus; chatEmpty#29562865 id:long = Chat; chat#41cbf256 flags:# creator:flags.0?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat; chatForbidden#6592a1a7 id:long title:string = Chat; -channel#fe4478bd flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true join_to_send:flags.28?true join_request:flags.29?true forum:flags.30?true flags2:# stories_hidden:flags2.1?true stories_hidden_min:flags2.2?true stories_unavailable:flags2.3?true signature_profiles:flags2.12?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int usernames:flags2.0?Vector stories_max_id:flags2.4?int color:flags2.7?PeerColor profile_color:flags2.8?PeerColor emoji_status:flags2.9?EmojiStatus level:flags2.10?int subscription_until_date:flags2.11?int = Chat; +channel#e00998b7 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true join_to_send:flags.28?true join_request:flags.29?true forum:flags.30?true flags2:# stories_hidden:flags2.1?true stories_hidden_min:flags2.2?true stories_unavailable:flags2.3?true signature_profiles:flags2.12?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int usernames:flags2.0?Vector stories_max_id:flags2.4?int color:flags2.7?PeerColor profile_color:flags2.8?PeerColor emoji_status:flags2.9?EmojiStatus level:flags2.10?int subscription_until_date:flags2.11?int bot_verification_icon:flags2.13?long = Chat; channelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat; chatFull#2633421b flags:# can_set_username:flags.7?true has_scheduled:flags.8?true translations_disabled:flags.19?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?ChatReactions reactions_limit:flags.20?int = ChatFull; -channelFull#bbab348d flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true flags2:# can_delete_channel:flags2.0?true antispam:flags2.1?true participants_hidden:flags2.2?true translations_disabled:flags2.3?true stories_pinned_available:flags2.5?true view_forum_as_messages:flags2.6?true restricted_sponsored:flags2.11?true can_view_revenue:flags2.12?true paid_media_allowed:flags2.14?true can_view_stars_revenue:flags2.15?true paid_reactions_available:flags2.16?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?ChatReactions reactions_limit:flags2.13?int stories:flags2.4?PeerStories wallpaper:flags2.7?WallPaper boosts_applied:flags2.8?int boosts_unrestrict:flags2.9?int emojiset:flags2.10?StickerSet = ChatFull; +channelFull#9ff3b858 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true flags2:# can_delete_channel:flags2.0?true antispam:flags2.1?true participants_hidden:flags2.2?true translations_disabled:flags2.3?true stories_pinned_available:flags2.5?true view_forum_as_messages:flags2.6?true restricted_sponsored:flags2.11?true can_view_revenue:flags2.12?true paid_media_allowed:flags2.14?true can_view_stars_revenue:flags2.15?true paid_reactions_available:flags2.16?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?ChatReactions reactions_limit:flags2.13?int stories:flags2.4?PeerStories wallpaper:flags2.7?WallPaper boosts_applied:flags2.8?int boosts_unrestrict:flags2.9?int emojiset:flags2.10?StickerSet bot_verification:flags2.17?BotVerification = ChatFull; chatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant; chatParticipantCreator#e46bcee4 user_id:long = ChatParticipant; @@ -121,8 +133,8 @@ chatPhotoEmpty#37c1011c = ChatPhoto; chatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto; messageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message; -message#94345242 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true invert_media:flags.27?true flags2:# offline:flags2.1?true video_processing_pending:flags2.4?true id:int from_id:flags.8?Peer from_boosts_applied:flags.29?int peer_id:Peer saved_peer_id:flags.28?Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long via_business_bot_id:flags2.0?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int quick_reply_shortcut_id:flags.30?int effect:flags2.2?long factcheck:flags2.3?FactCheck = Message; -messageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message; +message#96fdbbe9 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true invert_media:flags.27?true flags2:# offline:flags2.1?true video_processing_pending:flags2.4?true id:int from_id:flags.8?Peer from_boosts_applied:flags.29?int peer_id:Peer saved_peer_id:flags.28?Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long via_business_bot_id:flags2.0?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int quick_reply_shortcut_id:flags.30?int effect:flags2.2?long factcheck:flags2.3?FactCheck report_delivery_until_date:flags2.5?int = Message; +messageService#d3d28540 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true reactions_are_possible:flags.9?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction reactions:flags.20?MessageReactions ttl_period:flags.25?int = Message; messageMediaEmpty#3ded6320 = MessageMedia; messageMediaPhoto#695150d7 flags:# spoiler:flags.3?true photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia; @@ -188,7 +200,8 @@ messageActionRequestedPeerSentMe#93b31848 button_id:int peers:Vector wallpaper:flags.24?WallPaper stories:flags.25?PeerStories business_work_hours:flags2.0?BusinessWorkHours business_location:flags2.1?BusinessLocation business_greeting_message:flags2.2?BusinessGreetingMessage business_away_message:flags2.3?BusinessAwayMessage business_intro:flags2.4?BusinessIntro birthday:flags2.5?Birthday personal_channel_id:flags2.6?long personal_channel_message:flags2.6?int stargifts_count:flags2.8?int = UserFull; +userFull#4d975bbc flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true voice_messages_forbidden:flags.20?true translations_disabled:flags.23?true stories_pinned_available:flags.26?true blocked_my_stories_from:flags.27?true wallpaper_overridden:flags.28?true contact_require_premium:flags.29?true read_dates_private:flags.30?true flags2:# sponsored_enabled:flags2.7?true can_view_revenue:flags2.9?true bot_can_manage_emoji_status:flags2.10?true id:long about:flags.1?string settings:PeerSettings personal_photo:flags.21?Photo profile_photo:flags.2?Photo fallback_photo:flags.22?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string bot_group_admin_rights:flags.17?ChatAdminRights bot_broadcast_admin_rights:flags.18?ChatAdminRights premium_gifts:flags.19?Vector wallpaper:flags.24?WallPaper stories:flags.25?PeerStories business_work_hours:flags2.0?BusinessWorkHours business_location:flags2.1?BusinessLocation business_greeting_message:flags2.2?BusinessGreetingMessage business_away_message:flags2.3?BusinessAwayMessage business_intro:flags2.4?BusinessIntro birthday:flags2.5?Birthday personal_channel_id:flags2.6?long personal_channel_message:flags2.6?int stargifts_count:flags2.8?int starref_program:flags2.11?StarRefProgram bot_verification:flags2.12?BotVerification = UserFull; contact#145ade0b user_id:long mutual:Bool = Contact; @@ -376,7 +389,7 @@ updatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vec updatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update; updateChat#f89a6a4e chat_id:long = Update; updateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update; -updateGroupCall#14b24500 chat_id:long call:GroupCall = Update; +updateGroupCall#97d64341 flags:# chat_id:flags.0?long call:GroupCall = Update; updatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update; updateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update; updateChannelParticipant#985d3abb flags:# via_chatlist:flags.3?true channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update; @@ -426,7 +439,7 @@ updateBotEditBusinessMessage#7df587c flags:# connection_id:string message:Messag updateBotDeleteBusinessMessage#a02a982e connection_id:string peer:Peer messages:Vector qts:int = Update; updateNewStoryReaction#1824e40b story_id:int peer:Peer reaction:Reaction = Update; updateBroadcastRevenueTransactions#dfd961f5 peer:Peer balances:BroadcastRevenueBalances = Update; -updateStarsBalance#fb85198 balance:long = Update; +updateStarsBalance#4e80a379 balance:StarsAmount = Update; updateBusinessBotCallbackQuery#1ea2fda7 flags:# query_id:long user_id:long connection_id:string message:Message reply_to_message:flags.2?Message chat_instance:long data:flags.0?bytes = Update; updateStarsRevenueStatus#a584b019 peer:Peer status:StarsRevenueStatus = Update; updateBotPurchasedPaidMedia#283bd312 user_id:long payload:string qts:int = Update; @@ -624,7 +637,7 @@ chatInviteExported#a22cbd96 flags:# revoked:flags.0?true permanent:flags.5?true chatInvitePublicJoinRequests#ed107ab7 = ExportedChatInvite; chatInviteAlready#5a686d7c chat:Chat = ChatInvite; -chatInvite#fe65389d flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true verified:flags.7?true scam:flags.8?true fake:flags.9?true can_refulfill_subscription:flags.11?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector color:int subscription_pricing:flags.10?StarsSubscriptionPricing subscription_form_id:flags.12?long = ChatInvite; +chatInvite#5c9d3702 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true verified:flags.7?true scam:flags.8?true fake:flags.9?true can_refulfill_subscription:flags.11?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector color:int subscription_pricing:flags.10?StarsSubscriptionPricing subscription_form_id:flags.12?long bot_verification:flags.13?BotVerification = ChatInvite; chatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite; inputStickerSetEmpty#ffb62b95 = InputStickerSet; @@ -646,7 +659,7 @@ messages.stickerSetNotModified#d3f924eb = messages.StickerSet; botCommand#c27ac8c7 command:string description:string = BotCommand; -botInfo#36607333 flags:# has_preview_medias:flags.6?true user_id:flags.0?long description:flags.1?string description_photo:flags.4?Photo description_document:flags.5?Document commands:flags.2?Vector menu_button:flags.3?BotMenuButton privacy_policy_url:flags.7?string app_settings:flags.8?BotAppSettings = BotInfo; +botInfo#4d8a0299 flags:# has_preview_medias:flags.6?true user_id:flags.0?long description:flags.1?string description_photo:flags.4?Photo description_document:flags.5?Document commands:flags.2?Vector menu_button:flags.3?BotMenuButton privacy_policy_url:flags.7?string app_settings:flags.8?BotAppSettings verifier_settings:flags.9?BotVerifierSettings = BotInfo; keyboardButton#a2fa4880 text:string = KeyboardButton; keyboardButtonUrl#258aff05 text:string url:string = KeyboardButton; @@ -899,6 +912,7 @@ phoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason; phoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason; phoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason; phoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason; +phoneCallDiscardReasonAllowGroupCall#afe2b839 encrypted_key:bytes = PhoneCallDiscardReason; dataJSON#7d748d04 data:string = DataJSON; @@ -953,11 +967,11 @@ inputStickerSetItem#32da9e9c flags:# document:InputDocument emoji:string mask_co inputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall; phoneCallEmpty#5366c915 id:long = PhoneCall; -phoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall; -phoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall; -phoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall; -phoneCall#30535af5 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int custom_parameters:flags.7?DataJSON = PhoneCall; -phoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall; +phoneCallWaiting#eed42858 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int conference_call:flags.8?InputGroupCall = PhoneCall; +phoneCallRequested#45361c63 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol conference_call:flags.8?InputGroupCall = PhoneCall; +phoneCallAccepted#22fd7181 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol conference_call:flags.8?InputGroupCall = PhoneCall; +phoneCall#3ba5940c flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int custom_parameters:flags.7?DataJSON conference_call:flags.8?InputGroupCall = PhoneCall; +phoneCallDiscarded#f9d25503 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int conference_call:flags.8?InputGroupCall = PhoneCall; phoneConnection#9cc123c7 flags:# tcp:flags.0?true id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection; phoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection; @@ -1278,9 +1292,9 @@ bankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl; payments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData; -dialogFilter#5fb5523b flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string color:flags.27?int pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter; +dialogFilter#aa472651 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true title_noanimate:flags.28?true id:int title:TextWithEntities emoticon:flags.25?string color:flags.27?int pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter; dialogFilterDefault#363293ae = DialogFilter; -dialogFilterChatlist#9fe28ea4 flags:# has_my_invites:flags.26?true id:int title:string emoticon:flags.25?string color:flags.27?int pinned_peers:Vector include_peers:Vector = DialogFilter; +dialogFilterChatlist#96537bd7 flags:# has_my_invites:flags.26?true title_noanimate:flags.28?true id:int title:TextWithEntities emoticon:flags.25?string color:flags.27?int pinned_peers:Vector include_peers:Vector = DialogFilter; dialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested; @@ -1336,7 +1350,7 @@ peerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked; stats.messageStats#7fe91c14 views_graph:StatsGraph reactions_by_emotion_graph:StatsGraph = stats.MessageStats; groupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall; -groupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall; +groupCall#cdf8d3e3 flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int conference_from_call:flags.14?long = GroupCall; inputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall; @@ -1477,7 +1491,9 @@ inputInvoiceSlug#c326caef slug:string = InputInvoice; inputInvoicePremiumGiftCode#98986c0d purpose:InputStorePaymentPurpose option:PremiumGiftCodeOption = InputInvoice; inputInvoiceStars#65f00ce3 purpose:InputStorePaymentPurpose = InputInvoice; inputInvoiceChatInviteSubscription#34e793f1 hash:string = InputInvoice; -inputInvoiceStarGift#25d8c1d8 flags:# hide_name:flags.0?true user_id:InputUser gift_id:long message:flags.1?TextWithEntities = InputInvoice; +inputInvoiceStarGift#25d8c1d8 flags:# hide_name:flags.0?true include_upgrade:flags.2?true user_id:InputUser gift_id:long message:flags.1?TextWithEntities = InputInvoice; +inputInvoiceStarGiftUpgrade#5ebe7262 flags:# keep_original_details:flags.0?true msg_id:int = InputInvoice; +inputInvoiceStarGiftTransfer#ae3ba9ed msg_id:int to_id:InputUser = InputInvoice; payments.exportedInvoice#aed0cbd9 url:string = payments.ExportedInvoice; @@ -1595,7 +1611,7 @@ chatlists.exportedChatlistInvite#10e6e3a6 filter:DialogFilter invite:ExportedCha chatlists.exportedInvites#10ab6dc7 invites:Vector chats:Vector users:Vector = chatlists.ExportedInvites; chatlists.chatlistInviteAlready#fa87f659 filter_id:int missing_peers:Vector already_peers:Vector chats:Vector users:Vector = chatlists.ChatlistInvite; -chatlists.chatlistInvite#1dcd839d flags:# title:string emoticon:flags.0?string peers:Vector chats:Vector users:Vector = chatlists.ChatlistInvite; +chatlists.chatlistInvite#f10ece2f flags:# title_noanimate:flags.1?true title:TextWithEntities emoticon:flags.0?string peers:Vector chats:Vector users:Vector = chatlists.ChatlistInvite; chatlists.chatlistUpdates#93bd878d missing_peers:Vector chats:Vector users:Vector = chatlists.ChatlistUpdates; @@ -1836,9 +1852,9 @@ starsTransactionPeerAPI#f9677aad = StarsTransactionPeer; starsTopupOption#bd915c0 flags:# extended:flags.1?true stars:long store_product:flags.0?string currency:string amount:long = StarsTopupOption; -starsTransaction#35d4f276 flags:# refund:flags.3?true pending:flags.4?true failed:flags.6?true gift:flags.10?true reaction:flags.11?true id:string stars:long date:int peer:StarsTransactionPeer title:flags.0?string description:flags.1?string photo:flags.2?WebDocument transaction_date:flags.5?int transaction_url:flags.5?string bot_payload:flags.7?bytes msg_id:flags.8?int extended_media:flags.9?Vector subscription_period:flags.12?int giveaway_post_id:flags.13?int stargift:flags.14?StarGift floodskip_number:flags.15?int = StarsTransaction; +starsTransaction#64dfc926 flags:# refund:flags.3?true pending:flags.4?true failed:flags.6?true gift:flags.10?true reaction:flags.11?true stargift_upgrade:flags.18?true id:string stars:StarsAmount date:int peer:StarsTransactionPeer title:flags.0?string description:flags.1?string photo:flags.2?WebDocument transaction_date:flags.5?int transaction_url:flags.5?string bot_payload:flags.7?bytes msg_id:flags.8?int extended_media:flags.9?Vector subscription_period:flags.12?int giveaway_post_id:flags.13?int stargift:flags.14?StarGift floodskip_number:flags.15?int starref_commission_permille:flags.16?int starref_peer:flags.17?Peer starref_amount:flags.17?StarsAmount = StarsTransaction; -payments.starsStatus#bbfa316c flags:# balance:long subscriptions:flags.1?Vector subscriptions_next_offset:flags.2?string subscriptions_missing_balance:flags.4?long history:flags.3?Vector next_offset:flags.0?string chats:Vector users:Vector = payments.StarsStatus; +payments.starsStatus#6c9ce8ed flags:# balance:StarsAmount subscriptions:flags.1?Vector subscriptions_next_offset:flags.2?string subscriptions_missing_balance:flags.4?long history:flags.3?Vector next_offset:flags.0?string chats:Vector users:Vector = payments.StarsStatus; foundStory#e87acbc0 peer:Peer story:StoryItem = FoundStory; @@ -1846,7 +1862,7 @@ stories.foundStories#e2de7737 flags:# count:int stories:Vector next_ geoPointAddress#de4c5d93 flags:# country_iso2:string state:flags.0?string city:flags.1?string street:flags.2?string = GeoPointAddress; -starsRevenueStatus#79342946 flags:# withdrawal_enabled:flags.0?true current_balance:long available_balance:long overall_revenue:long next_withdrawal_at:flags.1?int = StarsRevenueStatus; +starsRevenueStatus#febe5491 flags:# withdrawal_enabled:flags.0?true current_balance:StarsAmount available_balance:StarsAmount overall_revenue:StarsAmount next_withdrawal_at:flags.1?int = StarsRevenueStatus; payments.starsRevenueStats#c92bb73b revenue_graph:StatsGraph status:StarsRevenueStatus usd_rate:double = payments.StarsRevenueStats; @@ -1874,22 +1890,55 @@ starsGiveawayOption#94ce852a flags:# extended:flags.0?true default:flags.1?true starsGiveawayWinnersOption#54236209 flags:# default:flags.0?true users:int per_user_stars:long = StarsGiveawayWinnersOption; -starGift#49c577cd flags:# limited:flags.0?true sold_out:flags.1?true birthday:flags.2?true id:long sticker:Document stars:long availability_remains:flags.0?int availability_total:flags.0?int convert_stars:long first_sale_date:flags.1?int last_sale_date:flags.1?int = StarGift; +starGift#2cc73c8 flags:# limited:flags.0?true sold_out:flags.1?true birthday:flags.2?true id:long sticker:Document stars:long availability_remains:flags.0?int availability_total:flags.0?int convert_stars:long first_sale_date:flags.1?int last_sale_date:flags.1?int upgrade_stars:flags.3?long = StarGift; +starGiftUnique#6a1407cd id:long title:string num:int owner_id:long attributes:Vector availability_issued:int availability_total:int = StarGift; payments.starGiftsNotModified#a388a368 = payments.StarGifts; payments.starGifts#901689ea hash:int gifts:Vector = payments.StarGifts; -userStarGift#eea49a6e flags:# name_hidden:flags.0?true unsaved:flags.5?true from_id:flags.1?long date:int gift:StarGift message:flags.2?TextWithEntities msg_id:flags.3?int convert_stars:flags.4?long = UserStarGift; + +userStarGift#325835e1 flags:# name_hidden:flags.0?true unsaved:flags.5?true refunded:flags.9?true can_upgrade:flags.10?true from_id:flags.1?long date:int gift:StarGift message:flags.2?TextWithEntities msg_id:flags.3?int convert_stars:flags.4?long upgrade_stars:flags.6?long can_export_at:flags.7?int transfer_stars:flags.8?long = UserStarGift; + payments.userStarGifts#6b65b517 flags:# count:int gifts:Vector next_offset:flags.0?string users:Vector = payments.UserStarGifts; messageReportOption#7903e3d9 text:string option:bytes = MessageReportOption; + reportResultChooseOption#f0e4e0b6 title:string options:Vector = ReportResult; reportResultAddComment#6f09ac31 flags:# optional:flags.0?true option:bytes = ReportResult; reportResultReported#8db33c4b = ReportResult; messages.botPreparedInlineMessage#8ecf0511 id:string expire_date:int = messages.BotPreparedInlineMessage; + messages.preparedInlineMessage#ff57708d query_id:long result:BotInlineResult peer_types:Vector cache_time:int users:Vector = messages.PreparedInlineMessage; + botAppSettings#c99b1950 flags:# placeholder_path:flags.0?bytes background_color:flags.1?int background_dark_color:flags.2?int header_color:flags.3?int header_dark_color:flags.4?int = BotAppSettings; +starRefProgram#dd0c66f2 flags:# bot_id:long commission_permille:int duration_months:flags.0?int end_date:flags.1?int daily_revenue_per_user:flags.2?StarsAmount = StarRefProgram; + +connectedBotStarRef#19a13f71 flags:# revoked:flags.1?true url:string date:int bot_id:long commission_permille:int duration_months:flags.0?int participants:long revenue:long = ConnectedBotStarRef; + +payments.connectedStarRefBots#98d5ea1d count:int connected_bots:Vector users:Vector = payments.ConnectedStarRefBots; + +payments.suggestedStarRefBots#b4d5d859 flags:# count:int suggested_bots:Vector users:Vector next_offset:flags.0?string = payments.SuggestedStarRefBots; + +starsAmount#bbb6b4a3 amount:long nanos:int = StarsAmount; + +messages.foundStickersNotModified#6010c534 flags:# next_offset:flags.0?int = messages.FoundStickers; +messages.foundStickers#82c9e290 flags:# next_offset:flags.0?int hash:long stickers:Vector = messages.FoundStickers; + +botVerifierSettings#b0cd6617 flags:# can_modify_custom_description:flags.1?true icon:long company:string custom_description:flags.0?string = BotVerifierSettings; + +botVerification#f93cd45c bot_id:long icon:long description:string = BotVerification; + +starGiftAttributeModel#39d99013 name:string document:Document rarity_permille:int = StarGiftAttribute; +starGiftAttributePattern#13acff19 name:string document:Document rarity_permille:int = StarGiftAttribute; +starGiftAttributeBackdrop#94271762 name:string center_color:int edge_color:int pattern_color:int text_color:int rarity_permille:int = StarGiftAttribute; +starGiftAttributeOriginalDetails#c02c4f4b flags:# sender_id:flags.0?long recipient_id:long date:int message:flags.1?TextWithEntities = StarGiftAttribute; + +payments.starGiftUpgradePreview#167bd90b sample_attributes:Vector = payments.StarGiftUpgradePreview; + +users.users#62d706b8 users:Vector = users.Users; +users.usersSlice#315a4974 count:int users:Vector = users.Users; + ---functions--- invokeAfterMsg#cb9f372d {X:Type} msg_id:long query:!X = X; @@ -2055,7 +2104,7 @@ contacts.block#2e2e8734 flags:# my_stories_from:flags.0?true id:InputPeer = Bool contacts.unblock#b550d328 flags:# my_stories_from:flags.0?true id:InputPeer = Bool; contacts.getBlocked#9a868f80 flags:# my_stories_from:flags.0?true offset:int limit:int = contacts.Blocked; contacts.search#11f812d8 q:string limit:int = contacts.Found; -contacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer; +contacts.resolveUsername#725afbbc flags:# username:string referer:flags.0?string = contacts.ResolvedPeer; contacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true bots_app:flags.16?true offset:int limit:int hash:long = contacts.TopPeers; contacts.resetTopPeerRating#1ae373ac category:TopPeerCategory peer:InputPeer = Bool; contacts.resetSaved#879537f1 = Bool; @@ -2119,7 +2168,7 @@ messages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_par messages.getMessagesViews#5784d3e1 peer:InputPeer id:Vector increment:Bool = messages.MessageViews; messages.editChatAdmin#a85bd1c2 chat_id:long user_id:InputUser is_admin:Bool = Bool; messages.migrateChat#a2875319 chat_id:long = Updates; -messages.searchGlobal#4bc6589a flags:# broadcasts_only:flags.1?true folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages; +messages.searchGlobal#4bc6589a flags:# broadcasts_only:flags.1?true groups_only:flags.2?true users_only:flags.3?true folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages; messages.reorderStickerSets#78337739 flags:# masks:flags.0?true emojis:flags.1?true order:Vector = Bool; messages.getDocumentByHash#b1f2061f sha256:bytes size:long mime_type:string = Document; messages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs; @@ -2295,6 +2344,8 @@ messages.reportSponsoredMessage#1af3dbb8 peer:InputPeer random_id:bytes option:b messages.getSponsoredMessages#9bd2f439 peer:InputPeer = messages.SponsoredMessages; messages.savePreparedInlineMessage#f21f7f2f flags:# result:InputBotInlineResult user_id:InputUser peer_types:flags.0?Vector = messages.BotPreparedInlineMessage; messages.getPreparedInlineMessage#857ebdb8 bot:InputUser id:string = messages.PreparedInlineMessage; +messages.searchStickers#29b1c66a flags:# emojis:flags.0?true q:string emoticon:string lang_code:Vector offset:int limit:int hash:long = messages.FoundStickers; +messages.reportMessagesDelivery#5a6d7395 flags:# push:flags.0?true peer:InputPeer id:Vector = Bool; updates.getState#edd4882a = updates.State; updates.getDifference#19c2f763 flags:# pts:int pts_limit:flags.1?int pts_total_limit:flags.0?int date:int qts:int qts_limit:flags.2?int = updates.Difference; @@ -2429,6 +2480,10 @@ bots.getPreviewMedias#a2a5594d bot:InputUser = Vector; bots.updateUserEmojiStatus#ed9f30c5 user_id:InputUser emoji_status:EmojiStatus = Bool; bots.toggleUserEmojiStatusPermission#6de6392 bot:InputUser enabled:Bool = Bool; bots.checkDownloadFileParams#50077589 bot:InputUser file_name:string url:string = Bool; +bots.getAdminedBots#b0711d83 = Vector; +bots.updateStarRefProgram#778b5ab3 flags:# bot:InputUser commission_permille:int duration_months:flags.0?int = StarRefProgram; +bots.setCustomVerification#8b89dfbd flags:# enabled:flags.1?true bot:flags.0?InputUser peer:InputPeer custom_description:flags.2?string = Bool; +bots.getBotRecommendations#2855be61 flags:# bot:InputUser = users.Users; payments.getPaymentForm#37148dbb flags:# invoice:InputInvoice theme_params:flags.0?DataJSON = payments.PaymentForm; payments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt; @@ -2462,9 +2517,18 @@ payments.fulfillStarsSubscription#cc5bebb3 peer:InputPeer subscription_id:string payments.getStarsGiveawayOptions#bd1efd3e = Vector; payments.getStarGifts#c4563590 hash:int = payments.StarGifts; payments.getUserStarGifts#5e72c7e1 user_id:InputUser offset:string limit:int = payments.UserStarGifts; -payments.saveStarGift#87acf08e flags:# unsave:flags.0?true user_id:InputUser msg_id:int = Bool; -payments.convertStarGift#421e027 user_id:InputUser msg_id:int = Bool; -payments.botCancelStarsSubscription#57f9ece6 flags:# restore:flags.0?true user_id:InputUser invoice_slug:flags.1?string charge_id:flags.2?string = Bool; +payments.saveStarGift#92fd2aae flags:# unsave:flags.0?true msg_id:int = Bool; +payments.convertStarGift#72770c83 msg_id:int = Bool; +payments.botCancelStarsSubscription#6dfa0622 flags:# restore:flags.0?true user_id:InputUser charge_id:string = Bool; +payments.getConnectedStarRefBots#5869a553 flags:# peer:InputPeer offset_date:flags.2?int offset_link:flags.2?string limit:int = payments.ConnectedStarRefBots; +payments.getConnectedStarRefBot#b7d998f0 peer:InputPeer bot:InputUser = payments.ConnectedStarRefBots; +payments.getSuggestedStarRefBots#d6b48f7 flags:# order_by_revenue:flags.0?true order_by_date:flags.1?true peer:InputPeer offset:string limit:int = payments.SuggestedStarRefBots; +payments.connectStarRefBot#7ed5348a peer:InputPeer bot:InputUser = payments.ConnectedStarRefBots; +payments.editConnectedStarRefBot#e4fca4a3 flags:# revoked:flags.0?true peer:InputPeer link:string = payments.ConnectedStarRefBots; +payments.getStarGiftUpgradePreview#9c9abcb1 gift_id:long = payments.StarGiftUpgradePreview; +payments.upgradeStarGift#cf4f0781 flags:# keep_original_details:flags.0?true msg_id:int = Updates; +payments.transferStarGift#333fb526 msg_id:int to_id:InputUser = Updates; +payments.getUserStarGift#b502e4a5 msg_id:Vector = payments.UserStarGifts; stickers.createStickerSet#9021ab67 flags:# masks:flags.0?true emojis:flags.5?true text_color:flags.6?true user_id:InputUser title:string short_name:string thumb:flags.2?InputDocument stickers:Vector software:flags.3?string = messages.StickerSet; stickers.removeStickerFromSet#f7760f51 sticker:InputDocument = messages.StickerSet; @@ -2479,7 +2543,7 @@ stickers.deleteStickerSet#87704394 stickerset:InputStickerSet = Bool; stickers.replaceSticker#4696459a sticker:InputDocument new_sticker:InputStickerSetItem = messages.StickerSet; phone.getCallConfig#55451fa9 = DataJSON; -phone.requestCall#42ff96ed flags:# video:flags.0?true user_id:InputUser random_id:int g_a_hash:bytes protocol:PhoneCallProtocol = phone.PhoneCall; +phone.requestCall#a6c4600c flags:# video:flags.0?true user_id:InputUser conference_call:flags.1?InputGroupCall random_id:int g_a_hash:bytes protocol:PhoneCallProtocol = phone.PhoneCall; phone.acceptCall#3bd2b4a0 peer:InputPhoneCall g_b:bytes protocol:PhoneCallProtocol = phone.PhoneCall; phone.confirmCall#2efe1722 peer:InputPhoneCall g_a:bytes key_fingerprint:long protocol:PhoneCallProtocol = phone.PhoneCall; phone.receivedCall#17d54f61 peer:InputPhoneCall = Bool; @@ -2488,7 +2552,7 @@ phone.setCallRating#59ead627 flags:# user_initiative:flags.0?true peer:InputPhon phone.saveCallDebug#277add7e peer:InputPhoneCall debug:DataJSON = Bool; phone.sendSignalingData#ff7a9383 peer:InputPhoneCall data:bytes = Bool; phone.createGroupCall#48cdc6d8 flags:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates; -phone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates; +phone.joinGroupCall#d61e1df3 flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string key_fingerprint:flags.3?long params:DataJSON = Updates; phone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates; phone.inviteToGroupCall#7b393160 call:InputGroupCall users:Vector = Updates; phone.discardGroupCall#7a777135 call:InputGroupCall = Updates; @@ -2509,6 +2573,7 @@ phone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates; phone.getGroupCallStreamChannels#1ab21940 call:InputGroupCall = phone.GroupCallStreamChannels; phone.getGroupCallStreamRtmpUrl#deb3abbf peer:InputPeer revoke:Bool = phone.GroupCallStreamRtmpUrl; phone.saveCallLog#41248786 peer:InputPhoneCall file:InputFile = Bool; +phone.createConferenceCall#dfc909ab peer:InputPhoneCall key_fingerprint:long = phone.PhoneCall; langpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference; langpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector; @@ -2584,4 +2649,12 @@ smsjobs.finishJob#4f1ebf24 flags:# job_id:string error:flags.0?string = Bool; fragment.getCollectibleInfo#be1e85ba collectible:InputCollectible = fragment.CollectibleInfo; -// LAYER 194 \ No newline at end of file +// test.useError = Error; +// test.useConfigSimple = help.ConfigSimple; +// test.parseInputAppEvent = InputAppEvent; + +// invokeWithBusinessConnectionPrefix#dd289f8e connection_id:string = Error; +// invokeWithGooglePlayIntegrityPrefix#1df92984 nonce:string token:string = Error; +// invokeWithApnsSecretPrefix#0dae54f8 nonce:string secret:string = Error; + +// LAYER 196 \ No newline at end of file diff --git a/compiler/docs/compiler.py b/compiler/docs/compiler.py index 6f73096d..7af8d45e 100644 --- a/compiler/docs/compiler.py +++ b/compiler/docs/compiler.py @@ -59,7 +59,8 @@ def build(path, level=0) -> None: full_name = f"{(namespace + '.') if namespace else ''}{name}" Path(DESTINATION, full_path).parent.mkdir( - parents=True, exist_ok=True + parents=True, + exist_ok=True, ) with Path(DESTINATION, full_path).open("w", encoding="utf-8") as f: @@ -68,9 +69,9 @@ def build(path, level=0) -> None: title=full_name, title_markup="=" * len(full_name), full_class_path="pyrogram.raw.{}".format( - ".".join(full_path.split("/")[:-1]) + "." + name + ".".join(full_path.split("/")[:-1]) + "." + name, ), - ) + ), ) if last not in all_entities: @@ -106,7 +107,7 @@ def build(path, level=0) -> None: title_markup="=" * len(k), module=module, entities="\n ".join(entities), - ) + ), ) f.write("\n") @@ -746,6 +747,9 @@ def get_title_list(s: str) -> list: Message.react Message.wait_for_click Message.pay + """, + "usergift": """ + UserGift UserGift.toggle """, "chat": """ @@ -854,8 +858,8 @@ def get_title_list(s: str) -> list: { f"{k}_hlist": "\n ".join( f"- :meth:`~{bm}`" for bm in bound_methods - ) - } + ), + }, ) fmt_keys.update( @@ -863,8 +867,8 @@ def get_title_list(s: str) -> list: f"{k}_toctree": "\n ".join( "{} <{}>".format(bm.split(".")[1], bm) for bm in bound_methods - ) - } + ), + }, ) for bm in bound_methods: diff --git a/compiler/docs/template/bound-methods.rst b/compiler/docs/template/bound-methods.rst index 9a2c61a8..3daa629c 100644 --- a/compiler/docs/template/bound-methods.rst +++ b/compiler/docs/template/bound-methods.rst @@ -36,6 +36,19 @@ Message {message_toctree} +UserGift +-------- + +.. hlist:: + :columns: 1 + + {usergift_hlist} + +.. toctree:: + :hidden: + + {usergift_toctree} + Story ----- diff --git a/compiler/errors/compiler.py b/compiler/errors/compiler.py index 0683b11c..11bb7b31 100644 --- a/compiler/errors/compiler.py +++ b/compiler/errors/compiler.py @@ -42,7 +42,8 @@ def start() -> None: with ( Path(HOME, "source", i).open(encoding="utf-8") as f_csv, Path(DEST, f"{name.lower()}_{code}.py").open( - "w", encoding="utf-8" + "w", + encoding="utf-8", ) as f_class, ): reader = csv.reader(f_csv, delimiter="\t") @@ -52,7 +53,7 @@ def start() -> None: [ str(i.capitalize()) for i in re.sub(r"_", " ", name).lower().split(" ") - ] + ], ) sub_classes = [] @@ -79,12 +80,12 @@ def start() -> None: sub_classes.append((sub_class, error_id, error_message)) with Path(HOME, "template/class.txt").open( - encoding="utf-8" + encoding="utf-8", ) as f_class_template: class_template = f_class_template.read() with Path(HOME, "template/sub_class.txt").open( - encoding="utf-8" + encoding="utf-8", ) as f_sub_class_template: sub_class_template = f_sub_class_template.read() @@ -101,7 +102,7 @@ def start() -> None: docstring=f'"""{k[2]}"""', ) for k in sub_classes - ] + ], ), ) diff --git a/compiler/errors/sort.py b/compiler/errors/sort.py index f864d566..8ca2db46 100644 --- a/compiler/errors/sort.py +++ b/compiler/errors/sort.py @@ -63,5 +63,5 @@ for p in Path("source/").glob(f"{h}*.tsv"): with p.open("w") as f: f.write("id\tmessage\n") - for i, item in enumerate(keys, start=1): + for _i, item in enumerate(keys, start=1): f.write(f"{item}\t{dct[item]}\n") diff --git a/pyproject.toml b/pyproject.toml index cb5dfc82..259a0f78 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,24 +67,6 @@ packages = [ "pyrogram" ] -[tool.rye] -managed = true -dev-dependencies = [ - "ruff", - "pytest", - "pytest-asyncio", - "pytest-cov", - "twine", - "pre-commit", -] - -[tool.rye.scripts] -clean = { chain = ["clean:api"] } -"clean:api" = { cmd = "rm -rf pyrogram/errors/exceptions pyrogram/raw/all.py pyrogram/raw/base pyrogram/raw/functions pyrogram/raw/types" } -api = { chain = ["api:raw", "api:errors"] } -"api:raw" = { call = "compiler.api.compiler:start" } -"api:errors" = { call = "compiler.errors.compiler:start" } - [tool.ruff] fix = true unsafe-fixes = true @@ -94,27 +76,36 @@ target-version = "py310" [tool.ruff.lint.isort] required-imports = ["from __future__ import annotations"] +[tool.ruff.lint.mccabe] +max-complexity = 50 + [tool.ruff.lint] select = [ - "FURB", # refurb - "I", # isort "E", # pycodestyle: error - "W", # pycodestyle: warning - "UP", # pyupgrade "F", # pyflakes - "SIM", # flake8-simplify - "RET", # flake8-return + "I", # isort + "W", # pycodestyle: warning + "B", # flake8-bugbear + "G", # flake8-logging-format + "N", # pep8-naming "C4", # flake8-comprehensions + "UP", # pyupgrade + "FA", # flake8-future-annotations + "PL", # pylint + "PIE", # flake8-pie + "PYI", # flake8-pyi "PTH", # flake8-use-pathlib - "PERF", # perflint - "N", # pep8-naming + "RET", # flake8-return "RUF", # ruff - "G", # flake8-logging-format - "TID", # flake8-tidy-imports + "SIM", # flake8-simplify "TCH", # flake8-type-checking - "FA", # flake8-future-annotations - "PL", # pylint + "TID", # flake8-tidy-imports "ARG", # flake8-unused-arguments + "C90", # mccabe + "COM", # flake8-commas + "FURB", # refurb + "PERF", # perflint + "ASYNC", # flake8-async ] ignore = [ diff --git a/pyrogram/__init__.py b/pyrogram/__init__.py index 2a644fdc..4375f68b 100644 --- a/pyrogram/__init__.py +++ b/pyrogram/__init__.py @@ -1,6 +1,6 @@ from __future__ import annotations -__version__ = "v0.1.194" +__version__ = "v0.2.196" __license__ = "MIT License" from concurrent.futures.thread import ThreadPoolExecutor diff --git a/pyrogram/client.py b/pyrogram/client.py index a4dec6a3..ff4c77ec 100644 --- a/pyrogram/client.py +++ b/pyrogram/client.py @@ -217,7 +217,7 @@ class Client(Methods): PARENT_DIR = Path(sys.argv[0]).parent INVITE_LINK_RE = re.compile( - r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/(?:joinchat/|\+))([\w-]+)$" + r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/(?:joinchat/|\+))([\w-]+)$", ) WORKERS = min(64, (os.cpu_count() or 0) + 4) WORKDIR = PARENT_DIR @@ -305,14 +305,17 @@ def __init__( self.protocol_factory = protocol_factory self.executor = ThreadPoolExecutor( - self.workers, thread_name_prefix="Handler" + self.workers, + thread_name_prefix="Handler", ) if storage: self.storage = storage elif self.session_string: self.storage = MemoryStorage( - self.name, self.session_string, self.is_telethon_string + self.name, + self.session_string, + self.is_telethon_string, ) elif self.in_memory: self.storage = MemoryStorage(self.name) @@ -325,10 +328,10 @@ def __init__( self.media_sessions = {} self.media_sessions_lock = asyncio.Lock() self.save_file_semaphore = asyncio.Semaphore( - self.max_concurrent_transmissions + self.max_concurrent_transmissions, ) self.get_file_semaphore = asyncio.Semaphore( - self.max_concurrent_transmissions + self.max_concurrent_transmissions, ) self.is_connected = None self.is_initialized = None @@ -372,7 +375,7 @@ async def updates_watchdog(self) -> None: break if datetime.now() - self.last_update_time > timedelta( - seconds=self.UPDATES_WATCHDOG_INTERVAL + seconds=self.UPDATES_WATCHDOG_INTERVAL, ): await self.invoke(raw.functions.updates.GetState()) @@ -383,7 +386,7 @@ async def authorize(self) -> User: print(f"Welcome to Pyrogram (version {__version__})") print( f"Pyrogram is free software and comes with ABSOLUTELY NO WARRANTY. Licensed\n" - f"under the terms of the {__license__}.\n" + f"under the terms of the {__license__}.\n", ) while True: @@ -425,7 +428,7 @@ async def authorize(self) -> User: } print( - f"The confirmation code has been sent via {sent_code_descriptions[sent_code.type]}" + f"The confirmation code has been sent via {sent_code_descriptions[sent_code.type]}", ) while True: @@ -434,7 +437,9 @@ async def authorize(self) -> User: try: signed_in = await self.sign_in( - self.phone_number, sent_code.phone_code_hash, self.phone_code + self.phone_number, + sent_code.phone_code_hash, + self.phone_code, ) except BadRequest as e: print(e.MESSAGE) @@ -454,23 +459,23 @@ async def authorize(self) -> User: try: if not self.password: confirm = await ainput( - "Confirm password recovery (y/n): " + "Confirm password recovery (y/n): ", ) if confirm == "y": email_pattern = await self.send_recovery_code() print( - f"The recovery code has been sent to {email_pattern}" + f"The recovery code has been sent to {email_pattern}", ) while True: recovery_code = await ainput( - "Enter recovery code: " + "Enter recovery code: ", ) try: return await self.recover_password( - recovery_code + recovery_code, ) except BadRequest as e: print(e.MESSAGE) @@ -551,7 +556,8 @@ def set_parse_mode(self, parse_mode: enums.ParseMode | None) -> None: self.parse_mode = parse_mode async def fetch_peers( - self, peers: list[raw.types.User | raw.types.Chat | raw.types.Channel] + self, + peers: list[raw.types.User | raw.types.Chat | raw.types.Channel], ) -> bool: is_min = False parsed_peers = [] @@ -608,7 +614,7 @@ async def fetch_peers( continue parsed_peers.append( - (peer_id, access_hash, peer_type, username, phone_number) + (peer_id, access_hash, peer_type, username, phone_number), ) await self.storage.update_peers(parsed_peers) @@ -624,7 +630,7 @@ async def handle_updates(self, updates) -> None: ( await self.fetch_peers(updates.users), await self.fetch_peers(updates.chats), - ) + ), ) users = {u.id: u for u in updates.users} @@ -648,7 +654,7 @@ async def handle_updates(self, updates) -> None: None, updates.date, updates.seq, - ) + ), ) if isinstance(update, raw.types.UpdateChannelTooLong): @@ -662,26 +668,27 @@ async def handle_updates(self, updates) -> None: diff = await self.invoke( raw.functions.updates.GetChannelDifference( channel=await self.resolve_peer( - utils.get_channel_id(channel_id) + utils.get_channel_id(channel_id), ), filter=raw.types.ChannelMessagesFilter( ranges=[ raw.types.MessageRange( min_id=update.message.id, max_id=update.message.id, - ) - ] + ), + ], ), pts=pts - pts_count, limit=pts, - ) + ), ) except ChannelPrivate: pass else: if ( not isinstance( - diff, raw.types.updates.ChannelDifferenceEmpty + diff, + raw.types.updates.ChannelDifferenceEmpty, ) and diff ): @@ -690,17 +697,20 @@ async def handle_updates(self, updates) -> None: self.dispatcher.updates_queue.put_nowait((update, users, chats)) elif isinstance( - updates, raw.types.UpdateShortMessage | raw.types.UpdateShortChatMessage + updates, + raw.types.UpdateShortMessage | raw.types.UpdateShortChatMessage, ): if not self.skip_updates: await self.storage.update_state( - (0, updates.pts, None, updates.date, None) + (0, updates.pts, None, updates.date, None), ) diff = await self.invoke( raw.functions.updates.GetDifference( - pts=updates.pts - updates.pts_count, date=updates.date, qts=-1 - ) + pts=updates.pts - updates.pts_count, + date=updates.date, + qts=-1, + ), ) if diff.new_messages: @@ -713,11 +723,11 @@ async def handle_updates(self, updates) -> None: ), {u.id: u for u in diff.users}, {c.id: c for c in diff.chats}, - ) + ), ) elif diff.other_updates: # The other_updates list can be empty self.dispatcher.updates_queue.put_nowait( - (diff.other_updates[0], {}, {}) + (diff.other_updates[0], {}, {}), ) elif isinstance(updates, raw.types.UpdateShort): self.dispatcher.updates_queue.put_nowait((updates.update, {}, {})) @@ -733,13 +743,13 @@ async def load_session(self) -> None: await self.storage.auth_key() is None, await self.storage.user_id() is None, await self.storage.is_bot() is None, - ] + ], ) if session_empty: if not self.api_id or not self.api_hash: raise AttributeError( - "The API key is required for new authorizations." + "The API key is required for new authorizations.", ) await self.storage.api_id(self.api_id) @@ -750,8 +760,10 @@ async def load_session(self) -> None: await self.storage.test_mode(self.test_mode) await self.storage.auth_key( await Auth( - self, await self.storage.dc_id(), await self.storage.test_mode() - ).create() + self, + await self.storage.dc_id(), + await self.storage.test_mode(), + ).create(), ) await self.storage.user_id(None) await self.storage.is_bot(None) @@ -762,7 +774,7 @@ async def load_session(self) -> None: while True: try: value = int( - await ainput("Enter the api_id part of the API key: ") + await ainput("Enter the api_id part of the API key: "), ) if value <= 0: @@ -808,7 +820,8 @@ def load_plugins(self) -> None: try: for handler, group in getattr(module, name).handlers: if isinstance(handler, Handler) and isinstance( - group, int + group, + int, ): self.add_handler(handler, group) @@ -855,7 +868,8 @@ def load_plugins(self) -> None: try: for handler, group in getattr(module, name).handlers: if isinstance(handler, Handler) and isinstance( - group, int + group, + int, ): self.add_handler(handler, group) @@ -909,7 +923,8 @@ def load_plugins(self) -> None: try: for handler, group in getattr(module, name).handlers: if isinstance(handler, Handler) and isinstance( - group, int + group, + int, ): self.remove_handler(handler, group) @@ -962,11 +977,16 @@ async def handle_download(self, packet) -> str: .as_posix() + ".temp" ) - file = BytesIO() if in_memory else Path(temp_file_path).open("wb") + file = BytesIO() if in_memory else Path(temp_file_path).open("wb") # noqa: ASYNC230 try: async for chunk in self.get_file( - file_id, file_size, 0, 0, progress, progress_args + file_id, + file_size, + 0, + 0, + progress, + progress_args, ): file.write(chunk) except BaseException as e: @@ -1005,7 +1025,8 @@ async def get_file( if file_type == FileType.CHAT_PHOTO: if file_id.chat_id > 0: peer = raw.types.InputPeerUser( - user_id=file_id.chat_id, access_hash=file_id.chat_access_hash + user_id=file_id.chat_id, + access_hash=file_id.chat_access_hash, ) elif file_id.chat_access_hash == 0: peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id) @@ -1059,18 +1080,21 @@ async def get_file( if dc_id != await self.storage.dc_id(): exported_auth = await self.invoke( - raw.functions.auth.ExportAuthorization(dc_id=dc_id) + raw.functions.auth.ExportAuthorization(dc_id=dc_id), ) await session.invoke( raw.functions.auth.ImportAuthorization( - id=exported_auth.id, bytes=exported_auth.bytes - ) + id=exported_auth.id, + bytes=exported_auth.bytes, + ), ) r = await session.invoke( raw.functions.upload.GetFile( - location=location, offset=offset_bytes, limit=chunk_size + location=location, + offset=offset_bytes, + limit=chunk_size, ), sleep_threshold=30, ) @@ -1118,7 +1142,9 @@ async def get_file( self, r.dc_id, await Auth( - self, r.dc_id, await self.storage.test_mode() + self, + r.dc_id, + await self.storage.test_mode(), ).create(), await self.storage.test_mode(), is_media=True, @@ -1134,18 +1160,19 @@ async def get_file( file_token=r.file_token, offset=offset_bytes, limit=chunk_size, - ) + ), ) if isinstance( - r2, raw.types.upload.CdnFileReuploadNeeded + r2, + raw.types.upload.CdnFileReuploadNeeded, ): try: await session.invoke( raw.functions.upload.ReuploadCdnFile( file_token=r.file_token, request_token=r2.request_token, - ) + ), ) except VolumeLocNotFound: break @@ -1159,14 +1186,15 @@ async def get_file( r.encryption_key, bytearray( r.encryption_iv[:-4] - + (offset_bytes // 16).to_bytes(4, "big") + + (offset_bytes // 16).to_bytes(4, "big"), ), ) hashes = await session.invoke( raw.functions.upload.GetCdnFileHashes( - file_token=r.file_token, offset=offset_bytes - ) + file_token=r.file_token, + offset=offset_bytes, + ), ) for i, h in enumerate(hashes): @@ -1199,7 +1227,8 @@ async def get_file( await func() else: await self.loop.run_in_executor( - self.executor, func + self.executor, + func, ) if len(chunk) < chunk_size or current >= total: @@ -1217,11 +1246,9 @@ async def get_file( finally: await session.stop() - @functools.lru_cache(maxsize=128) def guess_mime_type(self, filename: str) -> str | None: return self.mimetypes.guess_type(filename)[0] - @functools.lru_cache(maxsize=128) def guess_extension(self, mime_type: str) -> str | None: return self.mimetypes.guess_extension(mime_type) diff --git a/pyrogram/connection/connection.py b/pyrogram/connection/connection.py index e8bdd365..bd428f3e 100644 --- a/pyrogram/connection/connection.py +++ b/pyrogram/connection/connection.py @@ -35,7 +35,7 @@ def __init__( self.protocol: TCP | None = None async def connect(self) -> None: - for i in range(Connection.MAX_CONNECTION_ATTEMPTS): + for _i in range(Connection.MAX_CONNECTION_ATTEMPTS): self.protocol = self.protocol_factory(ipv6=self.ipv6, proxy=self.proxy) try: diff --git a/pyrogram/connection/transport/tcp/tcp.py b/pyrogram/connection/transport/tcp/tcp.py index 62a062bd..f65d86ef 100644 --- a/pyrogram/connection/transport/tcp/tcp.py +++ b/pyrogram/connection/transport/tcp/tcp.py @@ -81,7 +81,9 @@ async def _connect_via_direct(self, destination: tuple[str, int]) -> None: host, port = destination family = socket.AF_INET6 if self.ipv6 else socket.AF_INET self.reader, self.writer = await asyncio.open_connection( - host=host, port=port, family=family + host=host, + port=port, + family=family, ) async def _connect(self, destination: tuple[str, int]) -> None: @@ -93,8 +95,8 @@ async def _connect(self, destination: tuple[str, int]) -> None: async def connect(self, address: tuple[str, int]) -> None: try: await asyncio.wait_for(self._connect(address), TCP.TIMEOUT) - except asyncio.TimeoutError: - raise TimeoutError("Connection timed out") + except asyncio.TimeoutError as err: + raise TimeoutError("Connection timed out") from err async def close(self) -> None: if self.writer is None: @@ -116,7 +118,7 @@ async def send(self, data: bytes) -> None: await self.writer.drain() except Exception as e: log.info("Send exception: %s %s", type(e).__name__, e) - raise OSError(e) + raise OSError(e) from e async def recv(self, length: int = 0) -> bytes | None: data = b"" @@ -124,7 +126,8 @@ async def recv(self, length: int = 0) -> bytes | None: while len(data) < length: try: chunk = await asyncio.wait_for( - self.reader.read(length - len(data)), TCP.TIMEOUT + self.reader.read(length - len(data)), + TCP.TIMEOUT, ) except (OSError, asyncio.TimeoutError): return None diff --git a/pyrogram/connection/transport/tcp/tcp_abridged.py b/pyrogram/connection/transport/tcp/tcp_abridged.py index 1387450d..3209236b 100644 --- a/pyrogram/connection/transport/tcp/tcp_abridged.py +++ b/pyrogram/connection/transport/tcp/tcp_abridged.py @@ -25,7 +25,7 @@ async def send(self, data: bytes, *args) -> None: if length <= 126 else b"\x7f" + length.to_bytes(3, "little") ) - + data + + data, ) async def recv(self, length: int = 0) -> bytes | None: diff --git a/pyrogram/connection/transport/tcp/tcp_abridged_o.py b/pyrogram/connection/transport/tcp/tcp_abridged_o.py index abfcb3ae..1354ac9b 100644 --- a/pyrogram/connection/transport/tcp/tcp_abridged_o.py +++ b/pyrogram/connection/transport/tcp/tcp_abridged_o.py @@ -52,7 +52,10 @@ async def send(self, data: bytes, *args) -> None: else b"\x7f" + length.to_bytes(3, "little") ) + data payload = await self.loop.run_in_executor( - pyrogram.crypto_executor, aes.ctr256_encrypt, data, *self.encrypt + pyrogram.crypto_executor, + aes.ctr256_encrypt, + data, + *self.encrypt, ) await super().send(payload) @@ -79,5 +82,8 @@ async def recv(self, length: int = 0) -> bytes | None: return None return await self.loop.run_in_executor( - pyrogram.crypto_executor, aes.ctr256_decrypt, data, *self.decrypt + pyrogram.crypto_executor, + aes.ctr256_decrypt, + data, + *self.decrypt, ) diff --git a/pyrogram/connection/transport/tcp/tcp_intermediate_o.py b/pyrogram/connection/transport/tcp/tcp_intermediate_o.py index cd270eda..89490592 100644 --- a/pyrogram/connection/transport/tcp/tcp_intermediate_o.py +++ b/pyrogram/connection/transport/tcp/tcp_intermediate_o.py @@ -46,7 +46,7 @@ async def connect(self, address: tuple[str, int]) -> None: async def send(self, data: bytes, *args) -> None: await super().send( - aes.ctr256_encrypt(pack(" bytes | None: diff --git a/pyrogram/crypto/mtproto.py b/pyrogram/crypto/mtproto.py index 934e6f88..6556c12c 100644 --- a/pyrogram/crypto/mtproto.py +++ b/pyrogram/crypto/mtproto.py @@ -42,7 +42,10 @@ def pack( def unpack( - b: BytesIO, session_id: bytes, auth_key: bytes, auth_key_id: bytes + b: BytesIO, + session_id: bytes, + auth_key: bytes, + auth_key_id: bytes, ) -> Message: SecurityCheckMismatch.check(b.read(8) == auth_key_id, "b.read(8) == auth_key_id") @@ -52,7 +55,8 @@ def unpack( data.read(8) SecurityCheckMismatch.check( - data.read(8) == session_id, "data.read(8) == session_id" + data.read(8) == session_id, + "data.read(8) == session_id", ) try: @@ -60,8 +64,8 @@ def unpack( except KeyError as e: if e.args[0] == 0: raise ConnectionError( - "Received empty data. Check your internet connection." - ) + "Received empty data. Check your internet connection.", + ) from e left = data.read().hex() @@ -70,8 +74,8 @@ def unpack( left = "\n".join(" ".join(x for x in left) for left in left) raise ValueError( - f"The server sent an unknown constructor: {hex(e.args[0])}\n{left}" - ) + f"The server sent an unknown constructor: {hex(e.args[0])}\n{left}", + ) from e SecurityCheckMismatch.check( msg_key == sha256(auth_key[96 : 96 + 32] + data.getvalue()).digest()[8:24], @@ -82,7 +86,8 @@ def unpack( payload = data.read() padding = payload[message.length :] SecurityCheckMismatch.check( - 12 <= len(padding) <= 1024, "12 <= len(padding) <= 1024" + 12 <= len(padding) <= 1024, + "12 <= len(padding) <= 1024", ) SecurityCheckMismatch.check(len(payload) % 4 == 0, "len(payload) % 4 == 0") diff --git a/pyrogram/crypto/prime.py b/pyrogram/crypto/prime.py index cfc017df..03b8bd41 100644 --- a/pyrogram/crypto/prime.py +++ b/pyrogram/crypto/prime.py @@ -37,7 +37,7 @@ def decompose(pq: int) -> int: while g == 1: x = y - for i in range(r): + for _i in range(r): y = (pow(y, 2, pq) + c) % pq k = 0 @@ -45,7 +45,7 @@ def decompose(pq: int) -> int: while k < r and g == 1: ys = y - for i in range(min(m, r - k)): + for _i in range(min(m, r - k)): y = (pow(y, 2, pq) + c) % pq q = q * (abs(x - y)) % pq diff --git a/pyrogram/crypto/rsa.py b/pyrogram/crypto/rsa.py index 2c22fcbf..265f2a53 100644 --- a/pyrogram/crypto/rsa.py +++ b/pyrogram/crypto/rsa.py @@ -1,8 +1,12 @@ from __future__ import annotations -from collections import namedtuple +from typing import NamedTuple + + +class PublicKey(NamedTuple): + m: int + e: int -PublicKey = namedtuple("PublicKey", ["m", "e"]) server_public_keys = { 0xC3B42B026CE86B21 - (1 << 64): PublicKey( diff --git a/pyrogram/dispatcher.py b/pyrogram/dispatcher.py index ae00a86b..749355f6 100644 --- a/pyrogram/dispatcher.py +++ b/pyrogram/dispatcher.py @@ -166,7 +166,9 @@ async def deleted_bot_business_messages_parser(update, users, chats): async def callback_query_parser(update, users, chats): return ( await pyrogram.types.CallbackQuery._parse( - self.client, update, users + self.client, + update, + users, ), CallbackQueryHandler, ) @@ -198,7 +200,10 @@ async def chosen_inline_result_parser(update, users, chats): async def chat_member_updated_parser(update, users, chats): return ( pyrogram.types.ChatMemberUpdated._parse( - self.client, update, users, chats + self.client, + update, + users, + chats, ), ChatMemberUpdatedHandler, ) @@ -206,7 +211,10 @@ async def chat_member_updated_parser(update, users, chats): async def chat_join_request_parser(update, users, chats): return ( pyrogram.types.ChatJoinRequest._parse( - self.client, update, users, chats + self.client, + update, + users, + chats, ), ChatJoinRequestHandler, ) @@ -214,7 +222,9 @@ async def chat_join_request_parser(update, users, chats): async def story_parser(update, users, chats): return ( await pyrogram.types.Story._parse( - self.client, update.story, update.peer + self.client, + update.story, + update.peer, ), StoryHandler, ) @@ -222,7 +232,9 @@ async def story_parser(update, users, chats): async def shipping_query_parser(update, users, chats): return ( await pyrogram.types.ShippingQuery._parse( - self.client, update, users + self.client, + update, + users, ), ShippingQueryHandler, ) @@ -230,7 +242,9 @@ async def shipping_query_parser(update, users, chats): async def pre_checkout_query_parser(update, users, chats): return ( await pyrogram.types.PreCheckoutQuery._parse( - self.client, update, users + self.client, + update, + users, ), PreCheckoutQueryHandler, ) @@ -238,7 +252,10 @@ async def pre_checkout_query_parser(update, users, chats): async def message_bot_na_reaction_parser(update, users, chats): return ( pyrogram.types.MessageReactionUpdated._parse( - self.client, update, users, chats + self.client, + update, + users, + chats, ), MessageReactionUpdatedHandler, ) @@ -246,7 +263,10 @@ async def message_bot_na_reaction_parser(update, users, chats): async def message_bot_a_reaction_parser(update, users, chats): return ( pyrogram.types.MessageReactionCountUpdated._parse( - self.client, update, users, chats + self.client, + update, + users, + chats, ), MessageReactionCountUpdatedHandler, ) @@ -254,7 +274,8 @@ async def message_bot_a_reaction_parser(update, users, chats): async def bot_business_connect_parser(update, users, chats): return ( await pyrogram.types.BotBusinessConnection._parse( - self.client, update.connection + self.client, + update.connection, ), BotBusinessConnectHandler, ) @@ -289,11 +310,11 @@ async def bot_business_connect_parser(update, users, chats): async def start(self) -> None: if not self.client.no_updates: - for i in range(self.client.workers): + for _i in range(self.client.workers): self.locks_list.append(asyncio.Lock()) self.handler_worker_tasks.append( - self.loop.create_task(self.handler_worker(self.locks_list[-1])) + self.loop.create_task(self.handler_worker(self.locks_list[-1])), ) log.info("Started %s HandlerTasks", self.client.workers) @@ -327,7 +348,7 @@ async def start(self) -> None: pts=local_pts, date=local_date, qts=0, - ) + ), ) except ( errors.ChannelPrivate, @@ -380,7 +401,7 @@ async def start(self) -> None: ), users, chats, - ) + ), ) for update in diff.other_updates: @@ -404,7 +425,7 @@ async def start(self) -> None: async def stop(self) -> None: if not self.client.no_updates: - for i in range(self.client.workers): + for _i in range(self.client.workers): self.updates_queue.put_nowait(None) for i in self.handler_worker_tasks: @@ -440,7 +461,7 @@ async def fn() -> None: try: if group not in self.groups: raise ValueError( - f"Group {group} does not exist. Handler was not removed." + f"Group {group} does not exist. Handler was not removed.", ) self.groups[group].remove(handler) @@ -479,7 +500,8 @@ async def handler_worker(self, lock) -> None: if isinstance(handler, handler_type): try: if await handler.check( - self.client, parsed_update + self.client, + parsed_update, ): args = (parsed_update,) except Exception as e: diff --git a/pyrogram/enums/__init__.py b/pyrogram/enums/__init__.py index 50ec37d2..0c9af143 100644 --- a/pyrogram/enums/__init__.py +++ b/pyrogram/enums/__init__.py @@ -32,10 +32,10 @@ "BusinessSchedule", "ChatAction", "ChatEventAction", + "ChatJoinType", "ChatMemberStatus", "ChatMembersFilter", "ChatType", - "ChatJoinType", "ClientPlatform", "FolderColor", "ListenerTypes", @@ -46,8 +46,8 @@ "NextCodeType", "ParseMode", "PollType", - "ProfileColor", "PrivacyKey", + "ProfileColor", "ReactionType", "ReplyColor", "SentCodeType", diff --git a/pyrogram/errors/__init__.py b/pyrogram/errors/__init__.py index 56829a07..b0375242 100644 --- a/pyrogram/errors/__init__.py +++ b/pyrogram/errors/__init__.py @@ -42,7 +42,7 @@ class SecurityCheckMismatch(SecurityError): def __init__(self, msg: str | None = None) -> None: super().__init__( - "A security check mismatch has occurred." if msg is None else msg + "A security check mismatch has occurred." if msg is None else msg, ) @@ -51,7 +51,7 @@ class CDNFileHashMismatch(SecurityError): def __init__(self, msg: str | None = None) -> None: super().__init__( - "A CDN file hash mismatch has occurred." if msg is None else msg + "A CDN file hash mismatch has occurred." if msg is None else msg, ) diff --git a/pyrogram/errors/rpc_error.py b/pyrogram/errors/rpc_error.py index 1297f554..cbd2f432 100644 --- a/pyrogram/errors/rpc_error.py +++ b/pyrogram/errors/rpc_error.py @@ -33,7 +33,7 @@ def __init__( self.ID or self.NAME, self.MESSAGE.format(value=value), f'(caused by "{rpc_name}")' if rpc_name else "", - ) + ), ) try: @@ -47,7 +47,8 @@ def __init__( @staticmethod def raise_it( - rpc_error: raw.types.RpcError, rpc_type: type[TLObject] + rpc_error: raw.types.RpcError, + rpc_type: type[TLObject], ) -> NoReturn: error_code = rpc_error.error_code is_signed = error_code < 0 diff --git a/pyrogram/file_id.py b/pyrogram/file_id.py index 92421b16..80d44408 100644 --- a/pyrogram/file_id.py +++ b/pyrogram/file_id.py @@ -206,8 +206,10 @@ def decode(file_id: str): try: file_type = FileType(file_type) - except ValueError: - raise ValueError(f"Unknown file_type {file_type} of file_id {file_id}") + except ValueError as e: + raise ValueError( + f"Unknown file_type {file_type} of file_id {file_id}", + ) from e if has_web_location: url = String.read(buffer) @@ -233,10 +235,10 @@ def decode(file_id: str): try: thumbnail_source = ThumbnailSource(thumbnail_source) - except ValueError: + except ValueError as e: raise ValueError( - f"Unknown thumbnail_source {thumbnail_source} of file_id {file_id}" - ) + f"Unknown thumbnail_source {thumbnail_source} of file_id {file_id}", + ) from e if thumbnail_source == ThumbnailSource.LEGACY: secret, local_id = struct.unpack(" bool: async def me_filter(_, __, m: Message): - return bool(m.from_user and m.from_user.is_self or getattr(m, "outgoing", False)) + return bool( + (m.from_user and m.from_user.is_self) or getattr(m, "outgoing", False), + ) me = create(me_filter) @@ -386,7 +403,7 @@ async def media_spoiler_filter(_, __, m: Message): async def private_filter(_, __, m: Message): return bool( - m.chat and m.chat.type in {enums.ChatType.PRIVATE, enums.ChatType.BOT} + m.chat and m.chat.type in {enums.ChatType.PRIVATE, enums.ChatType.BOT}, ) @@ -396,7 +413,7 @@ async def private_filter(_, __, m: Message): async def group_filter(_, __, m: Message): return bool( - m.chat and m.chat.type in {enums.ChatType.GROUP, enums.ChatType.SUPERGROUP} + m.chat and m.chat.type in {enums.ChatType.GROUP, enums.ChatType.SUPERGROUP}, ) diff --git a/pyrogram/handlers/__init__.py b/pyrogram/handlers/__init__.py index e40ea67f..9d866164 100644 --- a/pyrogram/handlers/__init__.py +++ b/pyrogram/handlers/__init__.py @@ -7,23 +7,17 @@ from .chat_member_updated_handler import ChatMemberUpdatedHandler from .chosen_inline_result_handler import ChosenInlineResultHandler from .conversation_handler import ConversationHandler -from .deleted_bot_business_messages_handler import ( - DeletedBotBusinessMessagesHandler, -) +from .deleted_bot_business_messages_handler import DeletedBotBusinessMessagesHandler from .deleted_messages_handler import DeletedMessagesHandler from .disconnect_handler import DisconnectHandler -from .edited_bot_business_message_handler import ( - EditedBotBusinessMessageHandler, -) +from .edited_bot_business_message_handler import EditedBotBusinessMessageHandler from .edited_message_handler import EditedMessageHandler from .inline_query_handler import InlineQueryHandler from .message_handler import MessageHandler from .message_reaction_count_updated_handler import ( MessageReactionCountUpdatedHandler, ) -from .message_reaction_updated_handler import ( - MessageReactionUpdatedHandler, -) +from .message_reaction_updated_handler import MessageReactionUpdatedHandler from .poll_handler import PollHandler from .pre_checkout_query_handler import PreCheckoutQueryHandler from .raw_update_handler import RawUpdateHandler diff --git a/pyrogram/handlers/conversation_handler.py b/pyrogram/handlers/conversation_handler.py index e7645537..51637a89 100644 --- a/pyrogram/handlers/conversation_handler.py +++ b/pyrogram/handlers/conversation_handler.py @@ -49,7 +49,10 @@ async def check( filtered = await filters(client, update) else: filtered = await client.loop.run_in_executor( - client.executor, filters, client, update + client.executor, + filters, + client, + update, ) if not filtered or waiter["future"].done(): return False diff --git a/pyrogram/handlers/handler.py b/pyrogram/handlers/handler.py index 6abfb9c3..d4673a9f 100644 --- a/pyrogram/handlers/handler.py +++ b/pyrogram/handlers/handler.py @@ -21,7 +21,10 @@ async def check(self, client: pyrogram.Client, update: Update): if inspect.iscoroutinefunction(self.filters.__call__): return await self.filters(client, update) return await client.loop.run_in_executor( - client.executor, self.filters, client, update + client.executor, + self.filters, + client, + update, ) return True diff --git a/pyrogram/methods/account/get_privacy.py b/pyrogram/methods/account/get_privacy.py index 10dc7822..396abf27 100644 --- a/pyrogram/methods/account/get_privacy.py +++ b/pyrogram/methods/account/get_privacy.py @@ -6,7 +6,8 @@ class GetPrivacy: async def get_privacy( - self: pyrogram.Client, key: enums.PrivacyKey + self: pyrogram.Client, + key: enums.PrivacyKey, ) -> types.PrivacyRule: """Get account privacy rules. diff --git a/pyrogram/methods/account/set_account_ttl.py b/pyrogram/methods/account/set_account_ttl.py index 35ef3da1..7f4a533e 100644 --- a/pyrogram/methods/account/set_account_ttl.py +++ b/pyrogram/methods/account/set_account_ttl.py @@ -25,6 +25,6 @@ async def set_account_ttl(self: pyrogram.Client, days: int) -> bool: """ return await self.invoke( raw.functions.account.SetAccountTTL( - ttl=raw.types.AccountDaysTTL(days=days) - ) + ttl=raw.types.AccountDaysTTL(days=days), + ), ) diff --git a/pyrogram/methods/account/set_privacy.py b/pyrogram/methods/account/set_privacy.py index 7d98bb2c..b6befc23 100644 --- a/pyrogram/methods/account/set_privacy.py +++ b/pyrogram/methods/account/set_privacy.py @@ -44,8 +44,9 @@ async def set_privacy( """ r = await self.invoke( raw.functions.account.SetPrivacy( - key=key.value(), rules=[await rule.write(self) for rule in rules] - ) + key=key.value(), + rules=[await rule.write(self) for rule in rules], + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/advanced/invoke.py b/pyrogram/methods/advanced/invoke.py index 8dcdc075..9854e3e2 100644 --- a/pyrogram/methods/advanced/invoke.py +++ b/pyrogram/methods/advanced/invoke.py @@ -62,7 +62,8 @@ async def invoke( if self.takeout_id: query = raw.functions.InvokeWithTakeout( - takeout_id=self.takeout_id, query=query + takeout_id=self.takeout_id, + query=query, ) r = await self.session.invoke( diff --git a/pyrogram/methods/advanced/resolve_peer.py b/pyrogram/methods/advanced/resolve_peer.py index b01e7c28..9148d37f 100644 --- a/pyrogram/methods/advanced/resolve_peer.py +++ b/pyrogram/methods/advanced/resolve_peer.py @@ -12,7 +12,8 @@ class ResolvePeer: async def resolve_peer( - self: pyrogram.Client, peer_id: int | str + self: pyrogram.Client, + peer_id: int | str, ) -> raw.base.InputPeer | raw.base.InputUser | raw.base.InputChannel: """Get the InputPeer of a known peer id. Useful whenever an InputPeer type is required. @@ -39,13 +40,12 @@ async def resolve_peer( if not self.is_connected: raise ConnectionError("Client has not been started yet") + if peer_id in ("self", "me"): + return raw.types.InputPeerSelf() try: return await self.storage.get_peer_by_id(peer_id) except KeyError: if isinstance(peer_id, str): - if peer_id in ("self", "me"): - return raw.types.InputPeerSelf() - peer_id = re.sub(r"[@+\s]", "", peer_id.lower()) peer_id = re.sub(r"https://t.me/", "", peer_id.lower()) @@ -56,7 +56,7 @@ async def resolve_peer( return await self.storage.get_peer_by_username(peer_id) except KeyError: await self.invoke( - raw.functions.contacts.ResolveUsername(username=peer_id) + raw.functions.contacts.ResolveUsername(username=peer_id), ) return await self.storage.get_peer_by_username(peer_id) @@ -64,7 +64,7 @@ async def resolve_peer( try: return await self.storage.get_peer_by_phone_number(peer_id) except KeyError: - raise PeerIdInvalid + raise PeerIdInvalid from None peer_type = utils.get_peer_type(peer_id) @@ -72,9 +72,9 @@ async def resolve_peer( await self.fetch_peers( await self.invoke( raw.functions.users.GetUsers( - id=[raw.types.InputUser(user_id=peer_id, access_hash=0)] - ) - ) + id=[raw.types.InputUser(user_id=peer_id, access_hash=0)], + ), + ), ) elif peer_type == "chat": await self.invoke(raw.functions.messages.GetChats(id=[-peer_id])) @@ -85,12 +85,12 @@ async def resolve_peer( raw.types.InputChannel( channel_id=utils.get_channel_id(peer_id), access_hash=0, - ) - ] - ) + ), + ], + ), ) try: return await self.storage.get_peer_by_id(peer_id) except KeyError: - raise PeerIdInvalid + raise PeerIdInvalid from None diff --git a/pyrogram/methods/advanced/save_file.py b/pyrogram/methods/advanced/save_file.py index f6ca20fc..b26e84b8 100644 --- a/pyrogram/methods/advanced/save_file.py +++ b/pyrogram/methods/advanced/save_file.py @@ -81,7 +81,7 @@ async def save_file( if path is None: return None - async def worker(session): + async def worker(session) -> None: while True: data = await queue.get() @@ -104,14 +104,16 @@ def create_rpc(chunk, file_part, is_big, file_id, file_total_parts): bytes=chunk, ) return raw.functions.upload.SaveFilePart( - file_id=file_id, file_part=file_part, bytes=chunk + file_id=file_id, + file_part=file_part, + bytes=chunk, ) part_size = 512 * 1024 queue = asyncio.Queue(32) with ( - Path(path).open("rb", buffering=4096) + Path(path).open("rb", buffering=4096) # noqa: ASYNC230 if isinstance(path, str | PurePath) else path ) as fp: @@ -127,7 +129,7 @@ def create_rpc(chunk, file_part, is_big, file_id, file_total_parts): if file_size > file_size_limit_mib * 1024 * 1024: raise ValueError( - f"Can't upload files bigger than {file_size_limit_mib} MiB" + f"Can't upload files bigger than {file_size_limit_mib} MiB", ) file_total_parts = math.ceil(file_size / part_size) @@ -165,7 +167,7 @@ def create_rpc(chunk, file_part, is_big, file_id, file_total_parts): while True: chunk = await next_chunk_task next_chunk_task = self.loop.create_task( - self.preload(fp, part_size) + self.preload(fp, part_size), ) if not chunk: @@ -175,8 +177,12 @@ def create_rpc(chunk, file_part, is_big, file_id, file_total_parts): await queue.put( create_rpc( - chunk, file_part, is_big, file_id, file_total_parts - ) + chunk, + file_part, + is_big, + file_id, + file_total_parts, + ), ) if is_missing_part: diff --git a/pyrogram/methods/auth/accept_terms_of_service.py b/pyrogram/methods/auth/accept_terms_of_service.py index 152d2dae..1ac2be5e 100644 --- a/pyrogram/methods/auth/accept_terms_of_service.py +++ b/pyrogram/methods/auth/accept_terms_of_service.py @@ -6,7 +6,8 @@ class AcceptTermsOfService: async def accept_terms_of_service( - self: pyrogram.Client, terms_of_service_id: str + self: pyrogram.Client, + terms_of_service_id: str, ) -> bool: """Accept the given terms of service. @@ -18,8 +19,8 @@ async def accept_terms_of_service( """ r = await self.invoke( raw.functions.help.AcceptTermsOfService( - id=raw.types.DataJSON(data=terms_of_service_id) - ) + id=raw.types.DataJSON(data=terms_of_service_id), + ), ) return bool(r) diff --git a/pyrogram/methods/auth/check_password.py b/pyrogram/methods/auth/check_password.py index cf24d063..60129578 100644 --- a/pyrogram/methods/auth/check_password.py +++ b/pyrogram/methods/auth/check_password.py @@ -30,8 +30,8 @@ async def check_password(self: pyrogram.Client, password: str) -> types.User: password=compute_password_check( await self.invoke(raw.functions.account.GetPassword()), password, - ) - ) + ), + ), ) await self.storage.user_id(r.user.id) diff --git a/pyrogram/methods/auth/recover_password.py b/pyrogram/methods/auth/recover_password.py index 1aadeec6..f0e78327 100644 --- a/pyrogram/methods/auth/recover_password.py +++ b/pyrogram/methods/auth/recover_password.py @@ -10,7 +10,8 @@ class RecoverPassword: async def recover_password( - self: pyrogram.Client, recovery_code: str + self: pyrogram.Client, + recovery_code: str, ) -> types.User: """Recover your password with a recovery code and log in. diff --git a/pyrogram/methods/auth/resend_code.py b/pyrogram/methods/auth/resend_code.py index 535c6d09..c09ccde8 100644 --- a/pyrogram/methods/auth/resend_code.py +++ b/pyrogram/methods/auth/resend_code.py @@ -41,7 +41,7 @@ async def resend_code( raw.functions.auth.ResendCode( phone_number=phone_number, phone_code_hash=phone_code_hash, - ) + ), ) return types.SentCode._parse(r) diff --git a/pyrogram/methods/auth/send_code.py b/pyrogram/methods/auth/send_code.py index 677429f9..8719bae6 100644 --- a/pyrogram/methods/auth/send_code.py +++ b/pyrogram/methods/auth/send_code.py @@ -37,7 +37,7 @@ async def send_code(self: pyrogram.Client, phone_number: str) -> types.SentCode: api_id=self.api_id, api_hash=self.api_hash, settings=raw.types.CodeSettings(), - ) + ), ) except (PhoneMigrate, NetworkMigrate) as e: await self.session.stop() @@ -48,7 +48,7 @@ async def send_code(self: pyrogram.Client, phone_number: str) -> types.SentCode: self, await self.storage.dc_id(), await self.storage.test_mode(), - ).create() + ).create(), ) self.session = Session( self, diff --git a/pyrogram/methods/auth/sign_in.py b/pyrogram/methods/auth/sign_in.py index 2f73ddbc..5e1dfe3a 100644 --- a/pyrogram/methods/auth/sign_in.py +++ b/pyrogram/methods/auth/sign_in.py @@ -47,13 +47,13 @@ async def sign_in( phone_number=phone_number, phone_code_hash=phone_code_hash, phone_code=phone_code, - ) + ), ) if isinstance(r, raw.types.auth.AuthorizationSignUpRequired): if r.terms_of_service: return types.TermsOfService._parse( - terms_of_service=r.terms_of_service + terms_of_service=r.terms_of_service, ) return False diff --git a/pyrogram/methods/auth/sign_in_bot.py b/pyrogram/methods/auth/sign_in_bot.py index 991decfe..c791f909 100644 --- a/pyrogram/methods/auth/sign_in_bot.py +++ b/pyrogram/methods/auth/sign_in_bot.py @@ -34,7 +34,7 @@ async def sign_in_bot(self: pyrogram.Client, bot_token: str) -> types.User: api_id=self.api_id, api_hash=self.api_hash, bot_auth_token=bot_token, - ) + ), ) except UserMigrate as e: await self.session.stop() @@ -45,7 +45,7 @@ async def sign_in_bot(self: pyrogram.Client, bot_token: str) -> types.User: self, await self.storage.dc_id(), await self.storage.test_mode(), - ).create() + ).create(), ) self.session = Session( self, diff --git a/pyrogram/methods/auth/sign_up.py b/pyrogram/methods/auth/sign_up.py index aa5a5133..61ae78c3 100644 --- a/pyrogram/methods/auth/sign_up.py +++ b/pyrogram/methods/auth/sign_up.py @@ -47,7 +47,7 @@ async def sign_up( first_name=first_name, last_name=last_name, phone_code_hash=phone_code_hash, - ) + ), ) await self.storage.user_id(r.user.id) diff --git a/pyrogram/methods/bots/answer_callback_query.py b/pyrogram/methods/bots/answer_callback_query.py index 181c1afd..d0c8558f 100644 --- a/pyrogram/methods/bots/answer_callback_query.py +++ b/pyrogram/methods/bots/answer_callback_query.py @@ -61,5 +61,5 @@ async def answer_callback_query( alert=show_alert or None, message=text or None, url=url or None, - ) + ), ) diff --git a/pyrogram/methods/bots/answer_inline_query.py b/pyrogram/methods/bots/answer_inline_query.py index 0770c68e..8e9fe188 100644 --- a/pyrogram/methods/bots/answer_inline_query.py +++ b/pyrogram/methods/bots/answer_inline_query.py @@ -96,5 +96,5 @@ async def answer_inline_query( ) if switch_pm_text else None, - ) + ), ) diff --git a/pyrogram/methods/bots/answer_web_app_query.py b/pyrogram/methods/bots/answer_web_app_query.py index cc08112e..2664503d 100644 --- a/pyrogram/methods/bots/answer_web_app_query.py +++ b/pyrogram/methods/bots/answer_web_app_query.py @@ -30,7 +30,7 @@ async def answer_web_app_query( raw.functions.messages.SendWebViewResultMessage( bot_query_id=web_app_query_id, result=await result.write(self), - ) + ), ) return types.SentWebAppMessage._parse(r) diff --git a/pyrogram/methods/bots/delete_bot_commands.py b/pyrogram/methods/bots/delete_bot_commands.py index 0e53d373..b0409a14 100644 --- a/pyrogram/methods/bots/delete_bot_commands.py +++ b/pyrogram/methods/bots/delete_bot_commands.py @@ -7,7 +7,7 @@ class DeleteBotCommands: async def delete_bot_commands( self: pyrogram.Client, - scope: types.BotCommandScope = types.BotCommandScopeDefault(), + scope: types.BotCommandScope = None, language_code: str = "", ) -> bool: """Delete the list of the bot's commands for the given scope and user language. @@ -37,10 +37,12 @@ async def delete_bot_commands( # Delete commands await app.delete_bot_commands() """ + if scope is None: + scope = types.BotCommandScopeDefault() return await self.invoke( raw.functions.bots.ResetBotCommands( scope=await scope.write(self), lang_code=language_code, - ) + ), ) diff --git a/pyrogram/methods/bots/get_bot_commands.py b/pyrogram/methods/bots/get_bot_commands.py index 593955d5..6a6af5c6 100644 --- a/pyrogram/methods/bots/get_bot_commands.py +++ b/pyrogram/methods/bots/get_bot_commands.py @@ -7,7 +7,7 @@ class GetBotCommands: async def get_bot_commands( self: pyrogram.Client, - scope: types.BotCommandScope = types.BotCommandScopeDefault(), + scope: types.BotCommandScope = None, language_code: str = "", ) -> list[types.BotCommand]: """Get the current list of the bot's commands for the given scope and user language. @@ -38,12 +38,14 @@ async def get_bot_commands( commands = await app.get_bot_commands() print(commands) """ + if scope is None: + scope = types.BotCommandScopeDefault() r = await self.invoke( raw.functions.bots.GetBotCommands( scope=await scope.write(self), lang_code=language_code, - ) + ), ) return types.List(types.BotCommand.read(c) for c in r) diff --git a/pyrogram/methods/bots/get_bot_default_privileges.py b/pyrogram/methods/bots/get_bot_default_privileges.py index b68f0555..474acdd8 100644 --- a/pyrogram/methods/bots/get_bot_default_privileges.py +++ b/pyrogram/methods/bots/get_bot_default_privileges.py @@ -6,7 +6,8 @@ class GetBotDefaultPrivileges: async def get_bot_default_privileges( - self: pyrogram.Client, for_channels: bool | None = None + self: pyrogram.Client, + for_channels: bool | None = None, ) -> types.ChatPrivileges | None: """Get the current default privileges of the bot. @@ -27,7 +28,7 @@ async def get_bot_default_privileges( """ bot_info = await self.invoke( - raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()) + raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()), ) field = ( diff --git a/pyrogram/methods/bots/get_bot_info.py b/pyrogram/methods/bots/get_bot_info.py index a48c2607..2cdab0b7 100644 --- a/pyrogram/methods/bots/get_bot_info.py +++ b/pyrogram/methods/bots/get_bot_info.py @@ -28,6 +28,6 @@ async def get_bot_info( if bot: peer = await self.resolve_peer(bot) r = await self.invoke( - raw.functions.bots.GetBotInfo(lang_code=lang_code, bot=peer) + raw.functions.bots.GetBotInfo(lang_code=lang_code, bot=peer), ) return pyrogram.types.BotInfo._parse(r) diff --git a/pyrogram/methods/bots/get_chat_menu_button.py b/pyrogram/methods/bots/get_chat_menu_button.py index 876b1900..c087ac18 100644 --- a/pyrogram/methods/bots/get_chat_menu_button.py +++ b/pyrogram/methods/bots/get_chat_menu_button.py @@ -24,12 +24,12 @@ async def get_chat_menu_button( r = await self.invoke( raw.functions.bots.GetBotMenuButton( user_id=await self.resolve_peer(chat_id), - ) + ), ) else: r = ( await self.invoke( - raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()) + raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()), ) ).full_user.bot_info.menu_button @@ -41,6 +41,7 @@ async def get_chat_menu_button( if isinstance(r, raw.types.BotMenuButton): return types.MenuButtonWebApp( - text=r.text, web_app=types.WebAppInfo(url=r.url) + text=r.text, + web_app=types.WebAppInfo(url=r.url), ) return None diff --git a/pyrogram/methods/bots/get_collectible_item_info.py b/pyrogram/methods/bots/get_collectible_item_info.py index 68500cb7..4820c002 100644 --- a/pyrogram/methods/bots/get_collectible_item_info.py +++ b/pyrogram/methods/bots/get_collectible_item_info.py @@ -40,11 +40,11 @@ async def get_collectible_item_info( input_collectible = raw.types.InputCollectiblePhone(phone=phone_number) else: raise ValueError( - "No argument supplied. Either pass username OR phone_number" + "No argument supplied. Either pass username OR phone_number", ) r = await self.invoke( - raw.functions.fragment.GetCollectibleInfo(collectible=input_collectible) + raw.functions.fragment.GetCollectibleInfo(collectible=input_collectible), ) return types.CollectibleItemInfo._parse(r) diff --git a/pyrogram/methods/bots/get_game_high_scores.py b/pyrogram/methods/bots/get_game_high_scores.py index 06991647..f5a8b0e8 100644 --- a/pyrogram/methods/bots/get_game_high_scores.py +++ b/pyrogram/methods/bots/get_game_high_scores.py @@ -47,7 +47,7 @@ async def get_game_high_scores( peer=await self.resolve_peer(chat_id), id=message_id, user_id=await self.resolve_peer(user_id), - ) + ), ) return types.List( diff --git a/pyrogram/methods/bots/get_inline_bot_results.py b/pyrogram/methods/bots/get_inline_bot_results.py index d251ab9b..1538af1a 100644 --- a/pyrogram/methods/bots/get_inline_bot_results.py +++ b/pyrogram/methods/bots/get_inline_bot_results.py @@ -63,7 +63,7 @@ async def get_inline_bot_results( geo_point=raw.types.InputGeoPoint(lat=latitude, long=longitude) if (latitude is not None and longitude is not None) else None, - ) + ), ) except UnknownError as e: if e.value.error_code == -503 and e.value.error_message == "Timeout": diff --git a/pyrogram/methods/bots/send_game.py b/pyrogram/methods/bots/send_game.py index 84780052..a579f91e 100644 --- a/pyrogram/methods/bots/send_game.py +++ b/pyrogram/methods/bots/send_game.py @@ -98,8 +98,9 @@ async def send_game( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/bots/send_inline_bot_result.py b/pyrogram/methods/bots/send_inline_bot_result.py index 3b070933..dc1c89e7 100644 --- a/pyrogram/methods/bots/send_inline_bot_result.py +++ b/pyrogram/methods/bots/send_inline_bot_result.py @@ -13,6 +13,7 @@ async def send_inline_bot_result( disable_notification: bool | None = None, message_thread_id: int | None = None, reply_to_message_id: int | None = None, + reply_to_story_id: int | None = None, quote_text: str | None = None, quote_entities: list[types.MessageEntity] | None = None, parse_mode: enums.ParseMode | None = None, @@ -54,6 +55,9 @@ async def send_inline_bot_result( List of special entities that appear in quote_text, which can be specified instead of *parse_mode*. for reply_to_message only. + reply_to_story_id (``int``, *optional*): + If the message is a reply, ID of the target story. + parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): By default, quote_text are parsed using both Markdown and HTML styles. You can combine both syntaxes together. @@ -72,6 +76,7 @@ async def send_inline_bot_result( client=self, chat_id=chat_id, reply_to_message_id=reply_to_message_id, + reply_to_story_id=reply_to_story_id, message_thread_id=message_thread_id, quote_text=quote_text, quote_entities=quote_entities, @@ -86,12 +91,13 @@ async def send_inline_bot_result( random_id=self.rnd_id(), silent=disable_notification or None, reply_to=reply_to, - ) + ), ) for i in r.updates: if isinstance( - i, raw.types.UpdateNewMessage | raw.types.UpdateNewChannelMessage + i, + raw.types.UpdateNewMessage | raw.types.UpdateNewChannelMessage, ): return await types.Message._parse( self, diff --git a/pyrogram/methods/bots/set_bot_commands.py b/pyrogram/methods/bots/set_bot_commands.py index 5a3b38da..cdc11091 100644 --- a/pyrogram/methods/bots/set_bot_commands.py +++ b/pyrogram/methods/bots/set_bot_commands.py @@ -8,7 +8,7 @@ class SetBotCommands: async def set_bot_commands( self: pyrogram.Client, commands: list[types.BotCommand], - scope: types.BotCommandScope = types.BotCommandScopeDefault(), + scope: types.BotCommandScope = None, language_code: str = "", ) -> bool: """Set the list of the bot's commands. @@ -44,11 +44,13 @@ async def set_bot_commands( BotCommand("start", "Start the bot"), BotCommand("settings", "Bot settings")]) """ + if scope is None: + scope = types.BotCommandScopeDefault() return await self.invoke( raw.functions.bots.SetBotCommands( commands=[c.write() for c in commands], scope=await scope.write(self), lang_code=language_code, - ) + ), ) diff --git a/pyrogram/methods/bots/set_bot_info.py b/pyrogram/methods/bots/set_bot_info.py index ae9239da..4cee9ac4 100644 --- a/pyrogram/methods/bots/set_bot_info.py +++ b/pyrogram/methods/bots/set_bot_info.py @@ -46,6 +46,6 @@ async def set_bot_info( name=name, about=about, description=description, - ) + ), ) return bool(r) diff --git a/pyrogram/methods/bots/set_chat_menu_button.py b/pyrogram/methods/bots/set_chat_menu_button.py index c81972e2..db2dd1ef 100644 --- a/pyrogram/methods/bots/set_chat_menu_button.py +++ b/pyrogram/methods/bots/set_chat_menu_button.py @@ -32,7 +32,7 @@ async def set_chat_menu_button( if menu_button else (await types.MenuButtonDefault().write(self)) ), - ) + ), ) return True diff --git a/pyrogram/methods/bots/set_game_score.py b/pyrogram/methods/bots/set_game_score.py index 4c27e966..f13bc2e8 100644 --- a/pyrogram/methods/bots/set_game_score.py +++ b/pyrogram/methods/bots/set_game_score.py @@ -66,7 +66,7 @@ async def set_game_score( user_id=await self.resolve_peer(user_id), force=force or None, edit_message=not disable_edit_message or None, - ) + ), ) for i in r.updates: diff --git a/pyrogram/methods/business/answer_pre_checkout_query.py b/pyrogram/methods/business/answer_pre_checkout_query.py index 4d625d6f..ca2fbab2 100644 --- a/pyrogram/methods/business/answer_pre_checkout_query.py +++ b/pyrogram/methods/business/answer_pre_checkout_query.py @@ -44,5 +44,5 @@ async def answer_pre_checkout_query( query_id=int(pre_checkout_query_id), success=success or None, error=error or None, - ) + ), ) diff --git a/pyrogram/methods/business/answer_shipping_query.py b/pyrogram/methods/business/answer_shipping_query.py index f302b493..f0f3ad27 100644 --- a/pyrogram/methods/business/answer_shipping_query.py +++ b/pyrogram/methods/business/answer_shipping_query.py @@ -50,13 +50,13 @@ async def answer_shipping_query( raw.functions.messages.SetBotShippingResults( query_id=int(shipping_query_id), shipping_options=[so.write() for so in shipping_options], - ) + ), ) else: r = await self.invoke( raw.functions.messages.SetBotShippingResults( query_id=int(shipping_query_id), error=error_message or None, - ) + ), ) return r diff --git a/pyrogram/methods/business/create_invoice_link.py b/pyrogram/methods/business/create_invoice_link.py index ad79ec41..6bbc0503 100644 --- a/pyrogram/methods/business/create_invoice_link.py +++ b/pyrogram/methods/business/create_invoice_link.py @@ -116,8 +116,9 @@ async def create_invoice_link( size=photo_size, attributes=[ raw.types.DocumentAttributeImageSize( - w=photo_width, h=photo_height - ) + w=photo_width, + h=photo_height, + ), ], ) if photo_url @@ -139,10 +140,10 @@ async def create_invoice_link( payload=payload.encode() if isinstance(payload, str) else payload, provider=provider_token, provider_data=raw.types.DataJSON( - data=provider_data if provider_data else "{}" + data=provider_data if provider_data else "{}", ), start_param=start_parameter, - ) + ), ) r = await self.invoke(rpc) return r.url diff --git a/pyrogram/methods/business/get_business_connection.py b/pyrogram/methods/business/get_business_connection.py index ee14e1b3..9ad01013 100644 --- a/pyrogram/methods/business/get_business_connection.py +++ b/pyrogram/methods/business/get_business_connection.py @@ -6,7 +6,8 @@ class GetBusinessConnection: async def get_business_connection( - self: pyrogram.Client, business_connection_id: str + self: pyrogram.Client, + business_connection_id: str, ) -> types.Message: """Use this method to get information about the connection of the bot with a business account. @@ -22,12 +23,13 @@ async def get_business_connection( r = await self.invoke( raw.functions.account.GetBotBusinessConnection( - connection_id=business_connection_id - ) + connection_id=business_connection_id, + ), ) for i in r.updates: if isinstance(i, (raw.types.UpdateBotBusinessConnect)): return await types.BotBusinessConnection._parse( - client=self, bot_connection=i.connection + client=self, + bot_connection=i.connection, ) return None diff --git a/pyrogram/methods/business/get_payment_form.py b/pyrogram/methods/business/get_payment_form.py index 6fd19896..01d91139 100644 --- a/pyrogram/methods/business/get_payment_form.py +++ b/pyrogram/methods/business/get_payment_form.py @@ -40,7 +40,8 @@ async def get_payment_form( if isinstance(message_id, int): invoice = raw.types.InputInvoiceMessage( - peer=await self.resolve_peer(chat_id), msg_id=message_id + peer=await self.resolve_peer(chat_id), + msg_id=message_id, ) elif isinstance(message_id, str): match = re.match( diff --git a/pyrogram/methods/business/get_stars_transactions.py b/pyrogram/methods/business/get_stars_transactions.py index 8fba8b0b..ca254ec1 100644 --- a/pyrogram/methods/business/get_stars_transactions.py +++ b/pyrogram/methods/business/get_stars_transactions.py @@ -68,6 +68,6 @@ async def get_stars_transactions( inbound=is_inbound, outbound=is_outbound, ascending=is_ascending, - ) + ), ) return types.StarsStatus._parse(self, r) diff --git a/pyrogram/methods/business/get_stars_transactions_by_id.py b/pyrogram/methods/business/get_stars_transactions_by_id.py index 62d6e2ee..6d519b3f 100644 --- a/pyrogram/methods/business/get_stars_transactions_by_id.py +++ b/pyrogram/methods/business/get_stars_transactions_by_id.py @@ -63,6 +63,6 @@ async def get_stars_transactions_by_id( ) r = await self.invoke( - raw.functions.payments.GetStarsTransactionsByID(peer=peer, id=ids) + raw.functions.payments.GetStarsTransactionsByID(peer=peer, id=ids), ) return types.StarsStatus._parse(self, r) diff --git a/pyrogram/methods/business/get_user_gifts.py b/pyrogram/methods/business/get_user_gifts.py index 0e6730f7..e658213f 100644 --- a/pyrogram/methods/business/get_user_gifts.py +++ b/pyrogram/methods/business/get_user_gifts.py @@ -53,7 +53,9 @@ async def get_user_gifts( while True: r = await self.invoke( raw.functions.payments.GetUserStarGifts( - user_id=peer, offset=offset, limit=limit + user_id=peer, + offset=offset, + limit=limit, ), sleep_threshold=max(60, self.sleep_threshold), ) diff --git a/pyrogram/methods/business/refund_stars_payment.py b/pyrogram/methods/business/refund_stars_payment.py index 1bd427c7..309a0c6a 100644 --- a/pyrogram/methods/business/refund_stars_payment.py +++ b/pyrogram/methods/business/refund_stars_payment.py @@ -31,7 +31,7 @@ async def refund_star_payment( raw.functions.payments.RefundStarsCharge( user_id=await self.resolve_peer(user_id), charge_id=telegram_payment_charge_id, - ) + ), ) return True diff --git a/pyrogram/methods/business/sell_gift.py b/pyrogram/methods/business/sell_gift.py index 7ec45889..5f376bd3 100644 --- a/pyrogram/methods/business/sell_gift.py +++ b/pyrogram/methods/business/sell_gift.py @@ -6,7 +6,9 @@ class SellGift: async def sell_gift( - self: pyrogram.Client, sender_user_id: int | str, message_id: int + self: pyrogram.Client, + sender_user_id: int | str, + message_id: int, ) -> bool: """Sells a gift received by the current user for Telegram Stars. @@ -37,5 +39,5 @@ async def sell_gift( raise ValueError("sender_user_id must belong to a user.") return await self.invoke( - raw.functions.payments.ConvertStarGift(user_id=peer, msg_id=message_id) + raw.functions.payments.ConvertStarGift(user_id=peer, msg_id=message_id), ) diff --git a/pyrogram/methods/business/send_gift.py b/pyrogram/methods/business/send_gift.py index 3525a20d..1cb97828 100644 --- a/pyrogram/methods/business/send_gift.py +++ b/pyrogram/methods/business/send_gift.py @@ -73,13 +73,14 @@ async def send_gift( ) form = await self.invoke( - raw.functions.payments.GetPaymentForm(invoice=invoice) + raw.functions.payments.GetPaymentForm(invoice=invoice), ) await self.invoke( raw.functions.payments.SendStarsForm( - form_id=form.form_id, invoice=invoice - ) + form_id=form.form_id, + invoice=invoice, + ), ) return True diff --git a/pyrogram/methods/business/send_invoice.py b/pyrogram/methods/business/send_invoice.py index 7c013a83..68a46ebf 100644 --- a/pyrogram/methods/business/send_invoice.py +++ b/pyrogram/methods/business/send_invoice.py @@ -154,7 +154,8 @@ async def send_invoice( prices_total += price.amount text = f"Pay ⭐️{prices_total}" reply_markup.inline_keyboard.insert( - 0, [types.InlineKeyboardButtonBuy(text=text)] + 0, + [types.InlineKeyboardButtonBuy(text=text)], ) reply_to = await utils.get_reply_to( @@ -185,7 +186,7 @@ async def send_invoice( payload=encoded_payload, provider=provider, provider_data=raw.types.DataJSON( - data=provider_data if provider_data else "{}" + data=provider_data if provider_data else "{}", ), photo=raw.types.InputWebDocument( url=photo_url, @@ -205,12 +206,13 @@ async def send_invoice( reply_markup=await reply_markup.write(self) if reply_markup is not None else None, - ) + ), ) for i in r.updates: if isinstance( - i, raw.types.UpdateNewMessage | raw.types.UpdateNewChannelMessage + i, + raw.types.UpdateNewMessage | raw.types.UpdateNewChannelMessage, ): return await types.Message._parse( self, diff --git a/pyrogram/methods/business/send_payment_form.py b/pyrogram/methods/business/send_payment_form.py index abf2d5c5..81b05c87 100644 --- a/pyrogram/methods/business/send_payment_form.py +++ b/pyrogram/methods/business/send_payment_form.py @@ -47,7 +47,8 @@ async def send_payment_form( if isinstance(message_id, int): invoice = raw.types.InputInvoiceMessage( - peer=await self.resolve_peer(chat_id), msg_id=message_id + peer=await self.resolve_peer(chat_id), + msg_id=message_id, ) elif isinstance(message_id, str): match = re.match( @@ -63,7 +64,7 @@ async def send_payment_form( # if form.invoice.currency == "XTR": await self.invoke( - raw.functions.payments.SendStarsForm(form_id=form.id, invoice=invoice) + raw.functions.payments.SendStarsForm(form_id=form.id, invoice=invoice), ) # TODO: Add support for regular invoices (credentials) # else: diff --git a/pyrogram/methods/business/toggle_gift_is_saved.py b/pyrogram/methods/business/toggle_gift_is_saved.py index f373971b..c3caa634 100644 --- a/pyrogram/methods/business/toggle_gift_is_saved.py +++ b/pyrogram/methods/business/toggle_gift_is_saved.py @@ -43,6 +43,8 @@ async def toggle_gift_is_saved( return await self.invoke( raw.functions.payments.SaveStarGift( - user_id=peer, msg_id=message_id, unsave=not is_saved - ) + user_id=peer, + msg_id=message_id, + unsave=not is_saved, + ), ) diff --git a/pyrogram/methods/chats/add_chat_members.py b/pyrogram/methods/chats/add_chat_members.py index a565c46f..a732e4d2 100644 --- a/pyrogram/methods/chats/add_chat_members.py +++ b/pyrogram/methods/chats/add_chat_members.py @@ -57,14 +57,14 @@ async def add_chat_members( chat_id=peer.chat_id, user_id=await self.resolve_peer(user_id), fwd_limit=forward_limit, - ) + ), ) else: await self.invoke( raw.functions.channels.InviteToChannel( channel=peer, users=[await self.resolve_peer(user_id) for user_id in user_ids], - ) + ), ) return True diff --git a/pyrogram/methods/chats/archive_chats.py b/pyrogram/methods/chats/archive_chats.py index c0222d9c..1b53c99d 100644 --- a/pyrogram/methods/chats/archive_chats.py +++ b/pyrogram/methods/chats/archive_chats.py @@ -37,13 +37,14 @@ async def archive_chats( folder_peers = [ raw.types.InputFolderPeer( - peer=await self.resolve_peer(chat), folder_id=1 + peer=await self.resolve_peer(chat), + folder_id=1, ) for chat in chat_ids ] await self.invoke( - raw.functions.folders.EditPeerFolders(folder_peers=folder_peers) + raw.functions.folders.EditPeerFolders(folder_peers=folder_peers), ) return True diff --git a/pyrogram/methods/chats/ban_chat_member.py b/pyrogram/methods/chats/ban_chat_member.py index 4c17f0c6..64afbc83 100644 --- a/pyrogram/methods/chats/ban_chat_member.py +++ b/pyrogram/methods/chats/ban_chat_member.py @@ -14,7 +14,7 @@ async def ban_chat_member( self: pyrogram.Client, chat_id: int | str, user_id: int | str, - until_date: datetime = utils.zero_datetime(), + until_date: datetime | None = None, revoke_messages: bool | None = None, ) -> types.Message | bool: """Ban a user from a group, a supergroup or a channel. @@ -63,6 +63,8 @@ async def ban_chat_member( # Ban chat member and automatically unban after 24h await app.ban_chat_member(chat_id, user_id, datetime.now() + timedelta(days=1)) """ + if until_date is None: + until_date = utils.zero_datetime() chat_peer = await self.resolve_peer(chat_id) user_peer = await self.resolve_peer(user_id) @@ -83,7 +85,7 @@ async def ban_chat_member( embed_links=True, manage_topics=True, ), - ) + ), ) else: r = await self.invoke( @@ -91,7 +93,7 @@ async def ban_chat_member( chat_id=abs(chat_id), user_id=user_peer, revoke_history=revoke_messages, - ) + ), ) for i in r.updates: diff --git a/pyrogram/methods/chats/close_forum_topic.py b/pyrogram/methods/chats/close_forum_topic.py index 9d6c36de..41e785a5 100644 --- a/pyrogram/methods/chats/close_forum_topic.py +++ b/pyrogram/methods/chats/close_forum_topic.py @@ -6,7 +6,9 @@ class CloseForumTopic: async def close_forum_topic( - self: pyrogram.Client, chat_id: int | str, topic_id: int + self: pyrogram.Client, + chat_id: int | str, + topic_id: int, ) -> bool: """Close a forum topic. @@ -33,6 +35,6 @@ async def close_forum_topic( channel=await self.resolve_peer(chat_id), topic_id=topic_id, closed=True, - ) + ), ) return True diff --git a/pyrogram/methods/chats/close_general_topic.py b/pyrogram/methods/chats/close_general_topic.py index af3cfbfb..1f6f724f 100644 --- a/pyrogram/methods/chats/close_general_topic.py +++ b/pyrogram/methods/chats/close_general_topic.py @@ -28,6 +28,6 @@ async def close_general_topic(self: pyrogram.Client, chat_id: int | str) -> bool channel=await self.resolve_peer(chat_id), topic_id=1, closed=True, - ) + ), ) return True diff --git a/pyrogram/methods/chats/create_channel.py b/pyrogram/methods/chats/create_channel.py index 7ed46e8b..47e7f0ff 100644 --- a/pyrogram/methods/chats/create_channel.py +++ b/pyrogram/methods/chats/create_channel.py @@ -6,7 +6,9 @@ class CreateChannel: async def create_channel( - self: pyrogram.Client, title: str, description: str = "" + self: pyrogram.Client, + title: str, + description: str = "", ) -> types.Chat: """Create a new broadcast channel. @@ -29,8 +31,10 @@ async def create_channel( """ r = await self.invoke( raw.functions.channels.CreateChannel( - title=title, about=description, broadcast=True - ) + title=title, + about=description, + broadcast=True, + ), ) return types.Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/methods/chats/create_forum_topic.py b/pyrogram/methods/chats/create_forum_topic.py index e52e5feb..5ceb6d86 100644 --- a/pyrogram/methods/chats/create_forum_topic.py +++ b/pyrogram/methods/chats/create_forum_topic.py @@ -45,7 +45,7 @@ async def create_forum_topic( random_id=self.rnd_id(), icon_color=icon_color, icon_emoji_id=icon_emoji_id, - ) + ), ) return types.ForumTopicCreated._parse(r.updates[1].message) diff --git a/pyrogram/methods/chats/create_group.py b/pyrogram/methods/chats/create_group.py index 6a3df733..f4730138 100644 --- a/pyrogram/methods/chats/create_group.py +++ b/pyrogram/methods/chats/create_group.py @@ -42,7 +42,7 @@ async def create_group( raw.functions.messages.CreateChat( title=title, users=[await self.resolve_peer(u) for u in users], - ) + ), ) return types.Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/methods/chats/create_supergroup.py b/pyrogram/methods/chats/create_supergroup.py index 2835fd93..82474bcd 100644 --- a/pyrogram/methods/chats/create_supergroup.py +++ b/pyrogram/methods/chats/create_supergroup.py @@ -6,7 +6,9 @@ class CreateSupergroup: async def create_supergroup( - self: pyrogram.Client, title: str, description: str = "" + self: pyrogram.Client, + title: str, + description: str = "", ) -> types.Chat: """Create a new supergroup. @@ -33,8 +35,10 @@ async def create_supergroup( """ r = await self.invoke( raw.functions.channels.CreateChannel( - title=title, about=description, megagroup=True - ) + title=title, + about=description, + megagroup=True, + ), ) return types.Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/methods/chats/delete_channel.py b/pyrogram/methods/chats/delete_channel.py index 11027656..d40a36d4 100644 --- a/pyrogram/methods/chats/delete_channel.py +++ b/pyrogram/methods/chats/delete_channel.py @@ -25,8 +25,8 @@ async def delete_channel(self: pyrogram.Client, chat_id: int | str) -> bool: """ await self.invoke( raw.functions.channels.DeleteChannel( - channel=await self.resolve_peer(chat_id) - ) + channel=await self.resolve_peer(chat_id), + ), ) return True diff --git a/pyrogram/methods/chats/delete_chat_photo.py b/pyrogram/methods/chats/delete_chat_photo.py index 990e8c50..f39fd87e 100644 --- a/pyrogram/methods/chats/delete_chat_photo.py +++ b/pyrogram/methods/chats/delete_chat_photo.py @@ -35,14 +35,14 @@ async def delete_chat_photo(self: pyrogram.Client, chat_id: int | str) -> bool: raw.functions.messages.EditChatPhoto( chat_id=peer.chat_id, photo=raw.types.InputChatPhotoEmpty(), - ) + ), ) elif isinstance(peer, raw.types.InputPeerChannel): await self.invoke( raw.functions.channels.EditPhoto( channel=peer, photo=raw.types.InputChatPhotoEmpty(), - ) + ), ) else: raise ValueError(f'The chat_id "{chat_id}" belongs to a user') diff --git a/pyrogram/methods/chats/delete_folder.py b/pyrogram/methods/chats/delete_folder.py index 201d046a..fdc87d85 100644 --- a/pyrogram/methods/chats/delete_folder.py +++ b/pyrogram/methods/chats/delete_folder.py @@ -24,5 +24,5 @@ async def delete_folder(self: pyrogram.Client, folder_id: int) -> bool: app.delete_folder(folder_id) """ return await self.invoke( - raw.functions.messages.UpdateDialogFilter(id=folder_id) + raw.functions.messages.UpdateDialogFilter(id=folder_id), ) diff --git a/pyrogram/methods/chats/delete_forum_topic.py b/pyrogram/methods/chats/delete_forum_topic.py index 329ffc0d..633566f7 100644 --- a/pyrogram/methods/chats/delete_forum_topic.py +++ b/pyrogram/methods/chats/delete_forum_topic.py @@ -6,7 +6,9 @@ class DeleteForumTopic: async def delete_forum_topic( - self: pyrogram.Client, chat_id: int | str, topic_id: int + self: pyrogram.Client, + chat_id: int | str, + topic_id: int, ) -> bool: """Delete a forum topic. @@ -33,7 +35,7 @@ async def delete_forum_topic( raw.functions.channels.DeleteTopicHistory( channel=await self.resolve_peer(chat_id), top_msg_id=topic_id, - ) + ), ) except Exception as e: print(e) diff --git a/pyrogram/methods/chats/delete_supergroup.py b/pyrogram/methods/chats/delete_supergroup.py index 947b3e7f..f5a4d184 100644 --- a/pyrogram/methods/chats/delete_supergroup.py +++ b/pyrogram/methods/chats/delete_supergroup.py @@ -25,8 +25,8 @@ async def delete_supergroup(self: pyrogram.Client, chat_id: int | str) -> bool: """ await self.invoke( raw.functions.channels.DeleteChannel( - channel=await self.resolve_peer(chat_id) - ) + channel=await self.resolve_peer(chat_id), + ), ) return True diff --git a/pyrogram/methods/chats/delete_user_history.py b/pyrogram/methods/chats/delete_user_history.py index ad55a9e1..f770adea 100644 --- a/pyrogram/methods/chats/delete_user_history.py +++ b/pyrogram/methods/chats/delete_user_history.py @@ -31,7 +31,7 @@ async def delete_user_history( raw.functions.channels.DeleteParticipantHistory( channel=await self.resolve_peer(chat_id), participant=await self.resolve_peer(user_id), - ) + ), ) # Deleting messages you don't have right onto won't raise any error. diff --git a/pyrogram/methods/chats/edit_forum_topic.py b/pyrogram/methods/chats/edit_forum_topic.py index e3ec0fe9..549c9659 100644 --- a/pyrogram/methods/chats/edit_forum_topic.py +++ b/pyrogram/methods/chats/edit_forum_topic.py @@ -44,6 +44,6 @@ async def edit_forum_topic( topic_id=topic_id, title=title, icon_emoji_id=icon_emoji_id, - ) + ), ) return True diff --git a/pyrogram/methods/chats/edit_general_topic.py b/pyrogram/methods/chats/edit_general_topic.py index c841f3ea..c2521738 100644 --- a/pyrogram/methods/chats/edit_general_topic.py +++ b/pyrogram/methods/chats/edit_general_topic.py @@ -6,7 +6,9 @@ class EditGeneralTopic: async def edit_general_topic( - self: pyrogram.Client, chat_id: int | str, title: str + self: pyrogram.Client, + chat_id: int | str, + title: str, ) -> bool: """Edit a general forum topic. @@ -33,6 +35,6 @@ async def edit_general_topic( channel=await self.resolve_peer(chat_id), topic_id=1, title=title, - ) + ), ) return True diff --git a/pyrogram/methods/chats/export_folder_link.py b/pyrogram/methods/chats/export_folder_link.py index d7a17875..7dba18c0 100644 --- a/pyrogram/methods/chats/export_folder_link.py +++ b/pyrogram/methods/chats/export_folder_link.py @@ -44,7 +44,7 @@ async def export_folder_link(self: pyrogram.Client, folder_id: int) -> str: chatlist=raw.types.InputChatlistDialogFilter(filter_id=folder_id), title=folder.title, peers=[await self.resolve_peer(i.id) for i in peers], - ) + ), ) return r.invite.url diff --git a/pyrogram/methods/chats/get_chat.py b/pyrogram/methods/chats/get_chat.py index 6a660850..4841437c 100644 --- a/pyrogram/methods/chats/get_chat.py +++ b/pyrogram/methods/chats/get_chat.py @@ -6,7 +6,8 @@ class GetChat: async def get_chat( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> types.Chat | types.ChatPreview: """Get up to date information about a chat. @@ -39,7 +40,7 @@ async def get_chat( if match: r = await self.invoke( - raw.functions.messages.CheckChatInvite(hash=match.group(1)) + raw.functions.messages.CheckChatInvite(hash=match.group(1)), ) if isinstance(r, raw.types.ChatInvite): @@ -57,13 +58,13 @@ async def get_chat( if isinstance(peer, raw.types.InputPeerChannel): r = await self.invoke( - raw.functions.channels.GetFullChannel(channel=peer) + raw.functions.channels.GetFullChannel(channel=peer), ) elif isinstance(peer, raw.types.InputPeerUser | raw.types.InputPeerSelf): r = await self.invoke(raw.functions.users.GetFullUser(id=peer)) else: r = await self.invoke( - raw.functions.messages.GetFullChat(chat_id=peer.chat_id) + raw.functions.messages.GetFullChat(chat_id=peer.chat_id), ) return await types.Chat._parse_full(self, r) diff --git a/pyrogram/methods/chats/get_chat_event_log.py b/pyrogram/methods/chats/get_chat_event_log.py index 59e10fd5..f337692e 100644 --- a/pyrogram/methods/chats/get_chat_event_log.py +++ b/pyrogram/methods/chats/get_chat_event_log.py @@ -78,7 +78,7 @@ async def get_chat_event_log( if user_ids is not None else user_ids ), - ) + ), ) if not r.events: diff --git a/pyrogram/methods/chats/get_chat_member.py b/pyrogram/methods/chats/get_chat_member.py index 61640c76..eb408eb7 100644 --- a/pyrogram/methods/chats/get_chat_member.py +++ b/pyrogram/methods/chats/get_chat_member.py @@ -40,7 +40,7 @@ async def get_chat_member( if isinstance(chat, raw.types.InputPeerChat): r = await self.invoke( - raw.functions.messages.GetFullChat(chat_id=chat.chat_id) + raw.functions.messages.GetFullChat(chat_id=chat.chat_id), ) members = getattr(r.full_chat.participants, "participants", []) @@ -57,7 +57,10 @@ async def get_chat_member( raise UserNotParticipant if isinstance(chat, raw.types.InputPeerChannel): r = await self.invoke( - raw.functions.channels.GetParticipant(channel=chat, participant=user) + raw.functions.channels.GetParticipant( + channel=chat, + participant=user, + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/chats/get_chat_members.py b/pyrogram/methods/chats/get_chat_members.py index 5cf56028..f13a7d4f 100644 --- a/pyrogram/methods/chats/get_chat_members.py +++ b/pyrogram/methods/chats/get_chat_members.py @@ -108,7 +108,7 @@ async def get_chat_members( if isinstance(peer, raw.types.InputPeerChat): r = await self.invoke( - raw.functions.messages.GetFullChat(chat_id=peer.chat_id) + raw.functions.messages.GetFullChat(chat_id=peer.chat_id), ) members = getattr(r.full_chat.participants, "participants", []) diff --git a/pyrogram/methods/chats/get_chat_members_count.py b/pyrogram/methods/chats/get_chat_members_count.py index a322ccdb..bd050cb1 100644 --- a/pyrogram/methods/chats/get_chat_members_count.py +++ b/pyrogram/methods/chats/get_chat_members_count.py @@ -44,7 +44,7 @@ async def get_chat_members_count( return r.chats[0].requests_pending if isinstance(peer, raw.types.InputPeerChannel): r = await self.invoke( - raw.functions.channels.GetFullChannel(channel=peer) + raw.functions.channels.GetFullChannel(channel=peer), ) if not join_request: diff --git a/pyrogram/methods/chats/get_chat_online_count.py b/pyrogram/methods/chats/get_chat_online_count.py index fe537679..f64dcd1f 100644 --- a/pyrogram/methods/chats/get_chat_online_count.py +++ b/pyrogram/methods/chats/get_chat_online_count.py @@ -6,7 +6,8 @@ class GetChatOnlineCount: async def get_chat_online_count( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> int: """Get the number of members that are currently online in a chat. @@ -29,7 +30,7 @@ async def get_chat_online_count( return ( await self.invoke( raw.functions.messages.GetOnlines( - peer=await self.resolve_peer(chat_id) - ) + peer=await self.resolve_peer(chat_id), + ), ) ).onlines diff --git a/pyrogram/methods/chats/get_dialogs.py b/pyrogram/methods/chats/get_dialogs.py index 924542a8..e68f1ec1 100644 --- a/pyrogram/methods/chats/get_dialogs.py +++ b/pyrogram/methods/chats/get_dialogs.py @@ -75,7 +75,11 @@ async def get_dialogs( chat_id = utils.get_peer_id(message.peer_id) messages[chat_id] = await types.Message._parse( - self, message, users, chats, replies=1 + self, + message, + users, + chats, + replies=1, ) dialogs = [] @@ -85,7 +89,7 @@ async def get_dialogs( continue dialogs.append( - types.Dialog._parse(self, dialog, messages, users, chats) + types.Dialog._parse(self, dialog, messages, users, chats), ) if not dialogs: diff --git a/pyrogram/methods/chats/get_dialogs_count.py b/pyrogram/methods/chats/get_dialogs_count.py index ee441ab7..f7a86041 100644 --- a/pyrogram/methods/chats/get_dialogs_count.py +++ b/pyrogram/methods/chats/get_dialogs_count.py @@ -6,7 +6,9 @@ class GetDialogsCount: async def get_dialogs_count( - self: pyrogram.Client, pinned_only: bool = False, chat_list: int = 0 + self: pyrogram.Client, + pinned_only: bool = False, + chat_list: int = 0, ) -> int: """Get the total count of your dialogs. @@ -34,9 +36,9 @@ async def get_dialogs_count( return len( ( await self.invoke( - raw.functions.messages.GetPinnedDialogs(folder_id=chat_list) + raw.functions.messages.GetPinnedDialogs(folder_id=chat_list), ) - ).dialogs + ).dialogs, ) r = await self.invoke( raw.functions.messages.GetDialogs( @@ -46,7 +48,7 @@ async def get_dialogs_count( limit=1, hash=0, folder_id=chat_list, - ) + ), ) if isinstance(r, raw.types.messages.Dialogs): diff --git a/pyrogram/methods/chats/get_folders.py b/pyrogram/methods/chats/get_folders.py index 8c42db89..52446fc9 100644 --- a/pyrogram/methods/chats/get_folders.py +++ b/pyrogram/methods/chats/get_folders.py @@ -49,7 +49,7 @@ async def get_folders( folder for folder in dialog_filters.filters if not isinstance(folder, raw.types.DialogFilterDefault) - and (is_iterable and folder.id in ids or not is_iterable) + and ((is_iterable and folder.id in ids) or not is_iterable) ] raw_peers = {} @@ -67,8 +67,8 @@ async def get_folders( chunk = list(raw_peers.values())[i : i + 100] r = await self.invoke( raw.functions.messages.GetPeerDialogs( - peers=[raw.types.InputDialogPeer(peer=peer) for peer in chunk] - ) + peers=[raw.types.InputDialogPeer(peer=peer) for peer in chunk], + ), ) users.update({i.id: i for i in r.users}) chats.update({i.id: i for i in r.chats}) diff --git a/pyrogram/methods/chats/get_forum_topics.py b/pyrogram/methods/chats/get_forum_topics.py index 90f0b5ed..6f364098 100644 --- a/pyrogram/methods/chats/get_forum_topics.py +++ b/pyrogram/methods/chats/get_forum_topics.py @@ -14,7 +14,9 @@ class GetForumTopics: async def get_forum_topics( - self: pyrogram.Client, chat_id: int | str, limit: int = 0 + self: pyrogram.Client, + chat_id: int | str, + limit: int = 0, ) -> AsyncGenerator[types.ForumTopic, None] | None: """Get one or more topic from a chat. diff --git a/pyrogram/methods/chats/get_send_as_chats.py b/pyrogram/methods/chats/get_send_as_chats.py index 369e8dec..5758ec9e 100644 --- a/pyrogram/methods/chats/get_send_as_chats.py +++ b/pyrogram/methods/chats/get_send_as_chats.py @@ -6,7 +6,8 @@ class GetSendAsChats: async def get_send_as_chats( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> list[types.Chat]: """Get the list of "send_as" chats available. @@ -27,7 +28,7 @@ async def get_send_as_chats( print(chats) """ r = await self.invoke( - raw.functions.channels.GetSendAs(peer=await self.resolve_peer(chat_id)) + raw.functions.channels.GetSendAs(peer=await self.resolve_peer(chat_id)), ) users = {u.id: u for u in r.users} @@ -38,11 +39,11 @@ async def get_send_as_chats( for p in r.peers: if isinstance(p.peer, raw.types.PeerUser): send_as_chats.append( - types.Chat._parse_chat(self, users[p.peer.user_id]) + types.Chat._parse_chat(self, users[p.peer.user_id]), ) else: send_as_chats.append( - types.Chat._parse_chat(self, chats[p.peer.channel_id]) + types.Chat._parse_chat(self, chats[p.peer.channel_id]), ) return send_as_chats diff --git a/pyrogram/methods/chats/hide_general_topic.py b/pyrogram/methods/chats/hide_general_topic.py index 9a4560ab..9840a5e0 100644 --- a/pyrogram/methods/chats/hide_general_topic.py +++ b/pyrogram/methods/chats/hide_general_topic.py @@ -28,6 +28,6 @@ async def hide_general_topic(self: pyrogram.Client, chat_id: int | str) -> bool: channel=await self.resolve_peer(chat_id), topic_id=1, hidden=True, - ) + ), ) return True diff --git a/pyrogram/methods/chats/join_chat.py b/pyrogram/methods/chats/join_chat.py index ba13dbe0..5218443f 100644 --- a/pyrogram/methods/chats/join_chat.py +++ b/pyrogram/methods/chats/join_chat.py @@ -34,7 +34,7 @@ async def join_chat(self: pyrogram.Client, chat_id: int | str) -> types.Chat: if match: chat = await self.invoke( - raw.functions.messages.ImportChatInvite(hash=match.group(1)) + raw.functions.messages.ImportChatInvite(hash=match.group(1)), ) if isinstance(chat.chats[0], raw.types.Chat): return types.Chat._parse_chat_chat(self, chat.chats[0]) @@ -43,8 +43,8 @@ async def join_chat(self: pyrogram.Client, chat_id: int | str) -> types.Chat: return None chat = await self.invoke( raw.functions.channels.JoinChannel( - channel=await self.resolve_peer(chat_id) - ) + channel=await self.resolve_peer(chat_id), + ), ) return types.Chat._parse_channel_chat(self, chat.chats[0]) diff --git a/pyrogram/methods/chats/leave_chat.py b/pyrogram/methods/chats/leave_chat.py index 3f4921d8..3586a5af 100644 --- a/pyrogram/methods/chats/leave_chat.py +++ b/pyrogram/methods/chats/leave_chat.py @@ -40,20 +40,20 @@ async def leave_chat( if isinstance(peer, raw.types.InputPeerChannel): return await self.invoke( raw.functions.channels.LeaveChannel( - channel=await self.resolve_peer(chat_id) - ) + channel=await self.resolve_peer(chat_id), + ), ) if isinstance(peer, raw.types.InputPeerChat): r = await self.invoke( raw.functions.messages.DeleteChatUser( chat_id=peer.chat_id, user_id=raw.types.InputUserSelf(), - ) + ), ) if delete: await self.invoke( - raw.functions.messages.DeleteHistory(peer=peer, max_id=0) + raw.functions.messages.DeleteHistory(peer=peer, max_id=0), ) return r diff --git a/pyrogram/methods/chats/mark_chat_unread.py b/pyrogram/methods/chats/mark_chat_unread.py index 952aeccd..b84cd670 100644 --- a/pyrogram/methods/chats/mark_chat_unread.py +++ b/pyrogram/methods/chats/mark_chat_unread.py @@ -24,6 +24,7 @@ async def mark_chat_unread( return await self.invoke( raw.functions.messages.MarkDialogUnread( - peer=await self.resolve_peer(chat_id), unread=True - ) + peer=await self.resolve_peer(chat_id), + unread=True, + ), ) diff --git a/pyrogram/methods/chats/pin_chat_message.py b/pyrogram/methods/chats/pin_chat_message.py index 810f4dbe..de6fc136 100644 --- a/pyrogram/methods/chats/pin_chat_message.py +++ b/pyrogram/methods/chats/pin_chat_message.py @@ -52,7 +52,7 @@ async def pin_chat_message( id=message_id, silent=disable_notification or None, pm_oneside=not both_sides or None, - ) + ), ) users = {u.id: u for u in r.users} diff --git a/pyrogram/methods/chats/promote_chat_member.py b/pyrogram/methods/chats/promote_chat_member.py index 0dc09d32..8dcdcf9b 100644 --- a/pyrogram/methods/chats/promote_chat_member.py +++ b/pyrogram/methods/chats/promote_chat_member.py @@ -57,15 +57,17 @@ async def promote_chat_member( raw_chat_member = ( await self.invoke( raw.functions.channels.GetParticipant( - channel=chat_id, participant=user_id - ) + channel=chat_id, + participant=user_id, + ), ) ).participant except errors.RPCError: raw_chat_member = None if not title and isinstance( - raw_chat_member, raw.types.ChannelParticipantAdmin + raw_chat_member, + raw.types.ChannelParticipantAdmin, ): rank = raw_chat_member.rank else: @@ -93,7 +95,7 @@ async def promote_chat_member( other=privileges.can_manage_chat, ), rank=rank or "", - ) + ), ) return True diff --git a/pyrogram/methods/chats/reopen_forum_topic.py b/pyrogram/methods/chats/reopen_forum_topic.py index cdbff518..1cb3b0aa 100644 --- a/pyrogram/methods/chats/reopen_forum_topic.py +++ b/pyrogram/methods/chats/reopen_forum_topic.py @@ -6,7 +6,9 @@ class ReopenForumTopic: async def reopen_forum_topic( - self: pyrogram.Client, chat_id: int | str, topic_id: int + self: pyrogram.Client, + chat_id: int | str, + topic_id: int, ) -> bool: """Reopen a forum topic. @@ -33,6 +35,6 @@ async def reopen_forum_topic( channel=await self.resolve_peer(chat_id), topic_id=topic_id, closed=False, - ) + ), ) return True diff --git a/pyrogram/methods/chats/reopen_general_topic.py b/pyrogram/methods/chats/reopen_general_topic.py index 4df8228e..5e354f66 100644 --- a/pyrogram/methods/chats/reopen_general_topic.py +++ b/pyrogram/methods/chats/reopen_general_topic.py @@ -6,7 +6,8 @@ class ReopenGeneralTopic: async def reopen_general_topic( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> bool: """Reopen a general forum topic. @@ -30,6 +31,6 @@ async def reopen_general_topic( channel=await self.resolve_peer(chat_id), topic_id=1, closed=False, - ) + ), ) return True diff --git a/pyrogram/methods/chats/restrict_chat_member.py b/pyrogram/methods/chats/restrict_chat_member.py index ca8f51e0..20d0da7d 100644 --- a/pyrogram/methods/chats/restrict_chat_member.py +++ b/pyrogram/methods/chats/restrict_chat_member.py @@ -15,7 +15,7 @@ async def restrict_chat_member( chat_id: int | str, user_id: int | str, permissions: types.ChatPermissions, - until_date: datetime = utils.zero_datetime(), + until_date: datetime | None = None, ) -> types.Chat: """Restrict a user in a supergroup. @@ -62,6 +62,8 @@ async def restrict_chat_member( await app.restrict_chat_member(chat_id, user_id, ChatPermissions(can_send_messages=True)) """ + if until_date is None: + until_date = utils.zero_datetime() if permissions.all_perms is not None: send_audios = None @@ -242,7 +244,7 @@ async def restrict_chat_member( send_videos=send_videos, send_voices=send_voices, ), - ) + ), ) return types.Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/methods/chats/set_administrator_title.py b/pyrogram/methods/chats/set_administrator_title.py index 32e64b7b..af5338a5 100644 --- a/pyrogram/methods/chats/set_administrator_title.py +++ b/pyrogram/methods/chats/set_administrator_title.py @@ -46,8 +46,9 @@ async def set_administrator_title( r = ( await self.invoke( raw.functions.channels.GetParticipant( - channel=chat_id, participant=user_id - ) + channel=chat_id, + participant=user_id, + ), ) ).participant @@ -57,7 +58,7 @@ async def set_administrator_title( admin_rights = r.admin_rights else: raise ValueError( - "Custom titles can only be applied to owners or administrators of supergroups" + "Custom titles can only be applied to owners or administrators of supergroups", ) await self.invoke( @@ -66,7 +67,7 @@ async def set_administrator_title( user_id=user_id, admin_rights=admin_rights, rank=title, - ) + ), ) return True diff --git a/pyrogram/methods/chats/set_chat_description.py b/pyrogram/methods/chats/set_chat_description.py index 9c39fb97..32d7f9d8 100644 --- a/pyrogram/methods/chats/set_chat_description.py +++ b/pyrogram/methods/chats/set_chat_description.py @@ -6,7 +6,9 @@ class SetChatDescription: async def set_chat_description( - self: pyrogram.Client, chat_id: int | str, description: str + self: pyrogram.Client, + chat_id: int | str, + description: str, ) -> bool: """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. @@ -39,7 +41,7 @@ async def set_chat_description( raw.types.InputPeerChannel | raw.types.InputPeerChat, ): await self.invoke( - raw.functions.messages.EditChatAbout(peer=peer, about=description) + raw.functions.messages.EditChatAbout(peer=peer, about=description), ) else: raise ValueError(f'The chat_id "{chat_id}" belongs to a user') diff --git a/pyrogram/methods/chats/set_chat_permissions.py b/pyrogram/methods/chats/set_chat_permissions.py index 2cb0d1ec..06cb41f8 100644 --- a/pyrogram/methods/chats/set_chat_permissions.py +++ b/pyrogram/methods/chats/set_chat_permissions.py @@ -225,7 +225,7 @@ async def set_chat_permissions( send_videos=send_videos, send_voices=send_voices, ), - ) + ), ) return types.Chat._parse_chat(self, r.chats[0]) diff --git a/pyrogram/methods/chats/set_chat_photo.py b/pyrogram/methods/chats/set_chat_photo.py index 33d5c0b3..91c8c609 100644 --- a/pyrogram/methods/chats/set_chat_photo.py +++ b/pyrogram/methods/chats/set_chat_photo.py @@ -90,11 +90,11 @@ async def set_chat_photo( raw.functions.messages.EditChatPhoto( chat_id=peer.chat_id, photo=photo, - ) + ), ) elif isinstance(peer, raw.types.InputPeerChannel): await self.invoke( - raw.functions.channels.EditPhoto(channel=peer, photo=photo) + raw.functions.channels.EditPhoto(channel=peer, photo=photo), ) else: raise ValueError(f'The chat_id "{chat_id}" belongs to a user') diff --git a/pyrogram/methods/chats/set_chat_protected_content.py b/pyrogram/methods/chats/set_chat_protected_content.py index 1a325f3d..fd6e98b6 100644 --- a/pyrogram/methods/chats/set_chat_protected_content.py +++ b/pyrogram/methods/chats/set_chat_protected_content.py @@ -6,7 +6,9 @@ class SetChatProtectedContent: async def set_chat_protected_content( - self: pyrogram.Client, chat_id: int | str, enabled: bool + self: pyrogram.Client, + chat_id: int | str, + enabled: bool, ) -> bool: """Set the chat protected content setting. @@ -26,8 +28,9 @@ async def set_chat_protected_content( await self.invoke( raw.functions.messages.ToggleNoForwards( - peer=await self.resolve_peer(chat_id), enabled=enabled - ) + peer=await self.resolve_peer(chat_id), + enabled=enabled, + ), ) return True diff --git a/pyrogram/methods/chats/set_chat_title.py b/pyrogram/methods/chats/set_chat_title.py index a3694601..85396bba 100644 --- a/pyrogram/methods/chats/set_chat_title.py +++ b/pyrogram/methods/chats/set_chat_title.py @@ -6,7 +6,9 @@ class SetChatTitle: async def set_chat_title( - self: pyrogram.Client, chat_id: int | str, title: str + self: pyrogram.Client, + chat_id: int | str, + title: str, ) -> bool: """Change the title of a chat. Titles can't be changed for private chats. @@ -42,12 +44,13 @@ async def set_chat_title( if isinstance(peer, raw.types.InputPeerChat): await self.invoke( raw.functions.messages.EditChatTitle( - chat_id=peer.chat_id, title=title - ) + chat_id=peer.chat_id, + title=title, + ), ) elif isinstance(peer, raw.types.InputPeerChannel): await self.invoke( - raw.functions.channels.EditTitle(channel=peer, title=title) + raw.functions.channels.EditTitle(channel=peer, title=title), ) else: raise ValueError(f'The chat_id "{chat_id}" belongs to a user') diff --git a/pyrogram/methods/chats/set_chat_username.py b/pyrogram/methods/chats/set_chat_username.py index 86ab0b50..f2189809 100644 --- a/pyrogram/methods/chats/set_chat_username.py +++ b/pyrogram/methods/chats/set_chat_username.py @@ -42,8 +42,9 @@ async def set_chat_username( return bool( await self.invoke( raw.functions.channels.UpdateUsername( - channel=peer, username=username or "" - ) - ) + channel=peer, + username=username or "", + ), + ), ) raise ValueError(f'The chat_id "{chat_id}" belongs to a user or chat') diff --git a/pyrogram/methods/chats/set_send_as_chat.py b/pyrogram/methods/chats/set_send_as_chat.py index 476fb72a..80ee1b6a 100644 --- a/pyrogram/methods/chats/set_send_as_chat.py +++ b/pyrogram/methods/chats/set_send_as_chat.py @@ -37,5 +37,5 @@ async def set_send_as_chat( raw.functions.messages.SaveDefaultSendAs( peer=await self.resolve_peer(chat_id), send_as=await self.resolve_peer(send_as_chat_id), - ) + ), ) diff --git a/pyrogram/methods/chats/set_slow_mode.py b/pyrogram/methods/chats/set_slow_mode.py index 98eb47c7..9f8219e4 100644 --- a/pyrogram/methods/chats/set_slow_mode.py +++ b/pyrogram/methods/chats/set_slow_mode.py @@ -40,7 +40,7 @@ async def set_slow_mode( raw.functions.channels.ToggleSlowMode( channel=await self.resolve_peer(chat_id), seconds=seconds or 0, - ) + ), ) return True diff --git a/pyrogram/methods/chats/unarchive_chats.py b/pyrogram/methods/chats/unarchive_chats.py index 7f6d4786..823c2443 100644 --- a/pyrogram/methods/chats/unarchive_chats.py +++ b/pyrogram/methods/chats/unarchive_chats.py @@ -37,13 +37,14 @@ async def unarchive_chats( folder_peers = [ raw.types.InputFolderPeer( - peer=await self.resolve_peer(chat), folder_id=0 + peer=await self.resolve_peer(chat), + folder_id=0, ) for chat in chat_ids ] await self.invoke( - raw.functions.folders.EditPeerFolders(folder_peers=folder_peers) + raw.functions.folders.EditPeerFolders(folder_peers=folder_peers), ) return True diff --git a/pyrogram/methods/chats/unban_chat_member.py b/pyrogram/methods/chats/unban_chat_member.py index 3f38a5d9..45d35ad4 100644 --- a/pyrogram/methods/chats/unban_chat_member.py +++ b/pyrogram/methods/chats/unban_chat_member.py @@ -39,7 +39,7 @@ async def unban_chat_member( channel=await self.resolve_peer(chat_id), participant=await self.resolve_peer(user_id), banned_rights=raw.types.ChatBannedRights(until_date=0), - ) + ), ) return True diff --git a/pyrogram/methods/chats/unhide_general_topic.py b/pyrogram/methods/chats/unhide_general_topic.py index a6a1a367..cc8867ef 100644 --- a/pyrogram/methods/chats/unhide_general_topic.py +++ b/pyrogram/methods/chats/unhide_general_topic.py @@ -6,7 +6,8 @@ class UnhideGeneralTopic: async def unhide_general_topic( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> bool: """unhide a general forum topic. @@ -30,6 +31,6 @@ async def unhide_general_topic( channel=await self.resolve_peer(chat_id), topic_id=1, hidden=False, - ) + ), ) return True diff --git a/pyrogram/methods/chats/unpin_all_chat_messages.py b/pyrogram/methods/chats/unpin_all_chat_messages.py index c8a0a022..157ec879 100644 --- a/pyrogram/methods/chats/unpin_all_chat_messages.py +++ b/pyrogram/methods/chats/unpin_all_chat_messages.py @@ -31,8 +31,8 @@ async def unpin_all_chat_messages( """ await self.invoke( raw.functions.messages.UnpinAllMessages( - peer=await self.resolve_peer(chat_id) - ) + peer=await self.resolve_peer(chat_id), + ), ) return True diff --git a/pyrogram/methods/chats/unpin_chat_message.py b/pyrogram/methods/chats/unpin_chat_message.py index e1e6a569..5a6a821e 100644 --- a/pyrogram/methods/chats/unpin_chat_message.py +++ b/pyrogram/methods/chats/unpin_chat_message.py @@ -38,7 +38,7 @@ async def unpin_chat_message( peer=await self.resolve_peer(chat_id), id=message_id, unpin=True, - ) + ), ) return True diff --git a/pyrogram/methods/chats/update_color.py b/pyrogram/methods/chats/update_color.py index 41f29b0a..aae1983a 100644 --- a/pyrogram/methods/chats/update_color.py +++ b/pyrogram/methods/chats/update_color.py @@ -43,7 +43,7 @@ async def update_color( for_profile=isinstance(color, enums.ProfileColor), color=color.value, background_emoji_id=background_emoji_id, - ) + ), ) else: r = await self.invoke( @@ -51,7 +51,7 @@ async def update_color( channel=peer, color=color.value, background_emoji_id=background_emoji_id, - ) + ), ) return bool(r) diff --git a/pyrogram/methods/chats/update_folder.py b/pyrogram/methods/chats/update_folder.py index bb209137..2f187e55 100644 --- a/pyrogram/methods/chats/update_folder.py +++ b/pyrogram/methods/chats/update_folder.py @@ -122,5 +122,5 @@ async def update_folder( emoticon=emoji, color=color.value if color else None, ), - ) + ), ) diff --git a/pyrogram/methods/contacts/add_contact.py b/pyrogram/methods/contacts/add_contact.py index ffd7febf..c3bc1538 100644 --- a/pyrogram/methods/contacts/add_contact.py +++ b/pyrogram/methods/contacts/add_contact.py @@ -54,7 +54,7 @@ async def add_contact( last_name=last_name, phone=phone_number, add_phone_privacy_exception=share_phone_number, - ) + ), ) return types.User._parse(self, r.users[0]) diff --git a/pyrogram/methods/contacts/delete_contacts.py b/pyrogram/methods/contacts/delete_contacts.py index 993274b5..54a43790 100644 --- a/pyrogram/methods/contacts/delete_contacts.py +++ b/pyrogram/methods/contacts/delete_contacts.py @@ -6,7 +6,8 @@ class DeleteContacts: async def delete_contacts( - self: pyrogram.Client, user_ids: int | str | list[int | str] + self: pyrogram.Client, + user_ids: int | str | list[int | str], ) -> types.User | list[types.User] | None: """Delete contacts from your Telegram address book. @@ -36,8 +37,8 @@ async def delete_contacts( r = await self.invoke( raw.functions.contacts.DeleteContacts( - id=[await self.resolve_peer(i) for i in user_ids] - ) + id=[await self.resolve_peer(i) for i in user_ids], + ), ) if not r.updates: diff --git a/pyrogram/methods/contacts/get_contacts_count.py b/pyrogram/methods/contacts/get_contacts_count.py index 815adf2a..b30aff57 100644 --- a/pyrogram/methods/contacts/get_contacts_count.py +++ b/pyrogram/methods/contacts/get_contacts_count.py @@ -21,5 +21,5 @@ async def get_contacts_count(self: pyrogram.Client) -> int: """ return len( - (await self.invoke(raw.functions.contacts.GetContacts(hash=0))).contacts + (await self.invoke(raw.functions.contacts.GetContacts(hash=0))).contacts, ) diff --git a/pyrogram/methods/contacts/import_contacts.py b/pyrogram/methods/contacts/import_contacts.py index 4acaeeaf..8f8e5e57 100644 --- a/pyrogram/methods/contacts/import_contacts.py +++ b/pyrogram/methods/contacts/import_contacts.py @@ -31,5 +31,5 @@ async def import_contacts( InputPhoneContact("+1-789-012-3456", "Baz")]) """ return await self.invoke( - raw.functions.contacts.ImportContacts(contacts=contacts) + raw.functions.contacts.ImportContacts(contacts=contacts), ) diff --git a/pyrogram/methods/contacts/search_contacts.py b/pyrogram/methods/contacts/search_contacts.py index 2c351498..c18d566b 100644 --- a/pyrogram/methods/contacts/search_contacts.py +++ b/pyrogram/methods/contacts/search_contacts.py @@ -6,7 +6,9 @@ class SearchContacts: async def search_contacts( - self: pyrogram.Client, query: str, limit: int = 0 + self: pyrogram.Client, + query: str, + limit: int = 0, ) -> types.FoundContacts: """Returns users or channels found by name substring and auxiliary data. diff --git a/pyrogram/methods/decorators/on_bot_business_connect.py b/pyrogram/methods/decorators/on_bot_business_connect.py index 638fb3c5..b94c9d47 100644 --- a/pyrogram/methods/decorators/on_bot_business_connect.py +++ b/pyrogram/methods/decorators/on_bot_business_connect.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.BotBusinessConnectHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_bot_business_message.py b/pyrogram/methods/decorators/on_bot_business_message.py index 6a81c529..7ae5a5c4 100644 --- a/pyrogram/methods/decorators/on_bot_business_message.py +++ b/pyrogram/methods/decorators/on_bot_business_message.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.BotBusinessMessageHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_callback_query.py b/pyrogram/methods/decorators/on_callback_query.py index 417492ab..f9f80ae9 100644 --- a/pyrogram/methods/decorators/on_callback_query.py +++ b/pyrogram/methods/decorators/on_callback_query.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.CallbackQueryHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_chat_join_request.py b/pyrogram/methods/decorators/on_chat_join_request.py index e9e0b38b..cf9af14b 100644 --- a/pyrogram/methods/decorators/on_chat_join_request.py +++ b/pyrogram/methods/decorators/on_chat_join_request.py @@ -38,7 +38,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.ChatJoinRequestHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_chat_member_updated.py b/pyrogram/methods/decorators/on_chat_member_updated.py index 6aea5702..022a64bb 100644 --- a/pyrogram/methods/decorators/on_chat_member_updated.py +++ b/pyrogram/methods/decorators/on_chat_member_updated.py @@ -38,7 +38,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.ChatMemberUpdatedHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_chosen_inline_result.py b/pyrogram/methods/decorators/on_chosen_inline_result.py index 83299c4a..d2ba5f29 100644 --- a/pyrogram/methods/decorators/on_chosen_inline_result.py +++ b/pyrogram/methods/decorators/on_chosen_inline_result.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.ChosenInlineResultHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_deleted_bot_business_messages.py b/pyrogram/methods/decorators/on_deleted_bot_business_messages.py index b58f583d..9e8db515 100644 --- a/pyrogram/methods/decorators/on_deleted_bot_business_messages.py +++ b/pyrogram/methods/decorators/on_deleted_bot_business_messages.py @@ -11,7 +11,9 @@ class OnDeletedBotBusinessMessages: def on_deleted_bot_business_messages( - self=None, filters=None, group: int = 0 + self=None, + filters=None, + group: int = 0, ) -> Callable: """Decorator for handling deleted bot business messages. @@ -31,7 +33,8 @@ def decorator(func: Callable) -> Callable: if isinstance(self, pyrogram.Client): self.add_handler( pyrogram.handlers.DeletedBotBusinessMessagesHandler( - func, filters + func, + filters, ), group, ) @@ -42,10 +45,11 @@ def decorator(func: Callable) -> Callable: func.handlers.append( ( pyrogram.handlers.DeletedBotBusinessMessagesHandler( - func, self + func, + self, ), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_deleted_messages.py b/pyrogram/methods/decorators/on_deleted_messages.py index ac8d7bba..b66d40cf 100644 --- a/pyrogram/methods/decorators/on_deleted_messages.py +++ b/pyrogram/methods/decorators/on_deleted_messages.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.DeletedMessagesHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_edited_bot_business_message.py b/pyrogram/methods/decorators/on_edited_bot_business_message.py index eb794581..4cdce24d 100644 --- a/pyrogram/methods/decorators/on_edited_bot_business_message.py +++ b/pyrogram/methods/decorators/on_edited_bot_business_message.py @@ -11,7 +11,9 @@ class OnEditedBotBusinessMessage: def on_edited_bot_business_message( - self=None, filters=None, group: int = 0 + self=None, + filters=None, + group: int = 0, ) -> Callable: """Decorator for handling edited messages. @@ -40,10 +42,11 @@ def decorator(func: Callable) -> Callable: func.handlers.append( ( pyrogram.handlers.EditedBotBusinessMessageHandler( - func, self + func, + self, ), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_edited_message.py b/pyrogram/methods/decorators/on_edited_message.py index 79156baa..8d433bb4 100644 --- a/pyrogram/methods/decorators/on_edited_message.py +++ b/pyrogram/methods/decorators/on_edited_message.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.EditedMessageHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_inline_query.py b/pyrogram/methods/decorators/on_inline_query.py index 0c6e1d77..78e206a2 100644 --- a/pyrogram/methods/decorators/on_inline_query.py +++ b/pyrogram/methods/decorators/on_inline_query.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.InlineQueryHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_message.py b/pyrogram/methods/decorators/on_message.py index 1077eaf4..c33404e8 100644 --- a/pyrogram/methods/decorators/on_message.py +++ b/pyrogram/methods/decorators/on_message.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.MessageHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_message_reaction_count_updated.py b/pyrogram/methods/decorators/on_message_reaction_count_updated.py index 295280e2..5f6a8c0d 100644 --- a/pyrogram/methods/decorators/on_message_reaction_count_updated.py +++ b/pyrogram/methods/decorators/on_message_reaction_count_updated.py @@ -11,7 +11,9 @@ class OnMessageReactionCountUpdated: def on_message_reaction_count_updated( - self=None, filters=None, group: int = 0 + self=None, + filters=None, + group: int = 0, ) -> Callable: """Decorator for handling anonymous reaction changes on messages. @@ -30,7 +32,8 @@ def decorator(func: Callable) -> Callable: if isinstance(self, pyrogram.Client): self.add_handler( pyrogram.handlers.MessageReactionCountUpdatedHandler( - func, filters + func, + filters, ), group, ) @@ -41,10 +44,11 @@ def decorator(func: Callable) -> Callable: func.handlers.append( ( pyrogram.handlers.MessageReactionCountUpdatedHandler( - func, self + func, + self, ), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_message_reaction_updated.py b/pyrogram/methods/decorators/on_message_reaction_updated.py index 9379e5d5..23dabae3 100644 --- a/pyrogram/methods/decorators/on_message_reaction_updated.py +++ b/pyrogram/methods/decorators/on_message_reaction_updated.py @@ -11,7 +11,9 @@ class OnMessageReactionUpdated: def on_message_reaction_updated( - self=None, filters=None, group: int = 0 + self=None, + filters=None, + group: int = 0, ) -> Callable: """Decorator for handling reaction changes on messages. @@ -40,7 +42,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.MessageReactionUpdatedHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_poll.py b/pyrogram/methods/decorators/on_poll.py index d77cfaab..24d2d7ed 100644 --- a/pyrogram/methods/decorators/on_poll.py +++ b/pyrogram/methods/decorators/on_poll.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.PollHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_pre_checkout_query.py b/pyrogram/methods/decorators/on_pre_checkout_query.py index 9b4427bf..880a3d5b 100644 --- a/pyrogram/methods/decorators/on_pre_checkout_query.py +++ b/pyrogram/methods/decorators/on_pre_checkout_query.py @@ -43,7 +43,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.PreCheckoutQueryHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_raw_update.py b/pyrogram/methods/decorators/on_raw_update.py index 3c8ab884..262c8040 100644 --- a/pyrogram/methods/decorators/on_raw_update.py +++ b/pyrogram/methods/decorators/on_raw_update.py @@ -28,7 +28,7 @@ def decorator(func: Callable) -> Callable: func.handlers = [] func.handlers.append( - (pyrogram.handlers.RawUpdateHandler(func), group) + (pyrogram.handlers.RawUpdateHandler(func), group), ) return func diff --git a/pyrogram/methods/decorators/on_shipping_query.py b/pyrogram/methods/decorators/on_shipping_query.py index 91d3b8d8..4a83d0a6 100644 --- a/pyrogram/methods/decorators/on_shipping_query.py +++ b/pyrogram/methods/decorators/on_shipping_query.py @@ -44,7 +44,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.ShippingQueryHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_story.py b/pyrogram/methods/decorators/on_story.py index 31c54ea0..d74d33c4 100644 --- a/pyrogram/methods/decorators/on_story.py +++ b/pyrogram/methods/decorators/on_story.py @@ -39,7 +39,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.StoryHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/decorators/on_user_status.py b/pyrogram/methods/decorators/on_user_status.py index 04134577..087f5541 100644 --- a/pyrogram/methods/decorators/on_user_status.py +++ b/pyrogram/methods/decorators/on_user_status.py @@ -37,7 +37,7 @@ def decorator(func: Callable) -> Callable: ( pyrogram.handlers.UserStatusHandler(func, self), group if filters is None else filters, - ) + ), ) return func diff --git a/pyrogram/methods/invite_links/approve_all_chat_join_requests.py b/pyrogram/methods/invite_links/approve_all_chat_join_requests.py index 3e5c2b48..fe3771da 100644 --- a/pyrogram/methods/invite_links/approve_all_chat_join_requests.py +++ b/pyrogram/methods/invite_links/approve_all_chat_join_requests.py @@ -32,7 +32,7 @@ async def approve_all_chat_join_requests( peer=await self.resolve_peer(chat_id), approved=True, link=invite_link, - ) + ), ) return True diff --git a/pyrogram/methods/invite_links/approve_chat_join_request.py b/pyrogram/methods/invite_links/approve_chat_join_request.py index 530d1e39..c3309c5c 100644 --- a/pyrogram/methods/invite_links/approve_chat_join_request.py +++ b/pyrogram/methods/invite_links/approve_chat_join_request.py @@ -35,7 +35,7 @@ async def approve_chat_join_request( peer=await self.resolve_peer(chat_id), user_id=await self.resolve_peer(user_id), approved=True, - ) + ), ) return True diff --git a/pyrogram/methods/invite_links/create_chat_invite_link.py b/pyrogram/methods/invite_links/create_chat_invite_link.py index 6ad71207..61f0997d 100644 --- a/pyrogram/methods/invite_links/create_chat_invite_link.py +++ b/pyrogram/methods/invite_links/create_chat_invite_link.py @@ -67,7 +67,7 @@ async def create_chat_invite_link( usage_limit=member_limit, title=name, request_needed=creates_join_request, - ) + ), ) return types.ChatInviteLink._parse(self, r) diff --git a/pyrogram/methods/invite_links/decline_all_chat_join_requests.py b/pyrogram/methods/invite_links/decline_all_chat_join_requests.py index 2fa9499a..fb3ee180 100644 --- a/pyrogram/methods/invite_links/decline_all_chat_join_requests.py +++ b/pyrogram/methods/invite_links/decline_all_chat_join_requests.py @@ -32,7 +32,7 @@ async def decline_all_chat_join_requests( peer=await self.resolve_peer(chat_id), approved=False, link=invite_link, - ) + ), ) return True diff --git a/pyrogram/methods/invite_links/decline_chat_join_request.py b/pyrogram/methods/invite_links/decline_chat_join_request.py index 57683adc..df8c3e99 100644 --- a/pyrogram/methods/invite_links/decline_chat_join_request.py +++ b/pyrogram/methods/invite_links/decline_chat_join_request.py @@ -35,7 +35,7 @@ async def decline_chat_join_request( peer=await self.resolve_peer(chat_id), user_id=await self.resolve_peer(user_id), approved=False, - ) + ), ) return True diff --git a/pyrogram/methods/invite_links/delete_chat_admin_invite_links.py b/pyrogram/methods/invite_links/delete_chat_admin_invite_links.py index 6291baf8..a6a4a6ee 100644 --- a/pyrogram/methods/invite_links/delete_chat_admin_invite_links.py +++ b/pyrogram/methods/invite_links/delete_chat_admin_invite_links.py @@ -34,5 +34,5 @@ async def delete_chat_admin_invite_links( raw.functions.messages.DeleteRevokedExportedChatInvites( peer=await self.resolve_peer(chat_id), admin_id=await self.resolve_peer(admin_id), - ) + ), ) diff --git a/pyrogram/methods/invite_links/delete_chat_invite_link.py b/pyrogram/methods/invite_links/delete_chat_invite_link.py index 14553789..2289e2e8 100644 --- a/pyrogram/methods/invite_links/delete_chat_invite_link.py +++ b/pyrogram/methods/invite_links/delete_chat_invite_link.py @@ -31,5 +31,5 @@ async def delete_chat_invite_link( raw.functions.messages.DeleteExportedChatInvite( peer=await self.resolve_peer(chat_id), link=invite_link, - ) + ), ) diff --git a/pyrogram/methods/invite_links/edit_chat_invite_link.py b/pyrogram/methods/invite_links/edit_chat_invite_link.py index 2251699a..95abfaf5 100644 --- a/pyrogram/methods/invite_links/edit_chat_invite_link.py +++ b/pyrogram/methods/invite_links/edit_chat_invite_link.py @@ -70,7 +70,7 @@ async def edit_chat_invite_link( usage_limit=member_limit, title=name, request_needed=creates_join_request, - ) + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/invite_links/export_chat_invite_link.py b/pyrogram/methods/invite_links/export_chat_invite_link.py index 595f8b89..db1351ad 100644 --- a/pyrogram/methods/invite_links/export_chat_invite_link.py +++ b/pyrogram/methods/invite_links/export_chat_invite_link.py @@ -54,7 +54,7 @@ async def export_chat_invite_link( period=subscription_period, amount=subscription_price, ), - ) + ), ) return types.ChatInviteLink._parse(self, r) diff --git a/pyrogram/methods/invite_links/get_chat_admin_invite_links.py b/pyrogram/methods/invite_links/get_chat_admin_invite_links.py index 0622064d..6bd775ed 100644 --- a/pyrogram/methods/invite_links/get_chat_admin_invite_links.py +++ b/pyrogram/methods/invite_links/get_chat_admin_invite_links.py @@ -68,7 +68,7 @@ async def get_chat_admin_invite_links( revoked=revoked, offset_date=offset_date, offset_link=offset_link, - ) + ), ) if not r.invites: diff --git a/pyrogram/methods/invite_links/get_chat_admin_invite_links_count.py b/pyrogram/methods/invite_links/get_chat_admin_invite_links_count.py index 3db19ec1..e0dbf6ac 100644 --- a/pyrogram/methods/invite_links/get_chat_admin_invite_links_count.py +++ b/pyrogram/methods/invite_links/get_chat_admin_invite_links_count.py @@ -40,7 +40,7 @@ async def get_chat_admin_invite_links_count( admin_id=await self.resolve_peer(admin_id), limit=1, revoked=revoked, - ) + ), ) return r.count diff --git a/pyrogram/methods/invite_links/get_chat_admins_with_invite_links.py b/pyrogram/methods/invite_links/get_chat_admins_with_invite_links.py index 6eaedb38..46cd2eb6 100644 --- a/pyrogram/methods/invite_links/get_chat_admins_with_invite_links.py +++ b/pyrogram/methods/invite_links/get_chat_admins_with_invite_links.py @@ -27,8 +27,8 @@ async def get_chat_admins_with_invite_links( """ r = await self.invoke( raw.functions.messages.GetAdminsWithInvites( - peer=await self.resolve_peer(chat_id) - ) + peer=await self.resolve_peer(chat_id), + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/invite_links/get_chat_invite_link.py b/pyrogram/methods/invite_links/get_chat_invite_link.py index 1033fd8a..1dfffe04 100644 --- a/pyrogram/methods/invite_links/get_chat_invite_link.py +++ b/pyrogram/methods/invite_links/get_chat_invite_link.py @@ -30,7 +30,7 @@ async def get_chat_invite_link( raw.functions.messages.GetExportedChatInvite( peer=await self.resolve_peer(chat_id), link=invite_link, - ) + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/invite_links/get_chat_invite_link_joiners.py b/pyrogram/methods/invite_links/get_chat_invite_link_joiners.py index bd224714..c80a0ef7 100644 --- a/pyrogram/methods/invite_links/get_chat_invite_link_joiners.py +++ b/pyrogram/methods/invite_links/get_chat_invite_link_joiners.py @@ -54,7 +54,7 @@ async def get_chat_invite_link_joiners( limit=limit, offset_date=offset_date, offset_user=offset_user, - ) + ), ) if not r.importers: diff --git a/pyrogram/methods/invite_links/get_chat_invite_link_joiners_count.py b/pyrogram/methods/invite_links/get_chat_invite_link_joiners_count.py index c35e4b71..0a18c96a 100644 --- a/pyrogram/methods/invite_links/get_chat_invite_link_joiners_count.py +++ b/pyrogram/methods/invite_links/get_chat_invite_link_joiners_count.py @@ -6,7 +6,9 @@ class GetChatInviteLinkJoinersCount: async def get_chat_invite_link_joiners_count( - self: pyrogram.Client, chat_id: int | str, invite_link: str + self: pyrogram.Client, + chat_id: int | str, + invite_link: str, ) -> int: """Get the count of the members who joined the chat with the invite link. @@ -31,7 +33,7 @@ async def get_chat_invite_link_joiners_count( limit=1, offset_date=0, offset_user=raw.types.InputUserEmpty(), - ) + ), ) return r.count diff --git a/pyrogram/methods/invite_links/get_chat_join_requests.py b/pyrogram/methods/invite_links/get_chat_join_requests.py index eff7153a..9b356a8d 100644 --- a/pyrogram/methods/invite_links/get_chat_join_requests.py +++ b/pyrogram/methods/invite_links/get_chat_join_requests.py @@ -55,7 +55,7 @@ async def get_chat_join_requests( offset_user=offset_user, requested=True, q=query, - ) + ), ) if not r.importers: diff --git a/pyrogram/methods/invite_links/revoke_chat_invite_link.py b/pyrogram/methods/invite_links/revoke_chat_invite_link.py index 94c0bb59..b5837df9 100644 --- a/pyrogram/methods/invite_links/revoke_chat_invite_link.py +++ b/pyrogram/methods/invite_links/revoke_chat_invite_link.py @@ -36,7 +36,7 @@ async def revoke_chat_invite_link( peer=await self.resolve_peer(chat_id), link=invite_link, revoked=True, - ) + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/messages/copy_media_group.py b/pyrogram/methods/messages/copy_media_group.py index b74fa16f..fb4eefe7 100644 --- a/pyrogram/methods/messages/copy_media_group.py +++ b/pyrogram/methods/messages/copy_media_group.py @@ -121,9 +121,9 @@ async def copy_media_group( if message.caption and message.caption != "None" and type(captions) is not str - else "" + else "", ), - ) + ), ) r = await self.invoke( diff --git a/pyrogram/methods/messages/copy_message.py b/pyrogram/methods/messages/copy_message.py index 9fb52ac1..3df514b6 100644 --- a/pyrogram/methods/messages/copy_message.py +++ b/pyrogram/methods/messages/copy_message.py @@ -25,6 +25,7 @@ async def copy_message( disable_notification: bool | None = None, message_thread_id: int | None = None, reply_to_message_id: int | None = None, + reply_to_chat_id: int | None = None, schedule_date: datetime | None = None, protect_content: bool | None = None, allow_paid_broadcast: bool | None = None, @@ -83,6 +84,11 @@ async def copy_message( reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. + reply_to_chat_id (``int``, *optional*): + Unique identifier for the origin chat. + for reply to message from another chat. + You can also use chat public link in form of *t.me/* (str). + schedule_date (:py:obj:`~datetime.datetime`, *optional*): Date when the message will be automatically sent. @@ -120,6 +126,7 @@ async def copy_message( disable_notification=disable_notification, message_thread_id=message_thread_id, reply_to_message_id=reply_to_message_id, + reply_to_chat_id=reply_to_chat_id, schedule_date=schedule_date, protect_content=protect_content, allow_paid_broadcast=allow_paid_broadcast, diff --git a/pyrogram/methods/messages/delete_chat_history.py b/pyrogram/methods/messages/delete_chat_history.py index a38e4fb4..631b1cd1 100644 --- a/pyrogram/methods/messages/delete_chat_history.py +++ b/pyrogram/methods/messages/delete_chat_history.py @@ -59,11 +59,12 @@ async def delete_chat_history( r = await self.invoke( raw.functions.channels.DeleteHistory( channel=raw.types.InputChannel( - channel_id=peer.channel_id, access_hash=peer.access_hash + channel_id=peer.channel_id, + access_hash=peer.access_hash, ), max_id=max_id, for_everyone=revoke, - ) + ), ) else: r = await self.invoke( @@ -74,7 +75,7 @@ async def delete_chat_history( revoke=revoke, min_date=utils.datetime_to_timestamp(min_date), max_date=utils.datetime_to_timestamp(max_date), - ) + ), ) return ( diff --git a/pyrogram/methods/messages/delete_messages.py b/pyrogram/methods/messages/delete_messages.py index 18df8229..8a02f4e4 100644 --- a/pyrogram/methods/messages/delete_messages.py +++ b/pyrogram/methods/messages/delete_messages.py @@ -58,11 +58,11 @@ async def delete_messages( if isinstance(peer, raw.types.InputPeerChannel): r = await self.invoke( - raw.functions.channels.DeleteMessages(channel=peer, id=message_ids) + raw.functions.channels.DeleteMessages(channel=peer, id=message_ids), ) else: r = await self.invoke( - raw.functions.messages.DeleteMessages(id=message_ids, revoke=revoke) + raw.functions.messages.DeleteMessages(id=message_ids, revoke=revoke), ) return r.pts_count diff --git a/pyrogram/methods/messages/delete_scheduled_messages.py b/pyrogram/methods/messages/delete_scheduled_messages.py index 6ab034f9..0b336067 100644 --- a/pyrogram/methods/messages/delete_scheduled_messages.py +++ b/pyrogram/methods/messages/delete_scheduled_messages.py @@ -11,7 +11,9 @@ class DeleteScheduledMessages: async def delete_scheduled_messages( - self: pyrogram.Client, chat_id: int | str, message_ids: int | Iterable[int] + self: pyrogram.Client, + chat_id: int | str, + message_ids: int | Iterable[int], ) -> int: """Delete scheduled messages. @@ -43,7 +45,7 @@ async def delete_scheduled_messages( message_ids = list(message_ids) if is_iterable else [message_ids] r = await self.invoke( - raw.functions.channels.DeleteMessages(peer=peer, id=message_ids) + raw.functions.channels.DeleteMessages(peer=peer, id=message_ids), ) return r.messages if is_iterable else r.messages[0] diff --git a/pyrogram/methods/messages/download_media.py b/pyrogram/methods/messages/download_media.py index 76735d72..3884fd19 100644 --- a/pyrogram/methods/messages/download_media.py +++ b/pyrogram/methods/messages/download_media.py @@ -127,7 +127,7 @@ async def progress(current, total): break else: raise ValueError( - "This message doesn't contain any downloadable media" + "This message doesn't contain any downloadable media", ) else: media = message @@ -186,7 +186,7 @@ async def progress(current, total): file_size, progress, progress_args, - ) + ), ) if block: diff --git a/pyrogram/methods/messages/edit_inline_media.py b/pyrogram/methods/messages/edit_inline_media.py index f111889b..cd262b53 100644 --- a/pyrogram/methods/messages/edit_inline_media.py +++ b/pyrogram/methods/messages/edit_inline_media.py @@ -66,7 +66,8 @@ async def edit_inline_media( is_uploaded_file = is_bytes_io or Path(media.media).is_file() is_external_url = not is_uploaded_file and re.match( - "^https?://", media.media + "^https?://", + media.media, ) if is_bytes_io and not hasattr(media.media, "name"): @@ -77,8 +78,8 @@ async def edit_inline_media( raw.types.DocumentAttributeFilename( file_name=media.media.name if is_bytes_io - else Path(media.media).name - ) + else Path(media.media).name, + ), ] else: filename_attribute = [] @@ -91,11 +92,13 @@ async def edit_inline_media( ) elif is_external_url: media = raw.types.InputMediaPhotoExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.PHOTO + media.media, + FileType.PHOTO, ) elif isinstance(media, types.InputMediaVideo): if is_uploaded_file: @@ -119,11 +122,13 @@ async def edit_inline_media( ) elif is_external_url: media = raw.types.InputMediaDocumentExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.VIDEO + media.media, + FileType.VIDEO, ) elif isinstance(media, types.InputMediaAudio): if is_uploaded_file: @@ -147,7 +152,8 @@ async def edit_inline_media( media = raw.types.InputMediaDocumentExternal(url=media.media) else: media = utils.get_input_media_from_file_id( - media.media, FileType.AUDIO + media.media, + FileType.AUDIO, ) elif isinstance(media, types.InputMediaAnimation): if is_uploaded_file: @@ -173,11 +179,13 @@ async def edit_inline_media( ) elif is_external_url: media = raw.types.InputMediaDocumentExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.ANIMATION + media.media, + FileType.ANIMATION, ) elif isinstance(media, types.InputMediaDocument): if is_uploaded_file: @@ -195,7 +203,8 @@ async def edit_inline_media( media = raw.types.InputMediaDocumentExternal(url=media.media) else: media = utils.get_input_media_from_file_id( - media.media, FileType.DOCUMENT + media.media, + FileType.DOCUMENT, ) unpacked = utils.unpack_inline_message_id(inline_message_id) @@ -206,8 +215,9 @@ async def edit_inline_media( if is_uploaded_file: uploaded_media = await self.invoke( raw.functions.messages.UploadMedia( - peer=raw.types.InputPeerSelf(), media=media - ) + peer=raw.types.InputPeerSelf(), + media=media, + ), ) actual_media = ( diff --git a/pyrogram/methods/messages/edit_inline_text.py b/pyrogram/methods/messages/edit_inline_text.py index 89b2c9a1..afb5480c 100644 --- a/pyrogram/methods/messages/edit_inline_text.py +++ b/pyrogram/methods/messages/edit_inline_text.py @@ -71,7 +71,7 @@ async def edit_inline_text( if reply_markup else None, **await self.parser.parse(text, parse_mode), + invert_media=invert_media, ), sleep_threshold=self.sleep_threshold, - invert_media=invert_media, ) diff --git a/pyrogram/methods/messages/edit_message_media.py b/pyrogram/methods/messages/edit_message_media.py index 4abdd96b..dbee0e91 100644 --- a/pyrogram/methods/messages/edit_message_media.py +++ b/pyrogram/methods/messages/edit_message_media.py @@ -82,7 +82,10 @@ async def edit_message_media( if caption is not None: message, entities = ( await utils.parse_text_entities( - self, caption, parse_mode, caption_entities + self, + caption, + parse_mode, + caption_entities, ) ).values() @@ -95,7 +98,7 @@ async def edit_message_media( file=await self.save_file(media.media), spoiler=media.has_spoiler, ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -108,11 +111,13 @@ async def edit_message_media( ) elif re.match("^https?://", media.media): media = raw.types.InputMediaPhotoExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.PHOTO + media.media, + FileType.PHOTO, ) elif isinstance(media, types.InputMediaVideo): if isinstance(media.media, io.BytesIO) or Path(media.media).is_file(): @@ -134,11 +139,11 @@ async def edit_message_media( h=media.height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(media.media).name + file_name=file_name or Path(media.media).name, ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -151,11 +156,13 @@ async def edit_message_media( ) elif re.match("^https?://", media.media): media = raw.types.InputMediaDocumentExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.VIDEO + media.media, + FileType.VIDEO, ) elif isinstance(media, types.InputMediaAudio): if isinstance(media.media, io.BytesIO) or Path(media.media).is_file(): @@ -174,11 +181,11 @@ async def edit_message_media( title=media.title, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(media.media).name + file_name=file_name or Path(media.media).name, ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -186,13 +193,14 @@ async def edit_message_media( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif re.match("^https?://", media.media): media = raw.types.InputMediaDocumentExternal(url=media.media) else: media = utils.get_input_media_from_file_id( - media.media, FileType.AUDIO + media.media, + FileType.AUDIO, ) elif isinstance(media, types.InputMediaAnimation): if isinstance(media.media, io.BytesIO) or Path(media.media).is_file(): @@ -213,12 +221,12 @@ async def edit_message_media( h=media.height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(media.media).name + file_name=file_name or Path(media.media).name, ), raw.types.DocumentAttributeAnimated(), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -231,11 +239,13 @@ async def edit_message_media( ) elif re.match("^https?://", media.media): media = raw.types.InputMediaDocumentExternal( - url=media.media, spoiler=media.has_spoiler + url=media.media, + spoiler=media.has_spoiler, ) else: media = utils.get_input_media_from_file_id( - media.media, FileType.ANIMATION + media.media, + FileType.ANIMATION, ) elif isinstance(media, types.InputMediaDocument): if isinstance(media.media, io.BytesIO) or Path(media.media).is_file(): @@ -249,11 +259,11 @@ async def edit_message_media( file=await self.save_file(media.media), attributes=[ raw.types.DocumentAttributeFilename( - file_name=file_name or Path(media.media).name - ) + file_name=file_name or Path(media.media).name, + ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -261,13 +271,14 @@ async def edit_message_media( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif re.match("^https?://", media.media): media = raw.types.InputMediaDocumentExternal(url=media.media) else: media = utils.get_input_media_from_file_id( - media.media, FileType.DOCUMENT + media.media, + FileType.DOCUMENT, ) rpc = raw.functions.messages.EditMessage( @@ -282,8 +293,9 @@ async def edit_message_media( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/edit_message_reply_markup.py b/pyrogram/methods/messages/edit_message_reply_markup.py index 49765d6d..40be9259 100644 --- a/pyrogram/methods/messages/edit_message_reply_markup.py +++ b/pyrogram/methods/messages/edit_message_reply_markup.py @@ -55,8 +55,9 @@ async def edit_message_reply_markup( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/edit_message_text.py b/pyrogram/methods/messages/edit_message_text.py index 6dfa88b0..24d8f2f8 100644 --- a/pyrogram/methods/messages/edit_message_text.py +++ b/pyrogram/methods/messages/edit_message_text.py @@ -80,8 +80,9 @@ async def edit_message_text( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/forward_messages.py b/pyrogram/methods/messages/forward_messages.py index 8c6a3ac1..236cd1a3 100644 --- a/pyrogram/methods/messages/forward_messages.py +++ b/pyrogram/methods/messages/forward_messages.py @@ -92,7 +92,7 @@ async def forward_messages( noforwards=protect_content, allow_paid_floodskip=allow_paid_broadcast, drop_author=drop_author, - ) + ), ) users = {i.id: i for i in r.users} diff --git a/pyrogram/methods/messages/get_available_effects.py b/pyrogram/methods/messages/get_available_effects.py index 8e6b47e6..b13ee459 100644 --- a/pyrogram/methods/messages/get_available_effects.py +++ b/pyrogram/methods/messages/get_available_effects.py @@ -37,5 +37,5 @@ async def get_available_effects( documents.get(effect.effect_sticker_id, None), ) for effect in r.effects - ] + ], ) diff --git a/pyrogram/methods/messages/get_chat_history.py b/pyrogram/methods/messages/get_chat_history.py index 88ed0fe4..ac5b69f2 100644 --- a/pyrogram/methods/messages/get_chat_history.py +++ b/pyrogram/methods/messages/get_chat_history.py @@ -17,10 +17,12 @@ async def get_chunk( limit: int = 0, offset: int = 0, from_message_id: int = 0, - from_date: datetime = utils.zero_datetime(), + from_date: datetime | None = None, min_id: int = 0, max_id: int = 0, ): + if from_date is None: + from_date = utils.zero_datetime() messages = await client.invoke( raw.functions.messages.GetHistory( peer=await client.resolve_peer(chat_id), @@ -45,7 +47,7 @@ async def get_chat_history( limit: int = 0, offset: int = 0, offset_id: int = 0, - offset_date: datetime = utils.zero_datetime(), + offset_date: datetime | None = None, min_id: int = 0, max_id: int = 0, ) -> AsyncGenerator[types.Message, None] | None: @@ -91,6 +93,8 @@ async def get_chat_history( async for message in app.get_chat_history(chat_id): print(message.text) """ + if offset_date is None: + offset_date = utils.zero_datetime() current = 0 total = limit or (1 << 31) - 1 limit = min(100, total) diff --git a/pyrogram/methods/messages/get_chat_history_count.py b/pyrogram/methods/messages/get_chat_history_count.py index b6ff41cc..e84da141 100644 --- a/pyrogram/methods/messages/get_chat_history_count.py +++ b/pyrogram/methods/messages/get_chat_history_count.py @@ -10,7 +10,8 @@ class GetChatHistoryCount: async def get_chat_history_count( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> int: """Get the total count of messages in a chat. @@ -46,7 +47,7 @@ async def get_chat_history_count( max_id=0, min_id=0, hash=0, - ) + ), ) if isinstance(r, raw.types.messages.Messages): diff --git a/pyrogram/methods/messages/get_custom_emoji_stickers.py b/pyrogram/methods/messages/get_custom_emoji_stickers.py index 01435eae..2d70b321 100644 --- a/pyrogram/methods/messages/get_custom_emoji_stickers.py +++ b/pyrogram/methods/messages/get_custom_emoji_stickers.py @@ -27,8 +27,8 @@ async def get_custom_emoji_stickers( result = await self.invoke( raw.functions.messages.GetCustomEmojiDocuments( - document_id=custom_emoji_ids - ) + document_id=custom_emoji_ids, + ), ) stickers = pyrogram.types.List() diff --git a/pyrogram/methods/messages/get_discussion_message.py b/pyrogram/methods/messages/get_discussion_message.py index 69f8ab2c..c2ea7d27 100644 --- a/pyrogram/methods/messages/get_discussion_message.py +++ b/pyrogram/methods/messages/get_discussion_message.py @@ -38,7 +38,7 @@ async def get_discussion_message( raw.functions.messages.GetDiscussionMessage( peer=await self.resolve_peer(chat_id), msg_id=message_id, - ) + ), ) users = {u.id: u for u in r.users} diff --git a/pyrogram/methods/messages/get_discussion_replies.py b/pyrogram/methods/messages/get_discussion_replies.py index 98e74a99..a7c243e2 100644 --- a/pyrogram/methods/messages/get_discussion_replies.py +++ b/pyrogram/methods/messages/get_discussion_replies.py @@ -55,7 +55,7 @@ async def get_discussion_replies( max_id=0, min_id=0, hash=0, - ) + ), ) users = {u.id: u for u in r.users} @@ -67,7 +67,11 @@ async def get_discussion_replies( for message in messages: yield await types.Message._parse( - self, message, users, chats, replies=0 + self, + message, + users, + chats, + replies=0, ) current += 1 diff --git a/pyrogram/methods/messages/get_discussion_replies_count.py b/pyrogram/methods/messages/get_discussion_replies_count.py index 3e05b290..92b29865 100644 --- a/pyrogram/methods/messages/get_discussion_replies_count.py +++ b/pyrogram/methods/messages/get_discussion_replies_count.py @@ -39,7 +39,7 @@ async def get_discussion_replies_count( max_id=0, min_id=0, hash=0, - ) + ), ) return r.count diff --git a/pyrogram/methods/messages/get_media_group.py b/pyrogram/methods/messages/get_media_group.py index 3ec274fb..fc6037f4 100644 --- a/pyrogram/methods/messages/get_media_group.py +++ b/pyrogram/methods/messages/get_media_group.py @@ -10,7 +10,9 @@ class GetMediaGroup: async def get_media_group( - self: pyrogram.Client, chat_id: int | str, message_id: int + self: pyrogram.Client, + chat_id: int | str, + message_id: int, ) -> list[types.Message]: """Get the media group a message belongs to. diff --git a/pyrogram/methods/messages/get_messages.py b/pyrogram/methods/messages/get_messages.py index e0204199..a19e6dc7 100644 --- a/pyrogram/methods/messages/get_messages.py +++ b/pyrogram/methods/messages/get_messages.py @@ -29,10 +29,10 @@ async def get_messages( .. include:: /_includes/usable-by/users-bots.rst - You must use exactly one of ``chat_id`` OR ``link``. + You must use exactly one of ``message_ids`` OR (``chat_id``, ``message_ids``) OR (``chat_id``, ``reply_to_message_ids``) OR ``link``. Parameters: - chat_id (``int`` | ``str``): + chat_id (``int`` | ``str``, *optional*): Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) you can simply use "me" or "self". For a contact that exists in your Telegram address book you can use his phone number (str). @@ -54,7 +54,7 @@ async def get_messages( is_scheduled (``bool``, *optional*): Whether to get scheduled messages. Defaults to False. - link (``str``): + link (``str``, *optional*): A link of the message, usually can be copied using ``Copy Link`` functionality OR obtained using :obj:`~pyrogram.raw.types.Message.link` OR :obj:`~pyrogram.raw.functions.channels.ExportMessageLink` Returns: @@ -79,6 +79,9 @@ async def get_messages( # Get the replied-to message of a message await app.get_messages(chat_id=chat_id, reply_to_message_ids=message_id) + # Get message from link + await app.get_messages(link=link) + Raises: ValueError: In case of invalid arguments. """ @@ -93,7 +96,7 @@ async def get_messages( if ids is None: raise ValueError( - "No argument supplied. Either pass message_ids or reply_to_message_ids" + "No argument supplied. Either pass message_ids or reply_to_message_ids", ) peer = await self.resolve_peer(chat_id) @@ -136,7 +139,7 @@ async def get_messages( elif not self.me.is_bot and len(linkps) == 5 and linkps[3] == "m": r = await self.invoke( - raw.functions.account.ResolveBusinessChatLink(slug=linkps[4]) + raw.functions.account.ResolveBusinessChatLink(slug=linkps[4]), ) users = {i.id: i for i in r.users} entities = [ @@ -159,14 +162,15 @@ async def get_messages( raw_chat_id = linkps[3] if raw_chat_id == "m": raise ValueError( - "Invalid ClientType used to parse this message link" + "Invalid ClientType used to parse this message link", ) message_id = int(linkps[4]) return await self.get_messages( - chat_id=raw_chat_id, message_ids=message_id + chat_id=raw_chat_id, + message_ids=message_id, ) raise ValueError( - "No argument supplied. Either pass link OR (chat_id, message_ids or reply_to_message_ids)" + "No argument supplied. Either pass link OR (chat_id, message_ids or reply_to_message_ids)", ) diff --git a/pyrogram/methods/messages/get_scheduled_messages.py b/pyrogram/methods/messages/get_scheduled_messages.py index 2dac43c6..7f076263 100644 --- a/pyrogram/methods/messages/get_scheduled_messages.py +++ b/pyrogram/methods/messages/get_scheduled_messages.py @@ -14,7 +14,9 @@ class GetScheduledMessages: async def get_scheduled_messages( - self: pyrogram.Client, chat_id: int | str, message_ids: int | Iterable[int] + self: pyrogram.Client, + chat_id: int | str, + message_ids: int | Iterable[int], ) -> types.Message | list[types.Message]: """Get one or more scheduled messages from a chat by using message identifiers. You can retrieve up to 200 messages at once. diff --git a/pyrogram/methods/messages/inline_session.py b/pyrogram/methods/messages/inline_session.py index 22f9e18b..71f805fb 100644 --- a/pyrogram/methods/messages/inline_session.py +++ b/pyrogram/methods/messages/inline_session.py @@ -30,14 +30,15 @@ async def get_session(client: pyrogram.Client, dc_id: int): for _ in range(3): exported_auth = await client.invoke( - raw.functions.auth.ExportAuthorization(dc_id=dc_id) + raw.functions.auth.ExportAuthorization(dc_id=dc_id), ) try: await session.invoke( raw.functions.auth.ImportAuthorization( - id=exported_auth.id, bytes=exported_auth.bytes - ) + id=exported_auth.id, + bytes=exported_auth.bytes, + ), ) except AuthBytesInvalid: continue diff --git a/pyrogram/methods/messages/read_chat_history.py b/pyrogram/methods/messages/read_chat_history.py index be711244..c5c958e1 100644 --- a/pyrogram/methods/messages/read_chat_history.py +++ b/pyrogram/methods/messages/read_chat_history.py @@ -6,7 +6,9 @@ class ReadChatHistory: async def read_chat_history( - self: pyrogram.Client, chat_id: int | str, max_id: int = 0 + self: pyrogram.Client, + chat_id: int | str, + max_id: int = 0, ) -> bool: """Mark a chat's message history as read. diff --git a/pyrogram/methods/messages/retract_vote.py b/pyrogram/methods/messages/retract_vote.py index 3ada2d7b..5da18ba6 100644 --- a/pyrogram/methods/messages/retract_vote.py +++ b/pyrogram/methods/messages/retract_vote.py @@ -6,7 +6,9 @@ class RetractVote: async def retract_vote( - self: pyrogram.Client, chat_id: int | str, message_id: int + self: pyrogram.Client, + chat_id: int | str, + message_id: int, ) -> types.Poll: """Retract your vote in a poll. @@ -35,7 +37,7 @@ async def retract_vote( peer=await self.resolve_peer(chat_id), msg_id=message_id, options=[], - ) + ), ) return await types.Poll._parse(self, r.updates[0], r.users) diff --git a/pyrogram/methods/messages/search_global_count.py b/pyrogram/methods/messages/search_global_count.py index a68f3dfe..8d99209b 100644 --- a/pyrogram/methods/messages/search_global_count.py +++ b/pyrogram/methods/messages/search_global_count.py @@ -37,7 +37,7 @@ async def search_global_count( offset_peer=raw.types.InputPeerEmpty(), offset_id=0, limit=1, - ) + ), ) if hasattr(r, "count"): diff --git a/pyrogram/methods/messages/search_global_hashtag_messages.py b/pyrogram/methods/messages/search_global_hashtag_messages.py index df76fc02..949eb667 100644 --- a/pyrogram/methods/messages/search_global_hashtag_messages.py +++ b/pyrogram/methods/messages/search_global_hashtag_messages.py @@ -15,7 +15,7 @@ async def search_global_hashtag_messages( self: pyrogram.Client, hashtag: str = "", offset_id: int = 0, - offset_date: datetime = utils.zero_datetime(), + offset_date: datetime | None = None, limit: int = 0, ) -> AsyncGenerator[types.Message, None]: """Searches for public channel posts with the given hashtag. For optimal performance, the number of returned messages is chosen by Telegram Server and can be smaller than the specified limit. @@ -49,6 +49,8 @@ async def search_global_hashtag_messages( print(message.text) """ + if offset_date is None: + offset_date = utils.zero_datetime() current = 0 total = abs(limit) or (1 << 31) limit = min(100, total) diff --git a/pyrogram/methods/messages/search_global_hashtag_messages_count.py b/pyrogram/methods/messages/search_global_hashtag_messages_count.py index cd2f8b90..e0832216 100644 --- a/pyrogram/methods/messages/search_global_hashtag_messages_count.py +++ b/pyrogram/methods/messages/search_global_hashtag_messages_count.py @@ -30,7 +30,7 @@ async def search_global_hashtag_messages_count( offset_peer=raw.types.InputPeerEmpty(), offset_id=0, limit=1, - ) + ), ) if hasattr(r, "count"): diff --git a/pyrogram/methods/messages/search_messages_count.py b/pyrogram/methods/messages/search_messages_count.py index 4dab8db8..57303442 100644 --- a/pyrogram/methods/messages/search_messages_count.py +++ b/pyrogram/methods/messages/search_messages_count.py @@ -59,7 +59,7 @@ async def search_messages_count( from_id=(await self.resolve_peer(from_user) if from_user else None), hash=0, top_msg_id=thread_id, - ) + ), ) if hasattr(r, "count"): diff --git a/pyrogram/methods/messages/send_animation.py b/pyrogram/methods/messages/send_animation.py index e5dacfb2..c5800721 100644 --- a/pyrogram/methods/messages/send_animation.py +++ b/pyrogram/methods/messages/send_animation.py @@ -119,7 +119,7 @@ async def send_animation( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -234,18 +234,20 @@ async def progress(current, total): h=height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(animation).name + file_name=file_name or Path(animation).name, ), raw.types.DocumentAttributeAnimated(), ], ) elif re.match("^https?://", animation): media = raw.types.InputMediaDocumentExternal( - url=animation, spoiler=has_spoiler + url=animation, + spoiler=has_spoiler, ) else: media = utils.get_input_media_from_file_id( - animation, FileType.ANIMATION + animation, + FileType.ANIMATION, ) media.spoiler = has_spoiler else: @@ -269,7 +271,7 @@ async def progress(current, total): h=height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or animation.name + file_name=file_name or animation.name, ), raw.types.DocumentAttributeAnimated(), ], @@ -303,13 +305,15 @@ async def progress(current, total): raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) except FilePartMissing as e: await self.save_file( - animation, file_id=file.id, file_part=e.value + animation, + file_id=file.id, + file_part=e.value, ) else: for i in r.updates: @@ -341,8 +345,9 @@ async def progress(current, total): await self.invoke( raw.functions.messages.SaveGif( - id=document_id, unsave=True - ) + id=document_id, + unsave=True, + ), ) return message diff --git a/pyrogram/methods/messages/send_audio.py b/pyrogram/methods/messages/send_audio.py index d2357e2e..1fb57a00 100644 --- a/pyrogram/methods/messages/send_audio.py +++ b/pyrogram/methods/messages/send_audio.py @@ -111,7 +111,7 @@ async def send_audio( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -222,7 +222,7 @@ async def progress(current, total): title=title, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(audio).name + file_name=file_name or Path(audio).name, ), ], ) @@ -249,7 +249,7 @@ async def progress(current, total): title=title, ), raw.types.DocumentAttributeFilename( - file_name=file_name or audio.name + file_name=file_name or audio.name, ), ], ) @@ -281,7 +281,7 @@ async def progress(current, total): raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_cached_media.py b/pyrogram/methods/messages/send_cached_media.py index 79b9ff7f..13a071a4 100644 --- a/pyrogram/methods/messages/send_cached_media.py +++ b/pyrogram/methods/messages/send_cached_media.py @@ -78,7 +78,7 @@ async def send_cached_media( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -151,9 +151,12 @@ async def send_cached_media( if reply_markup else None, **await utils.parse_text_entities( - self, caption, parse_mode, caption_entities + self, + caption, + parse_mode, + caption_entities, ), - ) + ), ) for i in r.updates: diff --git a/pyrogram/methods/messages/send_chat_action.py b/pyrogram/methods/messages/send_chat_action.py index bb7cdc80..ceb7ebad 100644 --- a/pyrogram/methods/messages/send_chat_action.py +++ b/pyrogram/methods/messages/send_chat_action.py @@ -86,7 +86,7 @@ async def send_chat_action( raise ValueError("Invalid Argument Provided") if emoji_message_interaction is None: _, sticker_set = await self._get_raw_stickers( - raw.types.InputStickerSetAnimatedEmojiAnimations() + raw.types.InputStickerSetAnimatedEmojiAnimations(), ) emoji_message_interaction = raw.types.DataJSON( data=dumps( @@ -96,10 +96,10 @@ async def send_chat_action( { "t": 0, "i": randint(1, sticker_set.count), - } + }, ], - } - ) + }, + ), ) action = action.value( emoticon=emoji, @@ -116,7 +116,8 @@ async def send_chat_action( if business_connection_id: return await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) return await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_contact.py b/pyrogram/methods/messages/send_contact.py index 5b0d2e92..8c71f143 100644 --- a/pyrogram/methods/messages/send_contact.py +++ b/pyrogram/methods/messages/send_contact.py @@ -147,8 +147,9 @@ async def send_contact( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_dice.py b/pyrogram/methods/messages/send_dice.py index 762cb21d..75297f08 100644 --- a/pyrogram/methods/messages/send_dice.py +++ b/pyrogram/methods/messages/send_dice.py @@ -66,7 +66,7 @@ async def send_dice( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -146,8 +146,9 @@ async def send_dice( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_document.py b/pyrogram/methods/messages/send_document.py index 05b9d139..40e631bd 100644 --- a/pyrogram/methods/messages/send_document.py +++ b/pyrogram/methods/messages/send_document.py @@ -103,7 +103,7 @@ async def send_document( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -206,15 +206,16 @@ async def progress(current, total): thumb=thumb, attributes=[ raw.types.DocumentAttributeFilename( - file_name=file_name or Path(document).name - ) + file_name=file_name or Path(document).name, + ), ], ) elif re.match("^https?://", document): media = raw.types.InputMediaDocumentExternal(url=document) else: media = utils.get_input_media_from_file_id( - document, FileType.DOCUMENT + document, + FileType.DOCUMENT, ) else: thumb = await self.save_file(thumb) @@ -230,8 +231,8 @@ async def progress(current, total): thumb=thumb, attributes=[ raw.types.DocumentAttributeFilename( - file_name=file_name or document.name - ) + file_name=file_name or document.name, + ), ], ) @@ -262,13 +263,15 @@ async def progress(current, total): raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) except FilePartMissing as e: await self.save_file( - document, file_id=file.id, file_part=e.value + document, + file_id=file.id, + file_part=e.value, ) else: for i in r.updates: diff --git a/pyrogram/methods/messages/send_location.py b/pyrogram/methods/messages/send_location.py index 4510c01d..0626d6fe 100644 --- a/pyrogram/methods/messages/send_location.py +++ b/pyrogram/methods/messages/send_location.py @@ -130,7 +130,7 @@ async def send_location( lat=latitude, long=longitude, accuracy_radius=horizontal_accuracy, - ) + ), ), message="", silent=disable_notification or None, @@ -145,8 +145,9 @@ async def send_location( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_media_group.py b/pyrogram/methods/messages/send_media_group.py index 5a9fc736..bebd27d0 100644 --- a/pyrogram/methods/messages/send_media_group.py +++ b/pyrogram/methods/messages/send_media_group.py @@ -74,7 +74,7 @@ async def send_media_group( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -151,7 +151,7 @@ async def send_media_group( file=await self.save_file(i.media), spoiler=i.has_spoiler, ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -167,9 +167,10 @@ async def send_media_group( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaPhotoExternal( - url=i.media, spoiler=i.has_spoiler + url=i.media, + spoiler=i.has_spoiler, ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -182,7 +183,8 @@ async def send_media_group( ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.PHOTO + i.media, + FileType.PHOTO, ) else: media = await self.invoke( @@ -192,7 +194,7 @@ async def send_media_group( file=await self.save_file(i.media), spoiler=i.has_spoiler, ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -211,7 +213,7 @@ async def send_media_group( videoInfo = MediaInfo.parse(i.media) except OSError: is_animation = bool( - isinstance(i, types.InputMediaAnimation) + isinstance(i, types.InputMediaAnimation), ) else: if not any( @@ -229,7 +231,7 @@ async def send_media_group( h=i.height, ), raw.types.DocumentAttributeFilename( - file_name=Path(i.media).name + file_name=Path(i.media).name, ), ] if is_animation: @@ -246,7 +248,7 @@ async def send_media_group( nosound_video=is_animation, attributes=attributes, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -262,9 +264,10 @@ async def send_media_group( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaDocumentExternal( - url=i.media, spoiler=i.has_spoiler + url=i.media, + spoiler=i.has_spoiler, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -277,7 +280,8 @@ async def send_media_group( ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.VIDEO + i.media, + FileType.VIDEO, ) else: media = await self.invoke( @@ -288,7 +292,7 @@ async def send_media_group( thumb=await self.save_file(i.thumb), spoiler=i.has_spoiler, mime_type=self.guess_mime_type( - getattr(i.media, "name", "video.mp4") + getattr(i.media, "name", "video.mp4"), ) or "video/mp4", attributes=[ @@ -304,11 +308,11 @@ async def send_media_group( i.media, "name", "video.mp4", - ) + ), ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -337,11 +341,11 @@ async def send_media_group( title=i.title, ), raw.types.DocumentAttributeFilename( - file_name=Path(i.media).name + file_name=Path(i.media).name, ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -349,16 +353,16 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif re.match("^https?://", i.media): media = await self.invoke( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaDocumentExternal( - url=i.media + url=i.media, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -366,11 +370,12 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.AUDIO + i.media, + FileType.AUDIO, ) else: media = await self.invoke( @@ -378,7 +383,7 @@ async def send_media_group( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaUploadedDocument( mime_type=self.guess_mime_type( - getattr(i.media, "name", "audio.mp3") + getattr(i.media, "name", "audio.mp3"), ) or "audio/mpeg", file=await self.save_file(i.media), @@ -394,11 +399,11 @@ async def send_media_group( i.media, "name", "audio.mp3", - ) + ), ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -406,7 +411,7 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif isinstance(i, types.InputMediaDocument): if isinstance(i.media, str): @@ -421,11 +426,11 @@ async def send_media_group( thumb=await self.save_file(i.thumb), attributes=[ raw.types.DocumentAttributeFilename( - file_name=Path(i.media).name - ) + file_name=Path(i.media).name, + ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -433,16 +438,16 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif re.match("^https?://", i.media): media = await self.invoke( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaDocumentExternal( - url=i.media + url=i.media, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -450,11 +455,12 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.DOCUMENT + i.media, + FileType.DOCUMENT, ) else: media = await self.invoke( @@ -462,7 +468,7 @@ async def send_media_group( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaUploadedDocument( mime_type=self.guess_mime_type( - getattr(i.media, "name", "file.zip") + getattr(i.media, "name", "file.zip"), ) or "application/zip", file=await self.save_file(i.media), @@ -473,11 +479,11 @@ async def send_media_group( i.media, "name", "file.zip", - ) - ) + ), + ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -485,11 +491,11 @@ async def send_media_group( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) else: raise ValueError( - f"{i.__class__.__name__} is not a supported type for send_media_group" + f"{i.__class__.__name__} is not a supported type for send_media_group", ) multi_media.append( @@ -497,7 +503,7 @@ async def send_media_group( media=media, random_id=self.rnd_id(), **await self.parser.parse(i.caption, i.parse_mode), - ) + ), ) rpc = raw.functions.messages.SendMultiMedia( @@ -515,7 +521,8 @@ async def send_media_group( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc + connection_id=business_connection_id, + query=rpc, ), sleep_threshold=60, ) diff --git a/pyrogram/methods/messages/send_message.py b/pyrogram/methods/messages/send_message.py index d6950940..d3188120 100644 --- a/pyrogram/methods/messages/send_message.py +++ b/pyrogram/methods/messages/send_message.py @@ -75,7 +75,7 @@ async def send_message( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -181,8 +181,9 @@ async def send_message( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_paid_media.py b/pyrogram/methods/messages/send_paid_media.py index 823be529..98c46987 100644 --- a/pyrogram/methods/messages/send_paid_media.py +++ b/pyrogram/methods/messages/send_paid_media.py @@ -83,9 +83,9 @@ async def send_paid_media( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaUploadedPhoto( - file=await self.save_file(i.media) + file=await self.save_file(i.media), ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -93,14 +93,14 @@ async def send_paid_media( id=media.photo.id, access_hash=media.photo.access_hash, file_reference=media.photo.file_reference, - ) + ), ) elif re.match("^https?://", i.media): media = await self.invoke( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaPhotoExternal(url=i.media), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -108,20 +108,21 @@ async def send_paid_media( id=media.photo.id, access_hash=media.photo.access_hash, file_reference=media.photo.file_reference, - ) + ), ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.PHOTO + i.media, + FileType.PHOTO, ) else: media = await self.invoke( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaUploadedPhoto( - file=await self.save_file(i.media) + file=await self.save_file(i.media), ), - ) + ), ) media = raw.types.InputMediaPhoto( @@ -129,7 +130,7 @@ async def send_paid_media( id=media.photo.id, access_hash=media.photo.access_hash, file_reference=media.photo.file_reference, - ) + ), ) elif isinstance(i, types.InputPaidMediaVideo): if isinstance(i.media, str): @@ -142,7 +143,7 @@ async def send_paid_media( h=i.height, ), raw.types.DocumentAttributeFilename( - file_name=Path(i.media).name + file_name=Path(i.media).name, ), ] media = await self.invoke( @@ -156,7 +157,7 @@ async def send_paid_media( nosound_video=True, attributes=attributes, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -164,16 +165,16 @@ async def send_paid_media( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) elif re.match("^https?://", i.media): media = await self.invoke( raw.functions.messages.UploadMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaDocumentExternal( - url=i.media + url=i.media, ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -181,11 +182,12 @@ async def send_paid_media( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) else: media = utils.get_input_media_from_file_id( - i.media, FileType.VIDEO + i.media, + FileType.VIDEO, ) else: media = await self.invoke( @@ -195,7 +197,7 @@ async def send_paid_media( file=await self.save_file(i.media), thumb=await self.save_file(i.thumbnail), mime_type=self.guess_mime_type( - getattr(i.media, "name", "video.mp4") + getattr(i.media, "name", "video.mp4"), ) or "video/mp4", attributes=[ @@ -208,12 +210,14 @@ async def send_paid_media( ), raw.types.DocumentAttributeFilename( file_name=getattr( - i.media, "name", "video.mp4" - ) + i.media, + "name", + "video.mp4", + ), ), ], ), - ) + ), ) media = raw.types.InputMediaDocument( @@ -221,18 +225,19 @@ async def send_paid_media( id=media.document.id, access_hash=media.document.access_hash, file_reference=media.document.file_reference, - ) + ), ) else: raise ValueError( - f"{i.__class__.__name__} is not a supported type for send_paid_media" + f"{i.__class__.__name__} is not a supported type for send_paid_media", ) multi_media.append(media) rpc = raw.functions.messages.SendMedia( peer=await self.resolve_peer(chat_id), media=raw.types.InputMediaPaidMedia( - stars_amount=star_count, extended_media=multi_media + stars_amount=star_count, + extended_media=multi_media, ), silent=disable_notification or None, random_id=self.rnd_id(), @@ -240,7 +245,10 @@ async def send_paid_media( noforwards=protect_content, invert_media=show_caption_above_media, **await utils.parse_text_entities( - self, caption, parse_mode, caption_entities + self, + caption, + parse_mode, + caption_entities, ), ) session = None @@ -251,16 +259,18 @@ async def send_paid_media( ] if not business_connection: business_connection = await self.get_business_connection( - business_connection_id + business_connection_id, ) session = await get_session( - self, business_connection._raw.connection.dc_id + self, + business_connection._raw.connection.dc_id, ) if business_connection_id: r = await session.invoke( raw.functions.InvokeWithBusinessConnection( - query=rpc, connection_id=business_connection_id - ) + query=rpc, + connection_id=business_connection_id, + ), ) # await session.stop() else: @@ -287,7 +297,9 @@ async def send_paid_media( {i.id: i for i in r.users}, {i.id: i for i in r.chats}, business_connection_id=getattr( - i, "connection_id", business_connection_id + i, + "connection_id", + business_connection_id, ), raw_reply_to_message=i.reply_to_message, replies=0, diff --git a/pyrogram/methods/messages/send_paid_reaction.py b/pyrogram/methods/messages/send_paid_reaction.py index b6dcfca1..9223a37f 100644 --- a/pyrogram/methods/messages/send_paid_reaction.py +++ b/pyrogram/methods/messages/send_paid_reaction.py @@ -51,7 +51,7 @@ async def send_paid_reaction( random_id=self.rnd_id(), count=star_count, private=is_anonymous, - ) + ), ) users = {i.id: i for i in r.users} for i in r.updates: diff --git a/pyrogram/methods/messages/send_photo.py b/pyrogram/methods/messages/send_photo.py index b341ee3d..90f35a6e 100644 --- a/pyrogram/methods/messages/send_photo.py +++ b/pyrogram/methods/messages/send_photo.py @@ -97,7 +97,7 @@ async def send_photo( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -256,7 +256,7 @@ async def send_photo( raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_poll.py b/pyrogram/methods/messages/send_poll.py index 7e4488e4..6624471f 100644 --- a/pyrogram/methods/messages/send_poll.py +++ b/pyrogram/methods/messages/send_poll.py @@ -192,7 +192,10 @@ async def send_poll( ).values() q, q_entities = ( await pyrogram.utils.parse_text_entities( - self, question, None, question_entities + self, + question, + None, + question_entities, ) ).values() @@ -202,11 +205,13 @@ async def send_poll( poll=raw.types.Poll( id=self.rnd_id(), question=raw.types.TextWithEntities( - text=q, entities=q_entities or [] + text=q, + entities=q_entities or [], ), answers=[ await types.PollOption( - text=option.text, entities=option.entities + text=option.text, + entities=option.entities, ).write(self, i) for i, option in enumerate(options) ], @@ -236,8 +241,9 @@ async def send_poll( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_reaction.py b/pyrogram/methods/messages/send_reaction.py index 44f96a79..5448fe2a 100644 --- a/pyrogram/methods/messages/send_reaction.py +++ b/pyrogram/methods/messages/send_reaction.py @@ -87,7 +87,7 @@ async def send_reaction( reaction=reaction, big=big, add_to_recent=add_to_recent, - ) + ), ) for i in r.updates: if isinstance(i, raw.types.UpdateMessageReactions): @@ -102,7 +102,7 @@ async def send_reaction( if emoji else None, add_to_recent=add_to_recent, - ) + ), ) return True raise ValueError("You need to pass one of message_id!") diff --git a/pyrogram/methods/messages/send_sticker.py b/pyrogram/methods/messages/send_sticker.py index 980c8c09..4c5d7fdf 100644 --- a/pyrogram/methods/messages/send_sticker.py +++ b/pyrogram/methods/messages/send_sticker.py @@ -77,7 +77,7 @@ async def send_sticker( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -176,7 +176,7 @@ async def send_sticker( file=file, attributes=[ raw.types.DocumentAttributeFilename( - file_name=Path(sticker).name + file_name=Path(sticker).name, ), raw.types.DocumentAttributeSticker( alt=emoji, @@ -188,7 +188,8 @@ async def send_sticker( media = raw.types.InputMediaDocumentExternal(url=sticker) else: media = utils.get_input_media_from_file_id( - sticker, FileType.STICKER + sticker, + FileType.STICKER, ) else: file = await self.save_file( @@ -200,7 +201,7 @@ async def send_sticker( mime_type=self.guess_mime_type(sticker.name) or "image/webp", file=file, attributes=[ - raw.types.DocumentAttributeFilename(file_name=sticker.name) + raw.types.DocumentAttributeFilename(file_name=sticker.name), ], ) @@ -226,7 +227,7 @@ async def send_sticker( raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_venue.py b/pyrogram/methods/messages/send_venue.py index fcdda962..ebce7477 100644 --- a/pyrogram/methods/messages/send_venue.py +++ b/pyrogram/methods/messages/send_venue.py @@ -160,8 +160,9 @@ async def send_venue( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_video.py b/pyrogram/methods/messages/send_video.py index 22588788..fe02d64b 100644 --- a/pyrogram/methods/messages/send_video.py +++ b/pyrogram/methods/messages/send_video.py @@ -125,7 +125,7 @@ async def send_video( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -240,7 +240,7 @@ async def progress(current, total): h=height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or Path(video).name + file_name=file_name or Path(video).name, ), ], ) @@ -252,7 +252,9 @@ async def progress(current, total): ) else: media = utils.get_input_media_from_file_id( - video, FileType.VIDEO, ttl_seconds=ttl_seconds + video, + FileType.VIDEO, + ttl_seconds=ttl_seconds, ) media.spoiler = has_spoiler else: @@ -277,7 +279,7 @@ async def progress(current, total): h=height, ), raw.types.DocumentAttributeFilename( - file_name=file_name or video.name + file_name=file_name or video.name, ), ], ) @@ -310,7 +312,7 @@ async def progress(current, total): raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_video_note.py b/pyrogram/methods/messages/send_video_note.py index fce72e17..bd7ebc9d 100644 --- a/pyrogram/methods/messages/send_video_note.py +++ b/pyrogram/methods/messages/send_video_note.py @@ -88,7 +88,7 @@ async def send_video_note( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. message_effect_id (``int`` ``64-bit``, *optional*): Unique identifier of the message effect to be added to the message; for private chats only. @@ -201,13 +201,14 @@ async def send_video_note( duration=duration, w=length, h=length, - ) + ), ], ttl_seconds=ttl_seconds, ) else: media = utils.get_input_media_from_file_id( - video_note, FileType.VIDEO_NOTE + video_note, + FileType.VIDEO_NOTE, ) else: thumb = await self.save_file(thumb) @@ -226,7 +227,7 @@ async def send_video_note( duration=duration, w=length, h=length, - ) + ), ], ) @@ -252,13 +253,15 @@ async def send_video_note( raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) except FilePartMissing as e: await self.save_file( - video_note, file_id=file.id, file_part=e.value + video_note, + file_id=file.id, + file_part=e.value, ) else: for i in r.updates: diff --git a/pyrogram/methods/messages/send_voice.py b/pyrogram/methods/messages/send_voice.py index 5ceb7464..8c7333c3 100644 --- a/pyrogram/methods/messages/send_voice.py +++ b/pyrogram/methods/messages/send_voice.py @@ -89,10 +89,10 @@ async def send_voice( If the message is a reply, ID of the original message reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. message_effect_id (``int`` ``64-bit``, *optional*): Unique identifier of the message effect to be added to the message; for private chats only. @@ -188,8 +188,9 @@ async def send_voice( file=file, attributes=[ raw.types.DocumentAttributeAudio( - voice=True, duration=duration - ) + voice=True, + duration=duration, + ), ], ) elif re.match("^https?://", voice): @@ -207,8 +208,9 @@ async def send_voice( file=file, attributes=[ raw.types.DocumentAttributeAudio( - voice=True, duration=duration - ) + voice=True, + duration=duration, + ), ], ) @@ -239,7 +241,7 @@ async def send_voice( raw.functions.InvokeWithBusinessConnection( connection_id=business_connection_id, query=rpc, - ) + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/send_web_page.py b/pyrogram/methods/messages/send_web_page.py index dc11c0e5..10223d27 100644 --- a/pyrogram/methods/messages/send_web_page.py +++ b/pyrogram/methods/messages/send_web_page.py @@ -82,7 +82,7 @@ async def send_web_page( If the message is a reply, ID of the original message. reply_to_story_id (``int``, *optional*): - Unique identifier for the target story. + If the message is a reply, ID of the target story. reply_to_chat_id (``int`` | ``str``, *optional*): Unique identifier for the origin chat. @@ -162,8 +162,9 @@ async def send_web_page( if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/stop_poll.py b/pyrogram/methods/messages/stop_poll.py index 659b646a..70d8e26a 100644 --- a/pyrogram/methods/messages/stop_poll.py +++ b/pyrogram/methods/messages/stop_poll.py @@ -53,15 +53,16 @@ async def stop_poll( closed=True, question="", answers=[], - ) + ), ), reply_markup=await reply_markup.write(self) if reply_markup else None, ) if business_connection_id is not None: r = await self.invoke( raw.functions.InvokeWithBusinessConnection( - connection_id=business_connection_id, query=rpc - ) + connection_id=business_connection_id, + query=rpc, + ), ) else: r = await self.invoke(rpc) diff --git a/pyrogram/methods/messages/stream_media.py b/pyrogram/methods/messages/stream_media.py index 157e6607..d30199bb 100644 --- a/pyrogram/methods/messages/stream_media.py +++ b/pyrogram/methods/messages/stream_media.py @@ -77,7 +77,7 @@ async def stream_media( break else: raise ValueError( - "This message doesn't contain any downloadable media" + "This message doesn't contain any downloadable media", ) else: media = message @@ -90,7 +90,7 @@ async def stream_media( if offset < 0: if file_size == 0: raise ValueError( - "Negative offsets are not supported for file ids, pass a Message object instead" + "Negative offsets are not supported for file ids, pass a Message object instead", ) chunks = math.ceil(file_size / 1024 / 1024) diff --git a/pyrogram/methods/messages/translate_text.py b/pyrogram/methods/messages/translate_text.py index 139b4e89..03b3852b 100644 --- a/pyrogram/methods/messages/translate_text.py +++ b/pyrogram/methods/messages/translate_text.py @@ -42,7 +42,7 @@ async def translate_message_text( to_lang=to_language_code, peer=await self.resolve_peer(chat_id), id=ids, - ) + ), ) return ( @@ -94,9 +94,12 @@ async def translate_text( raw.functions.messages.TranslateText( to_lang=to_language_code, text=[ - raw.types.TextWithEntities(text=message, entities=entities or []) + raw.types.TextWithEntities( + text=message, + entities=entities or [], + ), ], - ) + ), ) return ( diff --git a/pyrogram/methods/messages/vote_poll.py b/pyrogram/methods/messages/vote_poll.py index f4548fab..ca0a1bc4 100644 --- a/pyrogram/methods/messages/vote_poll.py +++ b/pyrogram/methods/messages/vote_poll.py @@ -45,7 +45,7 @@ async def vote_poll( peer=await self.resolve_peer(chat_id), msg_id=message_id, options=[poll.options[option].data for option in options], - ) + ), ) return await types.Poll._parse(self, r.updates[0], r.users) diff --git a/pyrogram/methods/password/change_cloud_password.py b/pyrogram/methods/password/change_cloud_password.py index 62db6c3d..f9ab6cd8 100644 --- a/pyrogram/methods/password/change_cloud_password.py +++ b/pyrogram/methods/password/change_cloud_password.py @@ -65,7 +65,7 @@ async def change_cloud_password( new_password_hash=new_hash, hint=new_hint, ), - ) + ), ) return True diff --git a/pyrogram/methods/password/enable_cloud_password.py b/pyrogram/methods/password/enable_cloud_password.py index b1c0e73e..02a8c3df 100644 --- a/pyrogram/methods/password/enable_cloud_password.py +++ b/pyrogram/methods/password/enable_cloud_password.py @@ -66,7 +66,7 @@ async def enable_cloud_password( hint=hint, email=email, ), - ) + ), ) return True diff --git a/pyrogram/methods/password/remove_cloud_password.py b/pyrogram/methods/password/remove_cloud_password.py index 2b3c86c6..77ce127d 100644 --- a/pyrogram/methods/password/remove_cloud_password.py +++ b/pyrogram/methods/password/remove_cloud_password.py @@ -39,7 +39,7 @@ async def remove_cloud_password(self: pyrogram.Client, password: str) -> bool: new_password_hash=b"", hint="", ), - ) + ), ) return True diff --git a/pyrogram/methods/stickers/add_sticker_to_set.py b/pyrogram/methods/stickers/add_sticker_to_set.py index ce986f3f..ee8c4d9f 100644 --- a/pyrogram/methods/stickers/add_sticker_to_set.py +++ b/pyrogram/methods/stickers/add_sticker_to_set.py @@ -55,10 +55,10 @@ async def add_sticker_to_set( r = await self.invoke( raw.functions.stickers.AddStickerToSet( stickerset=raw.types.InputStickerSetShortName( - short_name=set_short_name + short_name=set_short_name, ), sticker=raw.types.InputStickerSetItem(document=media, emoji=emoji), - ) + ), ) return types.StickerSet._parse(r.set) diff --git a/pyrogram/methods/stickers/create_sticker_set.py b/pyrogram/methods/stickers/create_sticker_set.py index 2eb3f59d..6028462f 100644 --- a/pyrogram/methods/stickers/create_sticker_set.py +++ b/pyrogram/methods/stickers/create_sticker_set.py @@ -75,10 +75,10 @@ async def create_sticker_set( title=title, short_name=short_name, stickers=[ - raw.types.InputStickerSetItem(document=media, emoji=emoji) + raw.types.InputStickerSetItem(document=media, emoji=emoji), ], masks=masks, - ) + ), ) return types.StickerSet._parse(r.set) diff --git a/pyrogram/methods/stickers/get_sticker_set.py b/pyrogram/methods/stickers/get_sticker_set.py index 1ddb1649..68aaa74b 100644 --- a/pyrogram/methods/stickers/get_sticker_set.py +++ b/pyrogram/methods/stickers/get_sticker_set.py @@ -6,7 +6,8 @@ class GetStickerSet: async def get_sticker_set( - self: pyrogram.Client, set_short_name: str + self: pyrogram.Client, + set_short_name: str, ) -> types.StickerSet: """Get info about a stickerset. @@ -27,10 +28,10 @@ async def get_sticker_set( r = await self.invoke( raw.functions.messages.GetStickerSet( stickerset=raw.types.InputStickerSetShortName( - short_name=set_short_name + short_name=set_short_name, ), hash=0, - ) + ), ) return types.StickerSet._parse(r.set) diff --git a/pyrogram/methods/users/block_user.py b/pyrogram/methods/users/block_user.py index ed1c9566..90d7d47c 100644 --- a/pyrogram/methods/users/block_user.py +++ b/pyrogram/methods/users/block_user.py @@ -27,6 +27,6 @@ async def block_user(self: pyrogram.Client, user_id: int | str) -> bool: """ return bool( await self.invoke( - raw.functions.contacts.Block(id=await self.resolve_peer(user_id)) - ) + raw.functions.contacts.Block(id=await self.resolve_peer(user_id)), + ), ) diff --git a/pyrogram/methods/users/delete_account.py b/pyrogram/methods/users/delete_account.py index a3fc0a6f..6306278e 100644 --- a/pyrogram/methods/users/delete_account.py +++ b/pyrogram/methods/users/delete_account.py @@ -7,7 +7,9 @@ class DeleteAccount: async def delete_account( - self: pyrogram.Client, reason: str = "", password: str | None = None + self: pyrogram.Client, + reason: str = "", + password: str | None = None, ) -> bool: """Deletes the account of the current user, deleting all information associated with the user from the server. @@ -32,11 +34,12 @@ async def delete_account( raw.functions.account.DeleteAccount( reason=reason, password=compute_password_check( - await self.invoke(raw.functions.account.GetPassword()), password + await self.invoke(raw.functions.account.GetPassword()), + password, ) if password else None, - ) + ), ) return bool(r) diff --git a/pyrogram/methods/users/delete_profile_photos.py b/pyrogram/methods/users/delete_profile_photos.py index 9c0ed7c4..fc52cd9a 100644 --- a/pyrogram/methods/users/delete_profile_photos.py +++ b/pyrogram/methods/users/delete_profile_photos.py @@ -7,7 +7,8 @@ class DeleteProfilePhotos: async def delete_profile_photos( - self: pyrogram.Client, photo_ids: str | list[str] + self: pyrogram.Client, + photo_ids: str | list[str], ) -> bool: """Delete your own profile photos. @@ -40,5 +41,5 @@ async def delete_profile_photos( ] return bool( - await self.invoke(raw.functions.photos.DeletePhotos(id=input_photos)) + await self.invoke(raw.functions.photos.DeletePhotos(id=input_photos)), ) diff --git a/pyrogram/methods/users/edit_story.py b/pyrogram/methods/users/edit_story.py index c910486d..43705aa4 100644 --- a/pyrogram/methods/users/edit_story.py +++ b/pyrogram/methods/users/edit_story.py @@ -131,7 +131,8 @@ async def edit_story( media = raw.types.InputMediaDocumentExternal(url=animation) else: media = utils.get_input_media_from_file_id( - animation, FileType.ANIMATION + animation, + FileType.ANIMATION, ) else: file = await self.save_file(animation) @@ -173,7 +174,7 @@ async def edit_story( duration=0, w=0, h=0, - ) + ), ], ) elif re.match("^https?://", video): @@ -191,7 +192,7 @@ async def edit_story( duration=0, w=0, h=0, - ) + ), ], ) text = None @@ -199,8 +200,11 @@ async def edit_story( if caption: text, entities = self._split( **await utils.parse_text_entities( - self, caption, parse_mode, caption_entities - ) + self, + caption, + parse_mode, + caption_entities, + ), ) """ @@ -217,7 +221,7 @@ async def edit_story( if denied_users and len(denied_users) > 0: users = [await self.resolve_peer(user_id) for user_id in denied_users] privacy_rules.append( - raw.types.InputPrivacyValueDisallowUsers(users=users) + raw.types.InputPrivacyValueDisallowUsers(users=users), ) r = await self.invoke( @@ -231,6 +235,6 @@ async def edit_story( media_areas=[ await media_area.write(self) for media_area in media_areas ], - ) + ), ) return await types.Story._parse(self, r.updates[0].story, r.updates[0].peer) diff --git a/pyrogram/methods/users/get_chat_photos.py b/pyrogram/methods/users/get_chat_photos.py index df8b959a..6b232e07 100644 --- a/pyrogram/methods/users/get_chat_photos.py +++ b/pyrogram/methods/users/get_chat_photos.py @@ -47,13 +47,14 @@ async def get_chat_photos( if isinstance(peer_id, raw.types.InputPeerChannel): r = await self.invoke( - raw.functions.channels.GetFullChannel(channel=peer_id) + raw.functions.channels.GetFullChannel(channel=peer_id), ) current = types.Photo._parse(self, r.full_chat.chat_photo) or [] current = [current] current_animation = types.Animation._parse_chat_animation( - self, r.full_chat.chat_photo + self, + r.full_chat.chat_photo, ) if current_animation: current = [*current, current_animation] @@ -74,7 +75,7 @@ async def get_chat_photos( max_id=0, min_id=0, hash=0, - ) + ), ), ) @@ -116,14 +117,15 @@ async def get_chat_photos( offset=offset, max_id=0, limit=limit, - ) + ), ) photos = [] for photo in r.photos: photos.append(types.Photo._parse(self, photo)) current_animation = types.Animation._parse_chat_animation( - self, photo + self, + photo, ) if current_animation: photos.append(current_animation) diff --git a/pyrogram/methods/users/get_chat_photos_count.py b/pyrogram/methods/users/get_chat_photos_count.py index 509a864d..1b8e4136 100644 --- a/pyrogram/methods/users/get_chat_photos_count.py +++ b/pyrogram/methods/users/get_chat_photos_count.py @@ -6,7 +6,8 @@ class GetChatPhotosCount: async def get_chat_photos_count( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> int: """Get the total count of photos for a chat. @@ -36,14 +37,17 @@ async def get_chat_photos_count( raw.functions.messages.GetSearchCounters( peer=peer_id, filters=[raw.types.InputMessagesFilterChatPhotos()], - ) + ), ) return r[0].count r = await self.invoke( raw.functions.photos.GetUserPhotos( - user_id=peer_id, offset=0, max_id=0, limit=1 - ) + user_id=peer_id, + offset=0, + max_id=0, + limit=1, + ), ) if isinstance(r, raw.types.photos.Photos): diff --git a/pyrogram/methods/users/get_common_chats.py b/pyrogram/methods/users/get_common_chats.py index f3a69c5c..7b2ce8a7 100644 --- a/pyrogram/methods/users/get_common_chats.py +++ b/pyrogram/methods/users/get_common_chats.py @@ -6,7 +6,8 @@ class GetCommonChats: async def get_common_chats( - self: pyrogram.Client, user_id: int | str + self: pyrogram.Client, + user_id: int | str, ) -> list[types.Chat]: """Get the common chats you have with a user. @@ -40,7 +41,7 @@ async def get_common_chats( user_id=peer, max_id=0, limit=100, - ) + ), ) return types.List([types.Chat._parse_chat(self, x) for x in r.chats]) diff --git a/pyrogram/methods/users/get_me.py b/pyrogram/methods/users/get_me.py index f91e5eb0..fd2073b8 100644 --- a/pyrogram/methods/users/get_me.py +++ b/pyrogram/methods/users/get_me.py @@ -20,7 +20,7 @@ async def get_me(self: pyrogram.Client) -> types.User: print(me) """ r = await self.invoke( - raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()) + raw.functions.users.GetFullUser(id=raw.types.InputUserSelf()), ) users = {u.id: u for u in r.users} diff --git a/pyrogram/methods/users/get_peer_stories.py b/pyrogram/methods/users/get_peer_stories.py index a53c1abc..c9a2aeb4 100644 --- a/pyrogram/methods/users/get_peer_stories.py +++ b/pyrogram/methods/users/get_peer_stories.py @@ -14,7 +14,8 @@ class GetPeerStories: async def get_peer_stories( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> AsyncGenerator[types.Story, None] | None: """Get all active stories from an user/channel by using user identifiers. diff --git a/pyrogram/methods/users/get_stories.py b/pyrogram/methods/users/get_stories.py index abaacb1a..398dd6f4 100644 --- a/pyrogram/methods/users/get_stories.py +++ b/pyrogram/methods/users/get_stories.py @@ -61,7 +61,7 @@ async def get_stories( if is_iterable: return types.List( - [await types.Story._parse(self, story, peer) for story in r.stories] + [await types.Story._parse(self, story, peer) for story in r.stories], ) return ( await types.Story._parse(self, r.stories[0], peer) diff --git a/pyrogram/methods/users/get_stories_history.py b/pyrogram/methods/users/get_stories_history.py index e5a46baa..85f6700b 100644 --- a/pyrogram/methods/users/get_stories_history.py +++ b/pyrogram/methods/users/get_stories_history.py @@ -55,7 +55,9 @@ async def get_stories_history( peer = await self.resolve_peer("me") rpc = raw.functions.stories.GetStoriesArchive( - peer=peer, offset_id=offset_id, limit=limit + peer=peer, + offset_id=offset_id, + limit=limit, ) r = await self.invoke(rpc, sleep_threshold=-1) diff --git a/pyrogram/methods/users/send_story.py b/pyrogram/methods/users/send_story.py index 280fac8c..6e002d4c 100644 --- a/pyrogram/methods/users/send_story.py +++ b/pyrogram/methods/users/send_story.py @@ -15,7 +15,9 @@ def _split(self, message, entities, *args, **kwargs): return message, entities async def _upload_video( - self: pyrogram.Client, file_name: str, video: str | BinaryIO + self: pyrogram.Client, + file_name: str, + video: str | BinaryIO, ): file = await self.save_file(video) return raw.types.InputMediaUploadedDocument( @@ -23,8 +25,11 @@ async def _upload_video( file=file, attributes=[ raw.types.DocumentAttributeVideo( - supports_streaming=True, duration=0, w=0, h=0 - ) + supports_streaming=True, + duration=0, + w=0, + h=0, + ), ], ) @@ -144,7 +149,7 @@ async def send_story( privacy_rules = [types.StoriesPrivacyRules(type=privacy)] else: privacy_rules = [ - types.StoriesPrivacyRules(type=enums.StoriesPrivacyRules.PUBLIC) + types.StoriesPrivacyRules(type=enums.StoriesPrivacyRules.PUBLIC), ] if photo: @@ -172,7 +177,7 @@ async def send_story( duration=0, w=0, h=0, - ) + ), ], ) elif re.match("^https?://", video): @@ -184,13 +189,16 @@ async def send_story( media = await self._upload_video(file_name, video) elif forward_from_chat_id is None: raise ValueError( - "You need to pass one of the following parameter photo/video/forward_from_chat_id!" + "You need to pass one of the following parameter photo/video/forward_from_chat_id!", ) text, entities = self._split( **await utils.parse_text_entities( - self, caption, parse_mode, caption_entities - ) + self, + caption, + parse_mode, + caption_entities, + ), ) """ @@ -207,7 +215,7 @@ async def send_story( if denied_users and len(denied_users) > 0: users = [await self.resolve_peer(user_id) for user_id in denied_users] privacy_rules.append( - raw.types.InputPrivacyValueDisallowUsers(users=users) + raw.types.InputPrivacyValueDisallowUsers(users=users), ) forward_from_chat = None @@ -216,7 +224,7 @@ async def send_story( media = raw.types.InputMediaEmpty() if forward_from_story_id is None: raise ValueError( - "You need to pass forward_from_story_id to forward story!" + "You need to pass forward_from_story_id to forward story!", ) r = await self.invoke( @@ -235,13 +243,13 @@ async def send_story( if forward_from_chat_id is not None else None, fwd_modified=bool( - forward_from_chat_id is not None and caption is not None + forward_from_chat_id is not None and caption is not None, ), media_areas=[ await media_area.write(self) for media_area in media_areas ] if media_areas is not None else None, - ) + ), ) return await types.Story._parse(self, r.updates[0].story, r.updates[0].peer) diff --git a/pyrogram/methods/users/set_emoji_status.py b/pyrogram/methods/users/set_emoji_status.py index 21162047..eac54fa0 100644 --- a/pyrogram/methods/users/set_emoji_status.py +++ b/pyrogram/methods/users/set_emoji_status.py @@ -33,8 +33,8 @@ async def set_emoji_status( emoji_status.write() if emoji_status else raw.types.EmojiStatusEmpty() - ) - ) + ), + ), ) return True diff --git a/pyrogram/methods/users/set_profile_photo.py b/pyrogram/methods/users/set_profile_photo.py index d2ba2008..9997ca14 100644 --- a/pyrogram/methods/users/set_profile_photo.py +++ b/pyrogram/methods/users/set_profile_photo.py @@ -54,6 +54,6 @@ async def set_profile_photo( raw.functions.photos.UploadProfilePhoto( file=await self.save_file(photo), video=await self.save_file(video), - ) - ) + ), + ), ) diff --git a/pyrogram/methods/users/set_username.py b/pyrogram/methods/users/set_username.py index 74e2d53b..718c03b1 100644 --- a/pyrogram/methods/users/set_username.py +++ b/pyrogram/methods/users/set_username.py @@ -29,6 +29,6 @@ async def set_username(self: pyrogram.Client, username: str | None) -> bool: return bool( await self.invoke( - raw.functions.account.UpdateUsername(username=username or "") - ) + raw.functions.account.UpdateUsername(username=username or ""), + ), ) diff --git a/pyrogram/methods/users/unblock_user.py b/pyrogram/methods/users/unblock_user.py index 4f641b7a..a5af9425 100644 --- a/pyrogram/methods/users/unblock_user.py +++ b/pyrogram/methods/users/unblock_user.py @@ -27,6 +27,6 @@ async def unblock_user(self: pyrogram.Client, user_id: int | str) -> bool: """ return bool( await self.invoke( - raw.functions.contacts.Unblock(id=await self.resolve_peer(user_id)) - ) + raw.functions.contacts.Unblock(id=await self.resolve_peer(user_id)), + ), ) diff --git a/pyrogram/methods/users/update_birthday.py b/pyrogram/methods/users/update_birthday.py index c295df4c..78461e67 100644 --- a/pyrogram/methods/users/update_birthday.py +++ b/pyrogram/methods/users/update_birthday.py @@ -39,6 +39,6 @@ async def update_birthday( birthday = await birthday.write() r = await self.invoke( - raw.functions.account.UpdateBirthday(birthday=birthday) + raw.functions.account.UpdateBirthday(birthday=birthday), ) return bool(r) diff --git a/pyrogram/methods/users/update_personal_chat.py b/pyrogram/methods/users/update_personal_chat.py index fabc871c..6b7cebda 100644 --- a/pyrogram/methods/users/update_personal_chat.py +++ b/pyrogram/methods/users/update_personal_chat.py @@ -6,7 +6,8 @@ class UpdatePersonalChat: async def update_personal_chat( - self: pyrogram.Client, chat_id: int | str + self: pyrogram.Client, + chat_id: int | str, ) -> bool: """Update your birthday details. @@ -28,6 +29,6 @@ async def update_personal_chat( """ chat = await self.resolve_peer(chat_id) r = await self.invoke( - raw.functions.account.UpdatePersonalChannel(channel=chat) + raw.functions.account.UpdatePersonalChannel(channel=chat), ) return bool(r) diff --git a/pyrogram/methods/users/update_profile.py b/pyrogram/methods/users/update_profile.py index f9aad9fb..1e47f830 100644 --- a/pyrogram/methods/users/update_profile.py +++ b/pyrogram/methods/users/update_profile.py @@ -51,6 +51,6 @@ async def update_profile( first_name=first_name, last_name=last_name, about=bio, - ) - ) + ), + ), ) diff --git a/pyrogram/methods/utilities/remove_handler.py b/pyrogram/methods/utilities/remove_handler.py index f1fb2261..803dd9c9 100644 --- a/pyrogram/methods/utilities/remove_handler.py +++ b/pyrogram/methods/utilities/remove_handler.py @@ -11,7 +11,9 @@ class RemoveHandler: def remove_handler( - self: pyrogram.Client, handler: Handler, group: int = 0 + self: pyrogram.Client, + handler: Handler, + group: int = 0, ) -> None: """Remove a previously-registered update handler. diff --git a/pyrogram/methods/utilities/run_sync.py b/pyrogram/methods/utilities/run_sync.py index cc126f79..331ff068 100644 --- a/pyrogram/methods/utilities/run_sync.py +++ b/pyrogram/methods/utilities/run_sync.py @@ -12,7 +12,10 @@ class RunSync: Result = TypeVar("Result") async def run_sync( - self, func: Callable[..., Result], *args: Any, **kwargs: Any + self, + func: Callable[..., Result], + *args: Any, + **kwargs: Any, ) -> Result: """Runs the given sync function (optionally with arguments) on a separate thread. diff --git a/pyrogram/methods/utilities/start.py b/pyrogram/methods/utilities/start.py index 387c5e00..53974930 100644 --- a/pyrogram/methods/utilities/start.py +++ b/pyrogram/methods/utilities/start.py @@ -43,7 +43,7 @@ async def main(): if not is_authorized: await self.authorize() - if not await self.storage.is_bot() and self.takeout: + if self.takeout and not await self.storage.is_bot(): self.takeout_id = ( await self.invoke(raw.functions.account.InitTakeoutSession()) ).id diff --git a/pyrogram/parser/html.py b/pyrogram/parser/html.py index 1362ffd9..b8e2dfad 100644 --- a/pyrogram/parser/html.py +++ b/pyrogram/parser/html.py @@ -71,7 +71,7 @@ def handle_starttag(self, tag, attrs) -> None: self.tag_entities[tag] = [] self.tag_entities[tag].append( - entity(offset=len(self.text), length=0, **extra) + entity(offset=len(self.text), length=0, **extra), ) def handle_data(self, data) -> None: @@ -132,7 +132,7 @@ async def parse(self, text: str): try: if self.client is not None: entity.user_id = await self.client.resolve_peer( - entity.user_id + entity.user_id, ) except PeerIdInvalid: continue diff --git a/pyrogram/parser/markdown.py b/pyrogram/parser/markdown.py index 4b40ef0d..8b9b6e47 100644 --- a/pyrogram/parser/markdown.py +++ b/pyrogram/parser/markdown.py @@ -39,9 +39,9 @@ SPOILER_DELIM, ] ] - ] - ) - ) + ], + ), + ), ) OPENING_TAG = "<{}>" @@ -114,7 +114,7 @@ async def parse(self, text: str, strict: bool = False): placeholders[placeholder] = code_section text = text.replace(code_section, placeholder, 1) - for i, match in enumerate(re.finditer(MARKDOWN_RE, text)): + for _i, match in enumerate(re.finditer(MARKDOWN_RE, text)): start, _ = match.span() delim, text_url, url = match.groups() full = match.group(0) @@ -220,13 +220,13 @@ def unparse(text: str, entities: list): ( start_tag, start_offset, - ) + ), ) entities_offsets.append( ( end_tag, end_offset, - ) + ), ) last_length = last_length + 1 continue @@ -247,13 +247,13 @@ def unparse(text: str, entities: list): ( start_tag, start, - ) + ), ) entities_offsets.append( ( end_tag, end, - ) + ), ) entities_offsets = ( diff --git a/pyrogram/raw/core/future_salt.py b/pyrogram/raw/core/future_salt.py index 7740c3e9..615b91db 100644 --- a/pyrogram/raw/core/future_salt.py +++ b/pyrogram/raw/core/future_salt.py @@ -10,7 +10,7 @@ class FutureSalt(TLObject): ID = 0x0949D9DC - __slots__ = ["valid_since", "valid_until", "salt"] + __slots__ = ["salt", "valid_since", "valid_until"] QUALNAME = "FutureSalt" diff --git a/pyrogram/raw/core/future_salts.py b/pyrogram/raw/core/future_salts.py index 98780490..beb8a4a4 100644 --- a/pyrogram/raw/core/future_salts.py +++ b/pyrogram/raw/core/future_salts.py @@ -11,7 +11,7 @@ class FutureSalts(TLObject): ID = 0xAE500895 - __slots__ = ["req_msg_id", "now", "salts"] + __slots__ = ["now", "req_msg_id", "salts"] QUALNAME = "FutureSalts" diff --git a/pyrogram/raw/core/message.py b/pyrogram/raw/core/message.py index a02229ad..98a7d466 100644 --- a/pyrogram/raw/core/message.py +++ b/pyrogram/raw/core/message.py @@ -10,12 +10,16 @@ class Message(TLObject): ID = 0x5BB8E511 # hex(crc32(b"message msg_id:long seqno:int bytes:int body:Object = Message")) - __slots__ = ["msg_id", "seq_no", "length", "body"] + __slots__ = ["body", "length", "msg_id", "seq_no"] QUALNAME = "Message" def __init__( - self, body: TLObject, msg_id: int, seq_no: int, length: int + self, + body: TLObject, + msg_id: int, + seq_no: int, + length: int, ) -> None: self.msg_id = msg_id self.seq_no = seq_no diff --git a/pyrogram/raw/core/primitives/vector.py b/pyrogram/raw/core/primitives/vector.py index e7e056b0..9443da23 100644 --- a/pyrogram/raw/core/primitives/vector.py +++ b/pyrogram/raw/core/primitives/vector.py @@ -45,5 +45,5 @@ def read(cls, data: BytesIO, t: Any = None, *args: Any) -> List: # noqa: ARG003 def __new__(cls, value: list, t: Any = None) -> bytes: # type: ignore return b"".join( [Int(cls.ID, False), Int(len(value))] - + [cast(bytes, t(i)) if t else i.write() for i in value] + + [cast(bytes, t(i)) if t else i.write() for i in value], ) diff --git a/pyrogram/raw/core/tl_object.py b/pyrogram/raw/core/tl_object.py index e7e27307..1954f390 100644 --- a/pyrogram/raw/core/tl_object.py +++ b/pyrogram/raw/core/tl_object.py @@ -17,7 +17,8 @@ class TLObject: @classmethod def read(cls, b: BytesIO, *args: Any) -> Any: return cast(TLObject, objects[int.from_bytes(b.read(4), "little")]).read( - b, *args + b, + *args, ) def write(self, *args: Any) -> bytes: @@ -53,7 +54,7 @@ def __repr__(self) -> str: ), ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: for attr in self.__slots__: try: if getattr(self, attr) != getattr(other, attr): diff --git a/pyrogram/session/auth.py b/pyrogram/session/auth.py index bd105c05..8d819d19 100644 --- a/pyrogram/session/auth.py +++ b/pyrogram/session/auth.py @@ -133,7 +133,7 @@ async def create(self): q=q.to_bytes(4, "big"), public_key_fingerprint=public_key_fingerprint, encrypted_data=encrypted_data, - ) + ), ) encrypted_answer = server_dh_params.encrypted_answer @@ -155,7 +155,9 @@ async def create(self): server_nonce = int.from_bytes(server_nonce, "little", signed=True) answer_with_hash = aes.ige256_decrypt( - encrypted_answer, tmp_aes_key, tmp_aes_iv + encrypted_answer, + tmp_aes_key, + tmp_aes_iv, ) answer = answer_with_hash[20:] @@ -185,7 +187,9 @@ async def create(self): padding = urandom(-(len(data) + len(sha)) % 16) data_with_hash = sha + data + padding encrypted_data = aes.ige256_encrypt( - data_with_hash, tmp_aes_key, tmp_aes_iv + data_with_hash, + tmp_aes_key, + tmp_aes_iv, ) log.debug("Send set_client_DH_params") @@ -194,7 +198,7 @@ async def create(self): nonce=nonce, server_nonce=server_nonce, encrypted_data=encrypted_data, - ) + ), ) g_a = int.from_bytes(server_dh_inner_data.g_a, "big") @@ -209,13 +213,16 @@ async def create(self): g_b = int.from_bytes(g_b, "big") SecurityCheckMismatch.check( - 1 < g < dh_prime - 1, "1 < g < dh_prime - 1" + 1 < g < dh_prime - 1, + "1 < g < dh_prime - 1", ) SecurityCheckMismatch.check( - 1 < g_a < dh_prime - 1, "1 < g_a < dh_prime - 1" + 1 < g_a < dh_prime - 1, + "1 < g_a < dh_prime - 1", ) SecurityCheckMismatch.check( - 1 < g_b < dh_prime - 1, "1 < g_b < dh_prime - 1" + 1 < g_b < dh_prime - 1, + "1 < g_b < dh_prime - 1", ) SecurityCheckMismatch.check( 2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64), @@ -235,7 +242,8 @@ async def create(self): log.debug("SHA1 hash values check: OK") SecurityCheckMismatch.check( - nonce == res_pq.nonce, "nonce == res_pq.nonce" + nonce == res_pq.nonce, + "nonce == res_pq.nonce", ) server_nonce = int.from_bytes(server_nonce, "little", signed=True) SecurityCheckMismatch.check( diff --git a/pyrogram/session/session.py b/pyrogram/session/session.py index 6b58067f..bbc133a4 100644 --- a/pyrogram/session/session.py +++ b/pyrogram/session/session.py @@ -113,7 +113,8 @@ async def start(self) -> None: self.recv_task = asyncio.create_task(self.recv_worker()) await self.send( - raw.functions.Ping(ping_id=0), timeout=self.START_TIMEOUT + raw.functions.Ping(ping_id=0), + timeout=self.START_TIMEOUT, ) if not self.is_cdn: @@ -181,7 +182,8 @@ async def stop(self, restart: bool = False) -> None: if self.ping_task: try: await asyncio.wait_for( - self.ping_task, timeout=self.RECONN_TIMEOUT + self.ping_task, + timeout=self.RECONN_TIMEOUT, ) except asyncio.TimeoutError: self.ping_task.cancel() @@ -190,13 +192,15 @@ async def stop(self, restart: bool = False) -> None: if self.connection: with contextlib.suppress(Exception): await asyncio.wait_for( - self.connection.close(), timeout=self.RECONN_TIMEOUT + self.connection.close(), + timeout=self.RECONN_TIMEOUT, ) if self.recv_task: try: await asyncio.wait_for( - self.recv_task, timeout=self.RECONN_TIMEOUT + self.recv_task, + timeout=self.RECONN_TIMEOUT, ) except asyncio.TimeoutError: self.recv_task.cancel() @@ -227,7 +231,7 @@ async def restart(self) -> None: and (now - self.last_reconnect_attempt) < self.RECONNECT_THRESHOLD ): to_wait = self.RECONNECT_THRESHOLD + int( - self.RECONNECT_THRESHOLD - (now - self.last_reconnect_attempt) + self.RECONNECT_THRESHOLD - (now - self.last_reconnect_attempt), ) log.warning( "Client [%s] is reconnecting too frequently, sleeping for %s seconds", @@ -303,12 +307,12 @@ async def handle_packet(self, packet) -> None: try: if self.stored_msg_ids and msg.msg_id < self.stored_msg_ids[0]: raise SecurityCheckMismatch( - "The msg_id is lower than all the stored values" + "The msg_id is lower than all the stored values", ) if msg.msg_id in self.stored_msg_ids: raise SecurityCheckMismatch( - "The msg_id is equal to any of the stored values" + "The msg_id is equal to any of the stored values", ) time_diff = (msg.msg_id - MsgId()) / 2**32 @@ -316,13 +320,13 @@ async def handle_packet(self, packet) -> None: if time_diff > 30: raise SecurityCheckMismatch( "The msg_id belongs to over 30 seconds in the future. " - "Most likely the client time has to be synchronized." + "Most likely the client time has to be synchronized.", ) if time_diff < -300: raise SecurityCheckMismatch( "The msg_id belongs to over 300 seconds in the past. " - "Most likely the client time has to be synchronized." + "Most likely the client time has to be synchronized.", ) except SecurityCheckMismatch as e: log.info("Discarding packet: %s", e) @@ -332,7 +336,8 @@ async def handle_packet(self, packet) -> None: bisect.insort(self.stored_msg_ids, msg.msg_id) if isinstance( - msg.body, raw.types.MsgDetailedInfo | raw.types.MsgNewDetailedInfo + msg.body, + raw.types.MsgDetailedInfo | raw.types.MsgNewDetailedInfo, ): self.pending_acks.add(msg.body.answer_msg_id) continue @@ -343,7 +348,8 @@ async def handle_packet(self, packet) -> None: msg_id = None if isinstance( - msg.body, raw.types.BadMsgNotification | raw.types.BadServerSalt + msg.body, + raw.types.BadMsgNotification | raw.types.BadServerSalt, ): msg_id = msg.body.bad_msg_id elif isinstance(msg.body, FutureSalts | raw.types.RpcResult): @@ -362,7 +368,8 @@ async def handle_packet(self, packet) -> None: try: await self.send( - raw.types.MsgsAck(msg_ids=list(self.pending_acks)), False + raw.types.MsgsAck(msg_ids=list(self.pending_acks)), + False, ) except OSError: pass @@ -379,7 +386,8 @@ async def ping_worker(self) -> None: try: await asyncio.wait_for( - self.ping_task_event.wait(), self.PING_INTERVAL + self.ping_task_event.wait(), + self.PING_INTERVAL, ) except asyncio.TimeoutError: pass @@ -389,7 +397,8 @@ async def ping_worker(self) -> None: try: await self.send( raw.functions.PingDelayDisconnect( - ping_id=0, disconnect_delay=self.WAIT_TIMEOUT + 10 + ping_id=0, + disconnect_delay=self.WAIT_TIMEOUT + 10, ), False, ) @@ -418,7 +427,7 @@ async def recv_worker(self) -> None: if error_code == 404: raise Unauthorized( "Auth key not found in the system. You must delete your session file " - "and log in again with your phone number or bot token." + "and log in again with your phone number or bot token.", ) log.warning( @@ -534,7 +543,7 @@ async def invoke( while retries > 0: if self.currently_restarting: - while self.currently_restarting: + while self.currently_restarting: # noqa: ASYNC110 await asyncio.sleep(1) if self.instant_stop: diff --git a/pyrogram/storage/memory_storage.py b/pyrogram/storage/memory_storage.py index aa9c2ab1..0db90604 100644 --- a/pyrogram/storage/memory_storage.py +++ b/pyrogram/storage/memory_storage.py @@ -40,7 +40,7 @@ async def open(self) -> None: else self.OLD_SESSION_STRING_FORMAT_64 ), base64.urlsafe_b64decode( - self.session_string + "=" * (-len(self.session_string) % 4) + self.session_string + "=" * (-len(self.session_string) % 4), ), ) @@ -52,7 +52,7 @@ async def open(self) -> None: await self.date(0) log.warning( - "You are using an old session string format. Use export_session_string to update" + "You are using an old session string format. Use export_session_string to update", ) return if self.is_telethon_string: @@ -60,7 +60,8 @@ async def open(self) -> None: string = self.session_string[1:] ip_len = 4 if len(string) == 352 else 16 dc_id, ip, port, auth_key = struct.unpack( - f">B{ip_len}sH256s", base64.urlsafe_b64decode(string) + f">B{ip_len}sH256s", + base64.urlsafe_b64decode(string), ) api_id = 0 test_mode = False @@ -70,7 +71,7 @@ async def open(self) -> None: dc_id, api_id, test_mode, auth_key, user_id, is_bot = struct.unpack( self.SESSION_STRING_FORMAT, base64.urlsafe_b64decode( - self.session_string + "=" * (-len(self.session_string) % 4) + self.session_string + "=" * (-len(self.session_string) % 4), ), ) diff --git a/pyrogram/storage/sqlite_storage.py b/pyrogram/storage/sqlite_storage.py index 163f44c5..14122d39 100644 --- a/pyrogram/storage/sqlite_storage.py +++ b/pyrogram/storage/sqlite_storage.py @@ -92,7 +92,8 @@ def get_input_peer(peer_id: int, access_hash: int, peer_type: str): if peer_type in ["channel", "supergroup"]: return raw.types.InputPeerChannel( - channel_id=utils.get_channel_id(peer_id), access_hash=access_hash + channel_id=utils.get_channel_id(peer_id), + access_hash=access_hash, ) raise ValueError(f"Invalid peer type: {peer_type}") @@ -130,7 +131,8 @@ async def delete(self) -> NoReturn: raise NotImplementedError async def update_peers( - self, peers: list[tuple[int, int, str, str, str]] + self, + peers: list[tuple[int, int, str, str, str]], ) -> None: with contextlib.suppress(Exception): await self.conn.executemany( @@ -143,10 +145,12 @@ async def update_usernames(self, usernames: list[tuple[int, str]]) -> None: await self.conn.executescript(UNAME_SCHEMA) for user in usernames: await self.conn.execute( - "DELETE FROM usernames WHERE peer_id=?", (user[0],) + "DELETE FROM usernames WHERE peer_id=?", + (user[0],), ) await self.conn.executemany( - "REPLACE INTO usernames (peer_id, id)" "VALUES (?, ?)", usernames + "REPLACE INTO usernames (peer_id, id)" "VALUES (?, ?)", + usernames, ) async def update_state(self, value: tuple[int, int, int, int, int] = object): @@ -154,12 +158,13 @@ async def update_state(self, value: tuple[int, int, int, int, int] = object): return await ( await self.conn.execute( "SELECT id, pts, qts, date, seq FROM update_state " - "ORDER BY date ASC" + "ORDER BY date ASC", ) ).fetchall() if isinstance(value, int): await self.conn.execute( - "DELETE FROM update_state WHERE id = ?", (value,) + "DELETE FROM update_state WHERE id = ?", + (value,), ) else: await self.conn.execute( @@ -172,7 +177,8 @@ async def update_state(self, value: tuple[int, int, int, int, int] = object): async def get_peer_by_id(self, peer_id: int): q = await self.conn.execute( - "SELECT id, access_hash, type FROM peers WHERE id = ?", (peer_id,) + "SELECT id, access_hash, type FROM peers WHERE id = ?", + (peer_id,), ) r = await q.fetchone() diff --git a/pyrogram/storage/storage.py b/pyrogram/storage/storage.py index 4f444fc1..2957c9ff 100644 --- a/pyrogram/storage/storage.py +++ b/pyrogram/storage/storage.py @@ -39,13 +39,15 @@ async def delete(self) -> NoReturn: @abstractmethod async def update_peers( - self, peers: list[tuple[int, int, str, list[str], str]] + self, + peers: list[tuple[int, int, str, list[str], str]], ) -> NoReturn: raise NotImplementedError @abstractmethod async def update_state( - self, update_state: tuple[int, int, int, int, int] = object + self, + update_state: tuple[int, int, int, int, int] = object, ) -> NoReturn: raise NotImplementedError diff --git a/pyrogram/sync.py b/pyrogram/sync.py index 3e124d97..fb2e567c 100644 --- a/pyrogram/sync.py +++ b/pyrogram/sync.py @@ -27,7 +27,8 @@ async def anext(agen): item, done = loop.run_until_complete(anext(agen)) else: item, done = asyncio.run_coroutine_threadsafe( - anext(agen), loop + anext(agen), + loop, ).result() if done: @@ -62,7 +63,7 @@ def async_to_sync_wrap(*args, **kwargs): async def coro_wrapper(): return await asyncio.wrap_future( - asyncio.run_coroutine_threadsafe(coroutine, main_loop) + asyncio.run_coroutine_threadsafe(coroutine, main_loop), ) return coro_wrapper() @@ -99,7 +100,7 @@ def wrap(source) -> None: # Special case for idle and compose, because they are not inside Methods async_to_sync(idle_module, "idle") -idle = getattr(idle_module, "idle") +idle = idle_module.idle async_to_sync(compose_module, "compose") -compose = getattr(compose_module, "compose") +compose = compose_module.compose diff --git a/pyrogram/types/__init__.py b/pyrogram/types/__init__.py index 9a6f9bea..00091aa5 100644 --- a/pyrogram/types/__init__.py +++ b/pyrogram/types/__init__.py @@ -10,6 +10,7 @@ from .list import List from .messages_and_media import * from .object import Object +from .payments import * from .update import * from .user_and_chats import * diff --git a/pyrogram/types/authorization/__init__.py b/pyrogram/types/authorization/__init__.py index 39f5cfe1..05e231b7 100644 --- a/pyrogram/types/authorization/__init__.py +++ b/pyrogram/types/authorization/__init__.py @@ -8,6 +8,6 @@ __all__ = [ "ActiveSession", "ActiveSessions", - "TermsOfService", "SentCode", + "TermsOfService", ] diff --git a/pyrogram/types/authorization/active_session.py b/pyrogram/types/authorization/active_session.py index 1cb5a1a9..2c3eed69 100644 --- a/pyrogram/types/authorization/active_session.py +++ b/pyrogram/types/authorization/active_session.py @@ -137,7 +137,9 @@ def _parse(session: raw.types.Authorization) -> ActiveSession: is_password_pending=getattr(session, "password_pending", None), is_unconfirmed=getattr(session, "unconfirmed", None), can_accept_secret_chats=not getattr( - session, "encrypted_requests_disabled", False + session, + "encrypted_requests_disabled", + False, ), can_accept_calls=not getattr(session, "call_requests_disabled", False), is_official_application=getattr(session, "official_app", None), diff --git a/pyrogram/types/authorization/active_sessions.py b/pyrogram/types/authorization/active_sessions.py index f08ade3f..b35092df 100644 --- a/pyrogram/types/authorization/active_sessions.py +++ b/pyrogram/types/authorization/active_sessions.py @@ -37,6 +37,6 @@ def _parse( [ types.ActiveSession._parse(active) for active in authorizations.authorizations - ] + ], ), ) diff --git a/pyrogram/types/bots_and_keyboards/__init__.py b/pyrogram/types/bots_and_keyboards/__init__.py index e0418849..a939d97e 100644 --- a/pyrogram/types/bots_and_keyboards/__init__.py +++ b/pyrogram/types/bots_and_keyboards/__init__.py @@ -50,6 +50,16 @@ "BotAllowed", "BotApp", "BotBusinessConnection", + "BotCommand", + "BotCommandScope", + "BotCommandScopeAllChatAdministrators", + "BotCommandScopeAllGroupChats", + "BotCommandScopeAllPrivateChats", + "BotCommandScopeChat", + "BotCommandScopeChatAdministrators", + "BotCommandScopeChatMember", + "BotCommandScopeDefault", + "BotInfo", "CallbackGame", "CallbackQuery", "CollectibleItemInfo", @@ -59,29 +69,19 @@ "InlineKeyboardButtonBuy", "InlineKeyboardMarkup", "KeyboardButton", + "LoginUrl", + "MenuButton", + "MenuButtonCommands", + "MenuButtonDefault", + "MenuButtonWebApp", "ReplyKeyboardMarkup", "ReplyKeyboardRemove", "RequestPeerTypeChannel", "RequestPeerTypeChat", "RequestPeerTypeUser", - "RequestedChats", "RequestedChat", + "RequestedChats", "RequestedUser", - "LoginUrl", - "BotCommand", - "BotCommandScope", - "BotCommandScopeAllChatAdministrators", - "BotCommandScopeAllGroupChats", - "BotCommandScopeAllPrivateChats", - "BotCommandScopeChat", - "BotCommandScopeChatAdministrators", - "BotCommandScopeChatMember", - "BotCommandScopeDefault", - "BotInfo", - "WebAppInfo", - "MenuButton", - "MenuButtonCommands", - "MenuButtonWebApp", - "MenuButtonDefault", "SentWebAppMessage", + "WebAppInfo", ] diff --git a/pyrogram/types/bots_and_keyboards/bot_allowed.py b/pyrogram/types/bots_and_keyboards/bot_allowed.py index e7c6b064..8d7d7437 100644 --- a/pyrogram/types/bots_and_keyboards/bot_allowed.py +++ b/pyrogram/types/bots_and_keyboards/bot_allowed.py @@ -39,7 +39,8 @@ def __init__( @staticmethod def _parse( - client: pyrogram.Client, bot_allowed: raw.types.BotAllowed + client: pyrogram.Client, + bot_allowed: raw.types.BotAllowed, ) -> BotAllowed: bot_app = getattr(bot_allowed, "app", None) return BotAllowed( diff --git a/pyrogram/types/bots_and_keyboards/bot_command_scope_chat.py b/pyrogram/types/bots_and_keyboards/bot_command_scope_chat.py index 67a517bb..f0551207 100644 --- a/pyrogram/types/bots_and_keyboards/bot_command_scope_chat.py +++ b/pyrogram/types/bots_and_keyboards/bot_command_scope_chat.py @@ -22,5 +22,5 @@ def __init__(self, chat_id: int | str) -> None: async def write(self, client: pyrogram.Client) -> raw.base.BotCommandScope: return raw.types.BotCommandScopePeer( - peer=await client.resolve_peer(self.chat_id) + peer=await client.resolve_peer(self.chat_id), ) diff --git a/pyrogram/types/bots_and_keyboards/bot_command_scope_chat_administrators.py b/pyrogram/types/bots_and_keyboards/bot_command_scope_chat_administrators.py index 23f78d81..afdafbbc 100644 --- a/pyrogram/types/bots_and_keyboards/bot_command_scope_chat_administrators.py +++ b/pyrogram/types/bots_and_keyboards/bot_command_scope_chat_administrators.py @@ -22,5 +22,5 @@ def __init__(self, chat_id: int | str) -> None: async def write(self, client: pyrogram.Client) -> raw.base.BotCommandScope: return raw.types.BotCommandScopePeerAdmins( - peer=await client.resolve_peer(self.chat_id) + peer=await client.resolve_peer(self.chat_id), ) diff --git a/pyrogram/types/bots_and_keyboards/callback_query.py b/pyrogram/types/bots_and_keyboards/callback_query.py index 9d680863..a90e3a8d 100644 --- a/pyrogram/types/bots_and_keyboards/callback_query.py +++ b/pyrogram/types/bots_and_keyboards/callback_query.py @@ -74,7 +74,9 @@ def __init__( @staticmethod async def _parse( - client: pyrogram.Client, callback_query, users + client: pyrogram.Client, + callback_query, + users, ) -> CallbackQuery: message = None inline_message_id = None @@ -208,7 +210,9 @@ async def edit_message_text( disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup, business_connection_id=getattr( - self.message, "business_connection_id", None + self.message, + "business_connection_id", + None, ), ) return await self._client.edit_inline_text( @@ -257,7 +261,9 @@ async def edit_message_caption( parse_mode, reply_markup=reply_markup, business_connection_id=getattr( - self.message, "business_connection_id", None + self.message, + "business_connection_id", + None, ) if business_connection_id is None else business_connection_id, @@ -298,7 +304,9 @@ async def edit_message_media( media=media, reply_markup=reply_markup, business_connection_id=getattr( - self.message, "business_connection_id", None + self.message, + "business_connection_id", + None, ) if business_connection_id is None else business_connection_id, @@ -339,7 +347,9 @@ async def edit_message_reply_markup( message_id=self.message.id, reply_markup=reply_markup, business_connection_id=getattr( - self.message, "business_connection_id", None + self.message, + "business_connection_id", + None, ) if business_connection_id is None else business_connection_id, diff --git a/pyrogram/types/bots_and_keyboards/collectible_item_info.py b/pyrogram/types/bots_and_keyboards/collectible_item_info.py index 13927f27..53627233 100644 --- a/pyrogram/types/bots_and_keyboards/collectible_item_info.py +++ b/pyrogram/types/bots_and_keyboards/collectible_item_info.py @@ -52,7 +52,7 @@ def _parse( ) -> CollectibleItemInfo: return CollectibleItemInfo( purchase_date=utils.timestamp_to_datetime( - collectible_info.purchase_date + collectible_info.purchase_date, ), currency=collectible_info.currency, amount=collectible_info.amount, diff --git a/pyrogram/types/bots_and_keyboards/game_high_score.py b/pyrogram/types/bots_and_keyboards/game_high_score.py index cab2c88b..4d0e62f7 100644 --- a/pyrogram/types/bots_and_keyboards/game_high_score.py +++ b/pyrogram/types/bots_and_keyboards/game_high_score.py @@ -35,7 +35,9 @@ def __init__( @staticmethod def _parse( - client, game_high_score: raw.types.HighScore, users: dict + client, + game_high_score: raw.types.HighScore, + users: dict, ) -> GameHighScore: users = {i.id: i for i in users} diff --git a/pyrogram/types/bots_and_keyboards/inline_keyboard_button.py b/pyrogram/types/bots_and_keyboards/inline_keyboard_button.py index 2729ed66..24e6f28a 100644 --- a/pyrogram/types/bots_and_keyboards/inline_keyboard_button.py +++ b/pyrogram/types/bots_and_keyboards/inline_keyboard_button.py @@ -107,7 +107,8 @@ def read(b: raw.base.KeyboardButton): if isinstance(b, raw.types.KeyboardButtonUrlAuth): return InlineKeyboardButton( - text=b.text, login_url=types.LoginUrl.read(b) + text=b.text, + login_url=types.LoginUrl.read(b), ) if isinstance(b, raw.types.KeyboardButtonUserProfile): @@ -123,12 +124,14 @@ def read(b: raw.base.KeyboardButton): if isinstance(b, raw.types.KeyboardButtonGame): return InlineKeyboardButton( - text=b.text, callback_game=types.CallbackGame() + text=b.text, + callback_game=types.CallbackGame(), ) if isinstance(b, raw.types.KeyboardButtonWebView): return InlineKeyboardButton( - text=b.text, web_app=types.WebAppInfo(url=b.url) + text=b.text, + web_app=types.WebAppInfo(url=b.url), ) if isinstance(b, raw.types.KeyboardButtonCopy): @@ -170,7 +173,8 @@ async def write(self, client: pyrogram.Client): if self.switch_inline_query is not None: return raw.types.KeyboardButtonSwitchInline( - text=self.text, query=self.switch_inline_query + text=self.text, + query=self.switch_inline_query, ) if self.switch_inline_query_current_chat is not None: @@ -185,10 +189,12 @@ async def write(self, client: pyrogram.Client): if self.web_app is not None: return raw.types.KeyboardButtonWebView( - text=self.text, url=self.web_app.url + text=self.text, + url=self.web_app.url, ) if self.copy_text is not None: return raw.types.KeyboardButtonCopy( - text=self.text, copy_text=self.copy_text + text=self.text, + copy_text=self.copy_text, ) return None diff --git a/pyrogram/types/bots_and_keyboards/keyboard_button.py b/pyrogram/types/bots_and_keyboards/keyboard_button.py index 9c99cd00..8cdf3b78 100644 --- a/pyrogram/types/bots_and_keyboards/keyboard_button.py +++ b/pyrogram/types/bots_and_keyboards/keyboard_button.py @@ -152,6 +152,7 @@ def write(self): ) if self.web_app: return raw.types.KeyboardButtonSimpleWebView( - text=self.text, url=self.web_app.url + text=self.text, + url=self.web_app.url, ) return raw.types.KeyboardButton(text=self.text) diff --git a/pyrogram/types/bots_and_keyboards/reply_keyboard_markup.py b/pyrogram/types/bots_and_keyboards/reply_keyboard_markup.py index 139f263a..8e295cae 100644 --- a/pyrogram/types/bots_and_keyboards/reply_keyboard_markup.py +++ b/pyrogram/types/bots_and_keyboards/reply_keyboard_markup.py @@ -83,7 +83,7 @@ async def write(self, _: pyrogram.Client): if isinstance(j, str) else j.write() for j in i - ] + ], ) for i in self.keyboard ], diff --git a/pyrogram/types/bots_and_keyboards/sent_web_app_message.py b/pyrogram/types/bots_and_keyboards/sent_web_app_message.py index 5b5576fe..1516d5bc 100644 --- a/pyrogram/types/bots_and_keyboards/sent_web_app_message.py +++ b/pyrogram/types/bots_and_keyboards/sent_web_app_message.py @@ -25,5 +25,5 @@ def __init__( @staticmethod def _parse(obj: raw.types.WebViewMessageSent): return SentWebAppMessage( - inline_message_id=utils.pack_inline_message_id(obj.msg_id) + inline_message_id=utils.pack_inline_message_id(obj.msg_id), ) diff --git a/pyrogram/types/business/__init__.py b/pyrogram/types/business/__init__.py index e10c0bd4..da0ea250 100644 --- a/pyrogram/types/business/__init__.py +++ b/pyrogram/types/business/__init__.py @@ -17,17 +17,17 @@ __all__ = [ "ExtendedMediaPreview", - "Invoice", "InputStarsTransaction", + "Invoice", "PaidMedia", "PaidMediaPreview", "PaymentInfo", "PaymentRefunded", "PreCheckoutQuery", - "StarsStatus", - "StarsTransaction", "ShippingAddress", "ShippingOption", "ShippingQuery", + "StarsStatus", + "StarsTransaction", "SuccessfulPayment", ] diff --git a/pyrogram/types/business/extended_media_preview.py b/pyrogram/types/business/extended_media_preview.py index 007cd87e..fb109667 100644 --- a/pyrogram/types/business/extended_media_preview.py +++ b/pyrogram/types/business/extended_media_preview.py @@ -38,7 +38,8 @@ def __init__( @staticmethod def _parse( - client, media: raw.types.MessageExtendedMediaPreview + client, + media: raw.types.MessageExtendedMediaPreview, ) -> ExtendedMediaPreview: thumb = None if media.thumb: diff --git a/pyrogram/types/business/invoice.py b/pyrogram/types/business/invoice.py index 9380fbbb..024ebef8 100644 --- a/pyrogram/types/business/invoice.py +++ b/pyrogram/types/business/invoice.py @@ -119,7 +119,8 @@ def __init__( @staticmethod def _parse( - client, invoice: raw.types.MessageMediaInvoice | raw.types.Invoice + client, + invoice: raw.types.MessageMediaInvoice | raw.types.Invoice, ) -> Invoice: return Invoice( currency=invoice.currency, @@ -135,7 +136,9 @@ def _parse( is_phone_requested=getattr(invoice, "phone_requested", None), is_email_requested=getattr(invoice, "email_requested", None), is_shipping_address_requested=getattr( - invoice, "shipping_address_requested", None + invoice, + "shipping_address_requested", + None, ), is_flexible=getattr(invoice, "flexible", None), is_phone_to_provider=getattr(invoice, "phone_to_provider", None), diff --git a/pyrogram/types/business/paid_media.py b/pyrogram/types/business/paid_media.py index 0c2763a4..959c6cf8 100644 --- a/pyrogram/types/business/paid_media.py +++ b/pyrogram/types/business/paid_media.py @@ -37,7 +37,7 @@ def _parse(client, media: raw.types.MessageMediaPaidMedia) -> PaidMedia: extended_media.append(types.ExtendedMediaPreview._parse(client, m)) elif isinstance(m.media, raw.types.MessageMediaPhoto): extended_media.append( - types.Photo._parse(client, m.media.photo, m.media.ttl_seconds) + types.Photo._parse(client, m.media.photo, m.media.ttl_seconds), ) elif isinstance(m.media, raw.types.MessageMediaDocument): attributes = {type(i): i for i in m.media.document.attributes} @@ -48,7 +48,8 @@ def _parse(client, media: raw.types.MessageMediaPaidMedia) -> PaidMedia: ) if raw.types.DocumentAttributeAnimated in attributes: video_attributes = attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) extended_media.append( types.Animation._parse( @@ -56,7 +57,7 @@ def _parse(client, media: raw.types.MessageMediaPaidMedia) -> PaidMedia: m.media.document, video_attributes, file_name, - ) + ), ) else: video_attributes = attributes[raw.types.DocumentAttributeVideo] @@ -67,7 +68,7 @@ def _parse(client, media: raw.types.MessageMediaPaidMedia) -> PaidMedia: video_attributes, file_name, m.media.ttl_seconds, - ) + ), ) return PaidMedia( stars_amount=media.stars_amount, diff --git a/pyrogram/types/business/pre_checkout_query.py b/pyrogram/types/business/pre_checkout_query.py index 79b93b73..19945ddb 100644 --- a/pyrogram/types/business/pre_checkout_query.py +++ b/pyrogram/types/business/pre_checkout_query.py @@ -56,7 +56,9 @@ def __init__( @staticmethod async def _parse( - client: pyrogram.Client, pre_checkout_query, users + client: pyrogram.Client, + pre_checkout_query, + users, ) -> PreCheckoutQuery: # Try to decode pre-checkout query payload into string. If that fails, fallback to bytes instead of decoding by # ignoring/replacing errors, this way, button clicks will still work. diff --git a/pyrogram/types/business/stars_transaction.py b/pyrogram/types/business/stars_transaction.py index cce94948..2dfb9873 100644 --- a/pyrogram/types/business/stars_transaction.py +++ b/pyrogram/types/business/stars_transaction.py @@ -88,7 +88,9 @@ def __init__( @staticmethod def _parse( - client, transaction: raw.types.StarsTransaction, users: dict + client, + transaction: raw.types.StarsTransaction, + users: dict, ) -> StarsTransaction: chat_id = utils.get_raw_peer_id(transaction.peer.peer) chat = types.User._parse(client, users.get(chat_id)) @@ -107,7 +109,7 @@ def _parse( title=transaction.title, description=transaction.description, transaction_date=utils.timestamp_to_datetime( - transaction.transaction_date + transaction.transaction_date, ), transaction_url=transaction.transaction_url, payload=payload, diff --git a/pyrogram/types/inline_mode/__init__.py b/pyrogram/types/inline_mode/__init__.py index a7a76717..079c8e10 100644 --- a/pyrogram/types/inline_mode/__init__.py +++ b/pyrogram/types/inline_mode/__init__.py @@ -36,24 +36,24 @@ from .inline_query_result_voice import InlineQueryResultVoice __all__ = [ + "ChosenInlineResult", "InlineQuery", "InlineQueryResult", - "InlineQueryResultArticle", - "InlineQueryResultPhoto", "InlineQueryResultAnimation", + "InlineQueryResultArticle", "InlineQueryResultAudio", - "InlineQueryResultVideo", - "ChosenInlineResult", - "InlineQueryResultContact", - "InlineQueryResultDocument", - "InlineQueryResultVoice", - "InlineQueryResultLocation", - "InlineQueryResultVenue", - "InlineQueryResultCachedPhoto", "InlineQueryResultCachedAnimation", - "InlineQueryResultCachedSticker", + "InlineQueryResultCachedAudio", "InlineQueryResultCachedDocument", + "InlineQueryResultCachedPhoto", + "InlineQueryResultCachedSticker", "InlineQueryResultCachedVideo", "InlineQueryResultCachedVoice", - "InlineQueryResultCachedAudio", + "InlineQueryResultContact", + "InlineQueryResultDocument", + "InlineQueryResultLocation", + "InlineQueryResultPhoto", + "InlineQueryResultVenue", + "InlineQueryResultVideo", + "InlineQueryResultVoice", ] diff --git a/pyrogram/types/inline_mode/inline_query_result_animation.py b/pyrogram/types/inline_mode/inline_query_result_animation.py index b6f6320c..38f116a3 100644 --- a/pyrogram/types/inline_mode/inline_query_result_animation.py +++ b/pyrogram/types/inline_mode/inline_query_result_animation.py @@ -102,7 +102,7 @@ async def write(self, client: pyrogram.Client): w=self.animation_width, h=self.animation_height, duration=self.animation_duration, - ) + ), ], ) diff --git a/pyrogram/types/inline_mode/inline_query_result_article.py b/pyrogram/types/inline_mode/inline_query_result_article.py index 27532f88..437cd95f 100644 --- a/pyrogram/types/inline_mode/inline_query_result_article.py +++ b/pyrogram/types/inline_mode/inline_query_result_article.py @@ -65,7 +65,8 @@ async def write(self, client: pyrogram.Client): id=self.id, type=self.type, send_message=await self.input_message_content.write( - client, self.reply_markup + client, + self.reply_markup, ), title=self.title, description=self.description, @@ -76,8 +77,9 @@ async def write(self, client: pyrogram.Client): mime_type="image/jpeg", attributes=[ raw.types.DocumentAttributeImageSize( - w=self.thumb_width, h=self.thumb_height - ) + w=self.thumb_width, + h=self.thumb_height, + ), ], ) if self.thumb_url diff --git a/pyrogram/types/inline_mode/inline_query_result_audio.py b/pyrogram/types/inline_mode/inline_query_result_audio.py index e30e735a..bbff89ab 100644 --- a/pyrogram/types/inline_mode/inline_query_result_audio.py +++ b/pyrogram/types/inline_mode/inline_query_result_audio.py @@ -90,7 +90,7 @@ async def write(self, client: pyrogram.Client): duration=self.audio_duration, title=self.title, performer=self.performer, - ) + ), ], ) diff --git a/pyrogram/types/inline_mode/inline_query_result_contact.py b/pyrogram/types/inline_mode/inline_query_result_contact.py index 6791d0dd..7ba67baa 100644 --- a/pyrogram/types/inline_mode/inline_query_result_contact.py +++ b/pyrogram/types/inline_mode/inline_query_result_contact.py @@ -93,8 +93,9 @@ async def write(self, client: pyrogram.Client): mime_type="image/jpg", attributes=[ raw.types.DocumentAttributeImageSize( - w=self.thumb_width, h=self.thumb_height - ) + w=self.thumb_width, + h=self.thumb_height, + ), ], ) if self.thumb_url diff --git a/pyrogram/types/inline_mode/inline_query_result_document.py b/pyrogram/types/inline_mode/inline_query_result_document.py index e9384c94..5fdde2fa 100644 --- a/pyrogram/types/inline_mode/inline_query_result_document.py +++ b/pyrogram/types/inline_mode/inline_query_result_document.py @@ -100,8 +100,9 @@ async def write(self, client: pyrogram.Client): mime_type="image/jpeg", attributes=[ raw.types.DocumentAttributeImageSize( - w=self.thumb_width, h=self.thumb_height - ) + w=self.thumb_width, + h=self.thumb_height, + ), ], ) if self.thumb_url diff --git a/pyrogram/types/inline_mode/inline_query_result_location.py b/pyrogram/types/inline_mode/inline_query_result_location.py index d68a550e..a52ee11b 100644 --- a/pyrogram/types/inline_mode/inline_query_result_location.py +++ b/pyrogram/types/inline_mode/inline_query_result_location.py @@ -95,7 +95,8 @@ async def write(self, client: pyrogram.Client): if self.input_message_content else raw.types.InputBotInlineMessageMediaGeo( geo_point=raw.types.InputGeoPoint( - lat=self.latitude, long=self.longitude + lat=self.latitude, + long=self.longitude, ), heading=self.heading, period=self.live_period, diff --git a/pyrogram/types/inline_mode/inline_query_result_photo.py b/pyrogram/types/inline_mode/inline_query_result_photo.py index 12ce0367..c2c7cb25 100644 --- a/pyrogram/types/inline_mode/inline_query_result_photo.py +++ b/pyrogram/types/inline_mode/inline_query_result_photo.py @@ -91,8 +91,9 @@ async def write(self, client: pyrogram.Client): mime_type="image/jpeg", attributes=[ raw.types.DocumentAttributeImageSize( - w=self.photo_width, h=self.photo_height - ) + w=self.photo_width, + h=self.photo_height, + ), ], ) diff --git a/pyrogram/types/inline_mode/inline_query_result_venue.py b/pyrogram/types/inline_mode/inline_query_result_venue.py index 0916d54b..9fae040c 100644 --- a/pyrogram/types/inline_mode/inline_query_result_venue.py +++ b/pyrogram/types/inline_mode/inline_query_result_venue.py @@ -98,7 +98,8 @@ async def write(self, client: pyrogram.Client): if self.input_message_content else raw.types.InputBotInlineMessageMediaVenue( geo_point=raw.types.InputGeoPoint( - lat=self.latitude, long=self.longitude + lat=self.latitude, + long=self.longitude, ), title=self.title, address=self.address, diff --git a/pyrogram/types/inline_mode/inline_query_result_video.py b/pyrogram/types/inline_mode/inline_query_result_video.py index 55f35a67..a7ec713a 100644 --- a/pyrogram/types/inline_mode/inline_query_result_video.py +++ b/pyrogram/types/inline_mode/inline_query_result_video.py @@ -102,7 +102,7 @@ async def write(self, client: pyrogram.Client): duration=self.video_duration, w=self.video_width, h=self.video_height, - ) + ), ], ) diff --git a/pyrogram/types/inline_mode/inline_query_result_voice.py b/pyrogram/types/inline_mode/inline_query_result_voice.py index 78f221c1..3475e15f 100644 --- a/pyrogram/types/inline_mode/inline_query_result_voice.py +++ b/pyrogram/types/inline_mode/inline_query_result_voice.py @@ -74,7 +74,7 @@ async def write(self, client: pyrogram.Client): raw.types.DocumentAttributeAudio( duration=self.voice_duration, title=self.title, - ) + ), ], ) diff --git a/pyrogram/types/input_media/__init__.py b/pyrogram/types/input_media/__init__.py index 89de467c..faae56d1 100644 --- a/pyrogram/types/input_media/__init__.py +++ b/pyrogram/types/input_media/__init__.py @@ -13,11 +13,11 @@ __all__ = [ "InputMedia", "InputMediaAnimation", + "InputMediaArea", + "InputMediaAreaChannelPost", "InputMediaAudio", "InputMediaDocument", "InputMediaPhoto", "InputMediaVideo", "InputPhoneContact", - "InputMediaArea", - "InputMediaAreaChannelPost", ] diff --git a/pyrogram/types/input_message_content/__init__.py b/pyrogram/types/input_message_content/__init__.py index 137dd6ad..8a62788b 100644 --- a/pyrogram/types/input_message_content/__init__.py +++ b/pyrogram/types/input_message_content/__init__.py @@ -12,12 +12,12 @@ from .input_venue_message_content import InputVenueMessageContent __all__ = [ + "InputContactMessageContent", + "InputInvoiceMessageContent", + "InputLocationMessageContent", "InputMessageContent", "InputReplyToMessage", "InputReplyToStory", "InputTextMessageContent", - "InputLocationMessageContent", "InputVenueMessageContent", - "InputContactMessageContent", - "InputInvoiceMessageContent", ] diff --git a/pyrogram/types/input_message_content/input_invoice_message_content.py b/pyrogram/types/input_message_content/input_invoice_message_content.py index b714bd4d..137ccffa 100644 --- a/pyrogram/types/input_message_content/input_invoice_message_content.py +++ b/pyrogram/types/input_message_content/input_invoice_message_content.py @@ -132,8 +132,9 @@ async def write(self, client: pyrogram.Client, reply_markup): size=self.photo_size, attributes=[ raw.types.DocumentAttributeImageSize( - w=self.photo_width, h=self.photo_height - ) + w=self.photo_width, + h=self.photo_height, + ), ], ) if self.photo_url @@ -155,7 +156,7 @@ async def write(self, client: pyrogram.Client, reply_markup): else self.payload, provider=self.provider_token, provider_data=raw.types.DataJSON( - data=self.provider_data if self.provider_data else "{}" + data=self.provider_data if self.provider_data else "{}", ), reply_markup=await reply_markup.write(client) if reply_markup else None, ) diff --git a/pyrogram/types/input_message_content/input_reply_to_story.py b/pyrogram/types/input_message_content/input_reply_to_story.py index 14f891c9..d8682f16 100644 --- a/pyrogram/types/input_message_content/input_reply_to_story.py +++ b/pyrogram/types/input_message_content/input_reply_to_story.py @@ -13,7 +13,7 @@ class InputReplyToStory(Object): An InputPeer. story_id (``int``): - Unique identifier for the target story. + If the message is a reply, ID of the target story. """ def __init__( @@ -29,5 +29,6 @@ def __init__( def write(self): return raw.types.InputReplyToStory( - peer=self.peer, story_id=self.story_id + peer=self.peer, + story_id=self.story_id, ).write() diff --git a/pyrogram/types/input_message_content/input_venue_message_content.py b/pyrogram/types/input_message_content/input_venue_message_content.py index 3e5ca3d9..7c476458 100644 --- a/pyrogram/types/input_message_content/input_venue_message_content.py +++ b/pyrogram/types/input_message_content/input_venue_message_content.py @@ -59,7 +59,8 @@ def __init__( async def write(self, client: pyrogram.Client, reply_markup): return raw.types.InputBotInlineMessageMediaVenue( geo_point=raw.types.InputGeoPoint( - lat=self.latitude, long=self.longitude + lat=self.latitude, + long=self.longitude, ), title=self.title, address=self.address, diff --git a/pyrogram/types/input_privacy_rule/input_privacy_rule_allow_chats.py b/pyrogram/types/input_privacy_rule/input_privacy_rule_allow_chats.py index 687f3175..1296c32f 100644 --- a/pyrogram/types/input_privacy_rule/input_privacy_rule_allow_chats.py +++ b/pyrogram/types/input_privacy_rule/input_privacy_rule_allow_chats.py @@ -37,5 +37,5 @@ async def write(self, client: pyrogram.Client): chats = await asyncio.gather(*[client.resolve_peer(i) for i in chats]) return raw.types.InputPrivacyValueAllowChatParticipants( - chats=[utils.get_peer_id(i) for i in chats] + chats=[utils.get_peer_id(i) for i in chats], ) diff --git a/pyrogram/types/input_privacy_rule/input_privacy_rule_disallow_chats.py b/pyrogram/types/input_privacy_rule/input_privacy_rule_disallow_chats.py index 2ba03cf0..3cd2472b 100644 --- a/pyrogram/types/input_privacy_rule/input_privacy_rule_disallow_chats.py +++ b/pyrogram/types/input_privacy_rule/input_privacy_rule_disallow_chats.py @@ -37,5 +37,5 @@ async def write(self, client: pyrogram.Client): chats = await asyncio.gather(*[client.resolve_peer(i) for i in chats]) return raw.types.InputPrivacyValueDisallowChatParticipants( - chats=[utils.get_peer_id(i) for i in chats] + chats=[utils.get_peer_id(i) for i in chats], ) diff --git a/pyrogram/types/messages_and_media/__init__.py b/pyrogram/types/messages_and_media/__init__.py index 956d4627..73f5aa8a 100644 --- a/pyrogram/types/messages_and_media/__init__.py +++ b/pyrogram/types/messages_and_media/__init__.py @@ -69,8 +69,10 @@ "AvailableEffect", "Contact", "ContactRegistered", - "DraftMessage", + "Dice", "Document", + "DraftMessage", + "ExportedStoryLink", "Game", "GiftedPremium", "Giveaway", @@ -83,41 +85,39 @@ "MediaAreaCoordinates", "Message", "MessageEntity", + "MessageReactionCountUpdated", + "MessageReactionUpdated", + "MessageReactions", + "MessageReactor", + "MessageStory", + "PaymentForm", "Photo", - "Thumbnail", - "StrippedThumbnail", "Poll", "PollOption", - "PaymentForm", + "Reaction", + "ReactionCount", + "ReactionType", + "ReactionTypeCustomEmoji", + "ReactionTypeEmoji", + "ReactionTypePaid", + "ScreenshotTaken", "Sticker", "StickerSet", + "StoriesPrivacyRules", + "Story", + "StoryDeleted", + "StoryForwardHeader", + "StorySkipped", + "StoryViews", + "StrippedThumbnail", + "Thumbnail", + "TranslatedText", "Venue", "Video", "VideoNote", "Voice", + "WebAppData", "WebPage", "WebPageEmpty", "WebPagePreview", - "Dice", - "WebAppData", - "MessageReactions", - "MessageReactor", - "MessageReactionUpdated", - "MessageReactionCountUpdated", - "MessageStory", - "Story", - "StoryDeleted", - "StorySkipped", - "StoryViews", - "StoryForwardHeader", - "Reaction", - "ReactionType", - "ReactionTypeEmoji", - "ReactionTypeCustomEmoji", - "ReactionTypePaid", - "ReactionCount", - "TranslatedText", - "StoriesPrivacyRules", - "ExportedStoryLink", - "ScreenshotTaken", ] diff --git a/pyrogram/types/messages_and_media/alternative_video.py b/pyrogram/types/messages_and_media/alternative_video.py index 3c3685b0..932d25f4 100644 --- a/pyrogram/types/messages_and_media/alternative_video.py +++ b/pyrogram/types/messages_and_media/alternative_video.py @@ -75,7 +75,7 @@ def __init__( supports_streaming: bool | None = None, date: datetime | None = None, thumbs: list[types.Thumbnail] | None = None, - ): + ) -> None: super().__init__(client) self.file_id = file_id self.file_unique_id = file_unique_id @@ -111,7 +111,8 @@ def _parse( file_unique_id = ( FileUniqueId( - file_unique_type=FileUniqueType.DOCUMENT, media_id=video.id + file_unique_type=FileUniqueType.DOCUMENT, + media_id=video.id, ).encode() if video else None diff --git a/pyrogram/types/messages_and_media/draft_message.py b/pyrogram/types/messages_and_media/draft_message.py index f4e159b1..0e02f5e5 100644 --- a/pyrogram/types/messages_and_media/draft_message.py +++ b/pyrogram/types/messages_and_media/draft_message.py @@ -147,7 +147,10 @@ def _parse( if video_attributes.round_message: video_note = types.VideoNote._parse( - client, doc, video_attributes, media.ttl_seconds + client, + doc, + video_attributes, + media.ttl_seconds, ) media_type = enums.MessageMediaType.VIDEO_NOTE @@ -158,7 +161,10 @@ def _parse( if audio_attributes.voice: voice = types.Voice._parse( - client, doc, audio_attributes, media.ttl_seconds + client, + doc, + audio_attributes, + media.ttl_seconds, ) media_type = enums.MessageMediaType.VOICE @@ -196,7 +202,9 @@ def _parse( video_note=video_note, voice=voice, show_caption_above_media=getattr( - raw_draft_message, "invert_media", False + raw_draft_message, + "invert_media", + False, ), file_name=file_name, media=media_type, diff --git a/pyrogram/types/messages_and_media/giveaway.py b/pyrogram/types/messages_and_media/giveaway.py index 164546cb..4663ff8e 100644 --- a/pyrogram/types/messages_and_media/giveaway.py +++ b/pyrogram/types/messages_and_media/giveaway.py @@ -70,8 +70,8 @@ async def _parse(client, message: raw.types.Message) -> Giveaway: try: chat = await client.invoke( raw.functions.channels.GetChannels( - id=[await client.resolve_peer(chat_id)] - ) + id=[await client.resolve_peer(chat_id)], + ), ) except FloodWait as e: await asyncio.sleep(e.value) diff --git a/pyrogram/types/messages_and_media/giveaway_result.py b/pyrogram/types/messages_and_media/giveaway_result.py index b5bd7c19..5154abfa 100644 --- a/pyrogram/types/messages_and_media/giveaway_result.py +++ b/pyrogram/types/messages_and_media/giveaway_result.py @@ -88,12 +88,13 @@ async def _parse( chat_id = utils.get_channel_id(giveaway_result.channel_id) chat = await client.invoke( raw.functions.channels.GetChannels( - id=[await client.resolve_peer(chat_id)] - ) + id=[await client.resolve_peer(chat_id)], + ), ) chat = types.Chat._parse_chat(client, chat.chats[0]) giveaway_message = await client.get_messages( - chat_id, giveaway_result.launch_msg_id + chat_id, + giveaway_result.launch_msg_id, ) expired_date = utils.timestamp_to_datetime(giveaway_result.until_date) winners = [] diff --git a/pyrogram/types/messages_and_media/media_area.py b/pyrogram/types/messages_and_media/media_area.py index 26d55ef9..7656300e 100644 --- a/pyrogram/types/messages_and_media/media_area.py +++ b/pyrogram/types/messages_and_media/media_area.py @@ -19,7 +19,8 @@ def __init__(self, coordinates: types.MediaAreaCoordinates) -> None: self.coordinates = coordinates async def _parse( - self: pyrogram.Client, media_area: raw.base.MediaArea + self: pyrogram.Client, + media_area: raw.base.MediaArea, ) -> MediaArea: if isinstance(media_area, raw.types.MediaAreaChannelPost): return await types.MediaAreaChannelPost._parse(self, media_area) diff --git a/pyrogram/types/messages_and_media/media_area_channel_post.py b/pyrogram/types/messages_and_media/media_area_channel_post.py index 0ba15755..16cac047 100644 --- a/pyrogram/types/messages_and_media/media_area_channel_post.py +++ b/pyrogram/types/messages_and_media/media_area_channel_post.py @@ -42,8 +42,8 @@ async def _parse( ( await self.invoke( raw.functions.channels.GetChannels( - id=[await self.resolve_peer(channel_id)] - ) + id=[await self.resolve_peer(channel_id)], + ), ) ).chats[0], ) diff --git a/pyrogram/types/messages_and_media/message.py b/pyrogram/types/messages_and_media/message.py index bfd1a26f..7fdb952e 100644 --- a/pyrogram/types/messages_and_media/message.py +++ b/pyrogram/types/messages_and_media/message.py @@ -41,7 +41,7 @@ def html(self): def __getitem__(self, item): return parser_utils.remove_surrogates( - parser_utils.add_surrogates(self)[item] + parser_utils.add_surrogates(self)[item], ) @@ -717,7 +717,7 @@ async def wait_for_click( ) @staticmethod - async def _parse( + async def _parse( # noqa: C901 client: pyrogram.Client, message: raw.base.Message, users: dict, @@ -745,8 +745,8 @@ async def _parse( id=[ await client.resolve_peer(from_id), await client.resolve_peer(peer_id), - ] - ) + ], + ), ) except PeerIdInvalid: pass @@ -814,8 +814,9 @@ async def _parse( elif isinstance(action, raw.types.MessageActionChatJoinedByLink): new_chat_members = [ types.User._parse( - client, users[utils.get_raw_peer_id(message.from_id)] - ) + client, + users[utils.get_raw_peer_id(message.from_id)], + ), ] service_type = enums.MessageServiceType.NEW_CHAT_MEMBERS chat_join_type = enums.ChatJoinType.BY_LINK @@ -894,7 +895,9 @@ async def _parse( service_type = enums.MessageServiceType.VIDEO_CHAT_STARTED elif isinstance(action, raw.types.MessageActionInviteToGroupCall): video_chat_members_invited = types.VideoChatMembersInvited._parse( - client, action, users + client, + action, + users, ) service_type = enums.MessageServiceType.VIDEO_CHAT_MEMBERS_INVITED elif isinstance(action, raw.types.MessageActionWebViewDataSentMe): @@ -902,7 +905,9 @@ async def _parse( service_type = enums.MessageServiceType.WEB_APP_DATA elif isinstance(action, raw.types.MessageActionGiftPremium): gifted_premium = await types.GiftedPremium._parse( - client, action, from_user.id + client, + action, + from_user.id, ) service_type = enums.MessageServiceType.GIFTED_PREMIUM elif isinstance(action, raw.types.MessageActionGiveawayLaunch): @@ -910,7 +915,9 @@ async def _parse( service_type = enums.MessageServiceType.GIVEAWAY_LAUNCHED elif isinstance(action, raw.types.MessageActionGiveawayResults): giveaway_result = await types.GiveawayResult._parse( - client, action, True + client, + action, + True, ) service_type = enums.MessageServiceType.GIVEAWAY_RESULT elif isinstance(action, raw.types.MessageActionBoostApply): @@ -940,12 +947,16 @@ async def _parse( service_type = enums.MessageServiceType.GIFT_CODE elif isinstance(action, raw.types.MessageActionStarGift): user_gift = await types.UserGift._parse_action( - client, message, users + client, + message, + users, ) service_type = enums.MessageServiceType.USER_GIFT elif isinstance(action, raw.types.MessageActionStarGift): star_gift = await types.StarGift._parse_action( - client, message, users + client, + message, + users, ) service_type = enums.MessageServiceType.STAR_GIFT elif isinstance(action, raw.types.MessageActionScreenshotTaken): @@ -1023,7 +1034,9 @@ async def _parse( if isinstance(action, raw.types.MessageActionGameScore): parsed_message.game_high_score = types.GameHighScore._parse_action( - client, message, users + client, + message, + users, ) if message.reply_to and replies: @@ -1094,7 +1107,8 @@ async def _parse( forward_from = types.User._parse(client, users[raw_peer_id]) else: forward_from_chat = types.Chat._parse_channel_chat( - client, chats[raw_peer_id] + client, + chats[raw_peer_id], ) forward_from_message_id = forward_header.channel_post forward_signature = forward_header.post_author @@ -1130,7 +1144,9 @@ async def _parse( if media: if isinstance(media, raw.types.MessageMediaPhoto): photo = types.Photo._parse( - client, media.photo, media.ttl_seconds + client, + media.photo, + media.ttl_seconds, ) media_type = enums.MessageMediaType.PHOTO has_media_spoiler = media.spoiler @@ -1151,7 +1167,8 @@ async def _parse( media_type = enums.MessageMediaType.GIVEAWAY elif isinstance(media, raw.types.MessageMediaGiveawayResults): giveaway_result = await types.GiveawayResult._parse( - client, message.media + client, + message.media, ) media_type = enums.MessageMediaType.GIVEAWAY_RESULT elif isinstance(media, raw.types.MessageMediaStory): @@ -1165,7 +1182,8 @@ async def _parse( file_name = getattr( attributes.get( - raw.types.DocumentAttributeFilename, None + raw.types.DocumentAttributeFilename, + None, ), "file_name", None, @@ -1173,16 +1191,22 @@ async def _parse( if raw.types.DocumentAttributeAnimated in attributes: video_attributes = attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) animation = types.Animation._parse( - client, doc, video_attributes, file_name + client, + doc, + video_attributes, + file_name, ) media_type = enums.MessageMediaType.ANIMATION has_media_spoiler = media.spoiler elif raw.types.DocumentAttributeSticker in attributes: sticker = await types.Sticker._parse( - client, doc, attributes + client, + doc, + attributes, ) media_type = enums.MessageMediaType.STICKER elif raw.types.DocumentAttributeVideo in attributes: @@ -1192,7 +1216,9 @@ async def _parse( if video_attributes.round_message: video_note = types.VideoNote._parse( - client, doc, video_attributes + client, + doc, + video_attributes, ) media_type = enums.MessageMediaType.VIDEO_NOTE else: @@ -1232,7 +1258,7 @@ async def _parse( altdoc, altdoc_video_attribute, altdoc_file_name, - ) + ), ) elif raw.types.DocumentAttributeAudio in attributes: audio_attributes = attributes[ @@ -1241,12 +1267,17 @@ async def _parse( if audio_attributes.voice: voice = types.Voice._parse( - client, doc, audio_attributes + client, + doc, + audio_attributes, ) media_type = enums.MessageMediaType.VOICE else: audio = types.Audio._parse( - client, doc, audio_attributes, file_name + client, + doc, + audio_attributes, + file_name, ) media_type = enums.MessageMediaType.AUDIO else: @@ -1254,10 +1285,13 @@ async def _parse( media_type = enums.MessageMediaType.DOCUMENT elif isinstance(media, raw.types.MessageMediaWebPage): if isinstance( - media.webpage, raw.types.WebPage | raw.types.WebPageEmpty + media.webpage, + raw.types.WebPage | raw.types.WebPageEmpty, ): web_page_preview = types.WebPagePreview._parse( - client, media, message.invert_media + client, + media, + message.invert_media, ) media_type = enums.MessageMediaType.WEB_PAGE_PREVIEW else: @@ -1299,12 +1333,15 @@ async def _parse( ) reactions = types.MessageReactions._parse( - client, message.reactions, users + client, + message.reactions, + users, ) if message.via_business_bot_id: sender_business_bot = types.User._parse( - client, users.get(message.via_business_bot_id) + client, + users.get(message.via_business_bot_id), ) parsed_message = Message( @@ -1380,7 +1417,8 @@ async def _parse( views=message.views, forwards=message.forwards, via_bot=types.User._parse( - client, users.get(message.via_bot_id, None) + client, + users.get(message.via_bot_id, None), ), outgoing=message.out, reply_markup=reply_markup, @@ -1401,7 +1439,7 @@ async def _parse( for entity in message.reply_to.quote_entities ] parsed_message.quote_entities = types.List( - filter(lambda x: x is not None, quote_entities) + filter(lambda x: x is not None, quote_entities), ) if message.reply_to.forum_topic: if message.reply_to.reply_to_top_id: @@ -1415,14 +1453,15 @@ async def _parse( parsed_message.is_topic_message = True if topic: parsed_message.topic = types.ForumTopic._parse( - topic[thread_id] + topic[thread_id], ) else: try: msg = await client.get_messages( - parsed_message.chat.id, message.id + parsed_message.chat.id, + message.id, ) - if getattr(msg, "topic"): + if msg.topic: parsed_message.topic = msg.topic except Exception: pass @@ -1441,11 +1480,11 @@ async def _parse( ) elif isinstance(message.reply_to.peer, raw.types.PeerChat): parsed_message.reply_to_story_chat_id = utils.get_channel_id( - message.reply_to.peer.chat_id + message.reply_to.peer.chat_id, ) else: parsed_message.reply_to_story_chat_id = utils.get_channel_id( - message.reply_to.peer.channel_id + message.reply_to.peer.channel_id, ) rtci = getattr(message.reply_to, "reply_to_peer_id", None) reply_to_chat_id = ( @@ -1485,7 +1524,8 @@ async def _parse( if not reply_to_message: reply_to_message = await client.get_messages( - replies=replies - 1, **reply_to_params + replies=replies - 1, + **reply_to_params, ) if ( reply_to_message @@ -1561,7 +1601,8 @@ async def get_media_group(self) -> list[types.Message]: """ return await self._client.get_media_group( - chat_id=self.chat.id, message_id=self.id + chat_id=self.chat.id, + message_id=self.id, ) async def reply_text( @@ -4767,6 +4808,7 @@ async def copy( quote_text: str | None = None, quote_entities: list[types.MessageEntity] | None = None, reply_to_message_id: int | None = None, + reply_to_chat_id: int | None = None, schedule_date: datetime | None = None, protect_content: bool | None = None, allow_paid_broadcast: bool | None = None, @@ -4834,6 +4876,11 @@ async def copy( reply_to_message_id (``int``, *optional*): If the message is a reply, ID of the original message. + reply_to_chat_id (``int``, *optional*): + Unique identifier for the origin chat. + for reply to message from another chat. + You can also use chat public link in form of *t.me/* (str). + schedule_date (:py:obj:`~datetime.datetime`, *optional*): Date when the message will be automatically sent. @@ -4885,6 +4932,7 @@ async def copy( disable_notification=disable_notification, message_thread_id=message_thread_id, reply_to_message_id=reply_to_message_id, + reply_to_chat_id=reply_to_chat_id, quote_text=quote_text, quote_entities=quote_entities, schedule_date=schedule_date, @@ -4901,6 +4949,7 @@ async def copy( disable_notification=disable_notification, message_thread_id=message_thread_id, reply_to_message_id=reply_to_message_id, + reply_to_chat_id=reply_to_chat_id, schedule_date=schedule_date, has_spoiler=has_spoiler, protect_content=protect_content, @@ -4996,6 +5045,7 @@ async def copy( disable_notification=disable_notification, message_thread_id=message_thread_id, reply_to_message_id=reply_to_message_id, + reply_to_chat_id=reply_to_chat_id, quote_text=quote_text, quote_entities=quote_entities, schedule_date=schedule_date, @@ -5060,7 +5110,9 @@ async def delete(self, revoke: bool = True): RPCError: In case of a Telegram RPC error. """ return await self._client.delete_messages( - chat_id=self.chat.id, message_ids=self.id, revoke=revoke + chat_id=self.chat.id, + message_ids=self.id, + revoke=revoke, ) async def click( @@ -5159,12 +5211,14 @@ async def click( try: button = [button for row in keyboard for button in row][x] except IndexError: - raise ValueError(f"The button at index {x} doesn't exist") + raise ValueError(f"The button at index {x} doesn't exist") from None elif isinstance(x, int) and isinstance(y, int): try: button = keyboard[y][x] except IndexError: - raise ValueError(f"The button at position ({x}, {y}) doesn't exist") + raise ValueError( + f"The button at position ({x}, {y}) doesn't exist", + ) from None elif isinstance(x, str) and y is None: label = x.encode("utf-16", "surrogatepass").decode("utf-16") @@ -5176,7 +5230,9 @@ async def click( if label == button.text ) except IndexError: - raise ValueError(f"The button with label '{x}' doesn't exists") + raise ValueError( + f"The button with label '{x}' doesn't exists", + ) from None else: raise ValueError("Invalid arguments") @@ -5224,7 +5280,7 @@ async def click( url=web_app.url, platform=self._client.client_platform.value, # TODO - ) + ), ) return r.url if button.user_id: @@ -5238,7 +5294,10 @@ async def click( return None async def react( - self, emoji: str = "", big: bool = False, add_to_recent: bool = True + self, + emoji: str = "", + big: bool = False, + add_to_recent: bool = True, ) -> types.MessageReactions: """Bound method *react* of :obj:`~pyrogram.types.Message`. @@ -5312,7 +5371,8 @@ async def retract_vote( """ return await self._client.retract_vote( - chat_id=self.chat.id, message_id=self.id + chat_id=self.chat.id, + message_id=self.id, ) async def download( @@ -5322,7 +5382,7 @@ async def download( block: bool = True, progress: Callable | None = None, progress_args: tuple = (), - ) -> str: + ) -> str | BinaryIO: """Bound method *download* of :obj:`~pyrogram.types.Message`. Use as a shortcut for: @@ -5423,11 +5483,15 @@ async def vote( """ return await self._client.vote_poll( - chat_id=self.chat.id, message_id=self.id, options=option + chat_id=self.chat.id, + message_id=self.id, + options=option, ) async def pin( - self, disable_notification: bool = False, both_sides: bool = False + self, + disable_notification: bool = False, + both_sides: bool = False, ) -> types.Message: """Bound method *pin* of :obj:`~pyrogram.types.Message`. @@ -5491,7 +5555,8 @@ async def unpin(self) -> bool: RPCError: In case of a Telegram RPC error. """ return await self._client.unpin_chat_message( - chat_id=self.chat.id, message_id=self.id + chat_id=self.chat.id, + message_id=self.id, ) async def ask( @@ -5587,7 +5652,9 @@ async def ask( ) reply_message = await self._client.wait_for_message( - self.chat.id, filters=filters, timeout=timeout + self.chat.id, + filters=filters, + timeout=timeout, ) reply_message.request = request @@ -5613,7 +5680,8 @@ async def pay(self) -> bool: True on success. """ return await self._client.send_payment_form( - chat_id=self.chat.id, message_id=self.id + chat_id=self.chat.id, + message_id=self.id, ) async def translate(self, to_language_code: str) -> types.TranslatedText: diff --git a/pyrogram/types/messages_and_media/message_entity.py b/pyrogram/types/messages_and_media/message_entity.py index e0b4218a..16c84510 100644 --- a/pyrogram/types/messages_and_media/message_entity.py +++ b/pyrogram/types/messages_and_media/message_entity.py @@ -63,7 +63,9 @@ def __init__( @staticmethod def _parse( - client, entity: raw.base.MessageEntity, users: dict + client, + entity: raw.base.MessageEntity, + users: dict, ) -> MessageEntity | None: # Special case for InputMessageEntityMentionName -> MessageEntityType.TEXT_MENTION # This happens in case of UpdateShortSentMessage inside send_message() where entities are parsed from the input diff --git a/pyrogram/types/messages_and_media/message_reaction_updated.py b/pyrogram/types/messages_and_media/message_reaction_updated.py index 77201dd5..9b00f68b 100644 --- a/pyrogram/types/messages_and_media/message_reaction_updated.py +++ b/pyrogram/types/messages_and_media/message_reaction_updated.py @@ -89,7 +89,8 @@ def _parse( from_user = types.User._parse(client, users[raw_actor_peer_id]) else: actor_chat = types.Chat._parse_channel_chat( - client, chats[raw_actor_peer_id] + client, + chats[raw_actor_peer_id], ) return MessageReactionUpdated( diff --git a/pyrogram/types/messages_and_media/message_reactor.py b/pyrogram/types/messages_and_media/message_reactor.py index 0c77eda3..41c32450 100644 --- a/pyrogram/types/messages_and_media/message_reactor.py +++ b/pyrogram/types/messages_and_media/message_reactor.py @@ -55,7 +55,8 @@ def _parse( from_user = None if not is_anonymous: from_user = types.User._parse( - client, users.get(message_reactor.peer_id.user_id) + client, + users.get(message_reactor.peer_id.user_id), ) return MessageReactor( diff --git a/pyrogram/types/messages_and_media/message_story.py b/pyrogram/types/messages_and_media/message_story.py index 5c75e390..eefb0c4f 100644 --- a/pyrogram/types/messages_and_media/message_story.py +++ b/pyrogram/types/messages_and_media/message_story.py @@ -45,8 +45,8 @@ async def _parse( chat_id = utils.get_channel_id(message_story.peer.channel_id) chat = await client.invoke( raw.functions.channels.GetChannels( - id=[await client.resolve_peer(chat_id)] - ) + id=[await client.resolve_peer(chat_id)], + ), ) sender_chat = types.Chat._parse_chat(client, chat.chats[0]) else: diff --git a/pyrogram/types/messages_and_media/payment_form.py b/pyrogram/types/messages_and_media/payment_form.py index 39614e79..4fcb6f76 100644 --- a/pyrogram/types/messages_and_media/payment_form.py +++ b/pyrogram/types/messages_and_media/payment_form.py @@ -91,7 +91,8 @@ def _parse(client, payment_form: raw.base.payments.PaymentForm) -> PaymentForm: description=payment_form.description, invoice=types.Invoice._parse(client, payment_form.invoice), provider=types.User._parse( - client, users.get(getattr(payment_form, "provider_id", None)) + client, + users.get(getattr(payment_form, "provider_id", None)), ), url=getattr(payment_form, "url", None), can_save_credentials=getattr(payment_form, "can_save_credentials", None), diff --git a/pyrogram/types/messages_and_media/photo.py b/pyrogram/types/messages_and_media/photo.py index 74cb09b1..e7944381 100644 --- a/pyrogram/types/messages_and_media/photo.py +++ b/pyrogram/types/messages_and_media/photo.py @@ -91,7 +91,7 @@ def _parse( w=p.w, h=p.h, size=max(p.sizes), - ) + ), ) photos.sort(key=lambda p: p.size) diff --git a/pyrogram/types/messages_and_media/poll.py b/pyrogram/types/messages_and_media/poll.py index 63bfef68..6b285806 100644 --- a/pyrogram/types/messages_and_media/poll.py +++ b/pyrogram/types/messages_and_media/poll.py @@ -151,7 +151,7 @@ async def _parse( data=answer.option, entities=option_entities, client=client, - ) + ), ) q_entities = ( @@ -221,7 +221,7 @@ async def _parse_update( voter_count=result.voters, data=result.option, client=client, - ) + ), ) return Poll( diff --git a/pyrogram/types/messages_and_media/poll_option.py b/pyrogram/types/messages_and_media/poll_option.py index 03c45ed2..66befec5 100644 --- a/pyrogram/types/messages_and_media/poll_option.py +++ b/pyrogram/types/messages_and_media/poll_option.py @@ -41,12 +41,16 @@ def __init__( async def write(self, client, i): option, entities = ( await pyrogram.utils.parse_text_entities( - client, self.text, None, self.entities + client, + self.text, + None, + self.entities, ) ).values() return pyrogram.raw.types.PollAnswer( text=pyrogram.raw.types.TextWithEntities( - text=option, entities=entities or [] + text=option, + entities=entities or [], ), option=bytes([i]), ) diff --git a/pyrogram/types/messages_and_media/reaction.py b/pyrogram/types/messages_and_media/reaction.py index 72c696ba..eb053803 100644 --- a/pyrogram/types/messages_and_media/reaction.py +++ b/pyrogram/types/messages_and_media/reaction.py @@ -49,7 +49,8 @@ def __init__( def _parse(client: pyrogram.Client, reaction: raw.base.Reaction) -> Reaction: if isinstance(reaction, raw.types.ReactionEmoji): return Reaction( - client=client, type=ReactionTypeEmoji(emoji=reaction.emoticon) + client=client, + type=ReactionTypeEmoji(emoji=reaction.emoticon), ) if isinstance(reaction, raw.types.ReactionCustomEmoji): @@ -64,7 +65,8 @@ def _parse(client: pyrogram.Client, reaction: raw.base.Reaction) -> Reaction: @staticmethod def _parse_count( - client: pyrogram.Client, reaction_count: raw.base.ReactionCount + client: pyrogram.Client, + reaction_count: raw.base.ReactionCount, ) -> Reaction: reaction = Reaction._parse(client, reaction_count.reaction) reaction.count = reaction_count.count @@ -178,7 +180,11 @@ class ReactionCount(Object): """ def __init__( - self, *, type: ReactionType, total_count: int, chosen_order: int + self, + *, + type: ReactionType, + total_count: int, + chosen_order: int, ) -> None: super().__init__() self.type = type diff --git a/pyrogram/types/messages_and_media/sticker.py b/pyrogram/types/messages_and_media/sticker.py index 3455110b..daef374b 100644 --- a/pyrogram/types/messages_and_media/sticker.py +++ b/pyrogram/types/messages_and_media/sticker.py @@ -125,17 +125,18 @@ async def _get_sticker_set_name(invoke, input_sticker_set_id): await invoke( raw.functions.messages.GetStickerSet( stickerset=raw.types.InputStickerSetID( - id=set_id, access_hash=set_access_hash + id=set_id, + access_hash=set_access_hash, ), hash=0, - ) + ), ) ).set.short_name Sticker.cache[(set_id, set_access_hash)] = name if len(Sticker.cache) > 250: - for i in range(50): + for _i in range(50): Sticker.cache.pop(next(iter(Sticker.cache))) return name @@ -158,7 +159,8 @@ async def _parse( ) image_size_attributes = document_attributes.get( - raw.types.DocumentAttributeImageSize, None + raw.types.DocumentAttributeImageSize, + None, ) file_name = getattr( document_attributes.get(raw.types.DocumentAttributeFilename, None), @@ -166,7 +168,8 @@ async def _parse( None, ) video_attributes = document_attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) sticker_set = sticker_attributes.stickerset @@ -177,7 +180,8 @@ async def _parse( sticker_set.access_hash, ) set_name = await Sticker._get_sticker_set_name( - client.invoke, input_sticker_set_id + client.invoke, + input_sticker_set_id, ) else: set_name = None diff --git a/pyrogram/types/messages_and_media/story.py b/pyrogram/types/messages_and_media/story.py index 6d0cb966..95b6753d 100644 --- a/pyrogram/types/messages_and_media/story.py +++ b/pyrogram/types/messages_and_media/story.py @@ -202,15 +202,20 @@ async def _parse( if raw.types.DocumentAttributeAnimated in attributes: video_attributes = attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) animation = types.Animation._parse( - client, doc, video_attributes, None + client, + doc, + video_attributes, + None, ) media_type = enums.MessageMediaType.ANIMATION elif raw.types.DocumentAttributeVideo in attributes: video_attributes = attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) video = types.Video._parse( client, @@ -228,8 +233,8 @@ async def _parse( chat_id = utils.get_channel_id(peer.channel_id) chat = await client.invoke( raw.functions.channels.GetChannels( - id=[await client.resolve_peer(chat_id)] - ) + id=[await client.resolve_peer(chat_id)], + ), ) sender_chat = types.Chat._parse_chat(client, chat.chats[0]) elif isinstance(peer, raw.types.InputPeerSelf): @@ -240,16 +245,16 @@ async def _parse( from_id = getattr(stories, "from_id", None) if from_id is not None: if getattr(from_id, "user_id", None) is not None: - from_user = await client.get_users(getattr(from_id, "user_id")) + from_user = await client.get_users(from_id.user_id) elif getattr(from_id, "channel_id", None) is not None: chat = await client.invoke( raw.functions.channels.GetChannels( id=[ await client.resolve_peer( - utils.get_channel_id(getattr(from_id, "channel_id")) - ) - ] - ) + utils.get_channel_id(from_id.channel_id), + ), + ], + ), ) sender_chat = types.Chat._parse_chat(client, chat.chats[0]) elif getattr(from_id, "chat_id", None) is not None: @@ -257,10 +262,10 @@ async def _parse( raw.functions.channels.GetChannels( id=[ await client.resolve_peer( - utils.get_channel_id(getattr(from_id, "chat_id")) - ) - ] - ) + utils.get_channel_id(from_id.chat_id), + ), + ], + ), ) sender_chat = types.Chat._parse_chat(client, chat.chats[0]) @@ -291,7 +296,8 @@ async def _parse( if stories.fwd_from is not None: forward_from = await types.StoryForwardHeader._parse( - client, stories.fwd_from + client, + stories.fwd_from, ) media_areas = None @@ -331,7 +337,9 @@ async def _parse( ) async def react( - self, reaction: int | str | None = None, add_to_recent: bool = True + self, + reaction: int | str | None = None, + add_to_recent: bool = True, ) -> types.MessageReactions: """Bound method *react* of :obj:`~pyrogram.types.Story`. diff --git a/pyrogram/types/messages_and_media/story_forward_header.py b/pyrogram/types/messages_and_media/story_forward_header.py index ab2b61b6..9897e670 100644 --- a/pyrogram/types/messages_and_media/story_forward_header.py +++ b/pyrogram/types/messages_and_media/story_forward_header.py @@ -52,7 +52,7 @@ async def _parse( if fwd_header.from_peer is not None: if isinstance(fwd_header.from_peer, raw.types.PeerChannel): chat = await self.get_chat( - utils.get_channel_id(fwd_header.from_peer.channel_id) + utils.get_channel_id(fwd_header.from_peer.channel_id), ) elif isinstance(fwd_header.from_peer, raw.types.InputPeerSelf): user = self.me diff --git a/pyrogram/types/messages_and_media/stripped_thumbnail.py b/pyrogram/types/messages_and_media/stripped_thumbnail.py index c3700538..4731fbc3 100644 --- a/pyrogram/types/messages_and_media/stripped_thumbnail.py +++ b/pyrogram/types/messages_and_media/stripped_thumbnail.py @@ -24,6 +24,7 @@ def __init__(self, *, client: pyrogram.Client = None, data: bytes) -> None: @staticmethod def _parse( - client, stripped_thumbnail: raw.types.PhotoStrippedSize + client, + stripped_thumbnail: raw.types.PhotoStrippedSize, ) -> StrippedThumbnail: return StrippedThumbnail(data=stripped_thumbnail.bytes, client=client) diff --git a/pyrogram/types/messages_and_media/thumbnail.py b/pyrogram/types/messages_and_media/thumbnail.py index aa330cfb..6fc9662f 100644 --- a/pyrogram/types/messages_and_media/thumbnail.py +++ b/pyrogram/types/messages_and_media/thumbnail.py @@ -53,7 +53,8 @@ def __init__( @staticmethod def _parse( - client, media: raw.types.Photo | raw.types.Document + client, + media: raw.types.Photo | raw.types.Document, ) -> list[Thumbnail] | None: if isinstance(media, raw.types.Photo): raw_thumbs = [ @@ -97,7 +98,7 @@ def _parse( height=thumb.h, file_size=thumb.size, client=client, - ) + ), ) return parsed_thumbs or None diff --git a/pyrogram/types/messages_and_media/translated_text.py b/pyrogram/types/messages_and_media/translated_text.py index 6c1bdb45..df51eced 100644 --- a/pyrogram/types/messages_and_media/translated_text.py +++ b/pyrogram/types/messages_and_media/translated_text.py @@ -18,14 +18,18 @@ class TranslatedText(Object): """ def __init__( - self, *, text: str, entities: list[types.MessageEntity] | None = None + self, + *, + text: str, + entities: list[types.MessageEntity] | None = None, ) -> None: self.text = text self.entities = entities @staticmethod def _parse( - client, translate_result: raw.types.TextWithEntities + client, + translate_result: raw.types.TextWithEntities, ) -> TranslatedText: entities = [ types.MessageEntity._parse(client, entity, {}) diff --git a/pyrogram/types/messages_and_media/web_page.py b/pyrogram/types/messages_and_media/web_page.py index 80814a22..22e90e8b 100644 --- a/pyrogram/types/messages_and_media/web_page.py +++ b/pyrogram/types/messages_and_media/web_page.py @@ -139,10 +139,14 @@ def _parse(client, webpage: raw.types.WebPage) -> WebPage: elif raw.types.DocumentAttributeAnimated in attributes: video_attributes = attributes.get( - raw.types.DocumentAttributeVideo, None + raw.types.DocumentAttributeVideo, + None, ) animation = types.Animation._parse( - client, doc, video_attributes, file_name + client, + doc, + video_attributes, + file_name, ) elif raw.types.DocumentAttributeVideo in attributes: diff --git a/pyrogram/types/payments/gift.py b/pyrogram/types/payments/gift.py index a9c1a33b..6071b909 100644 --- a/pyrogram/types/payments/gift.py +++ b/pyrogram/types/payments/gift.py @@ -60,7 +60,7 @@ def __init__( last_send_date: datetime | None = None, is_limited: bool | None = None, is_sold_out: bool | None = None, - ): + ) -> None: super().__init__(client) self.id = id @@ -90,10 +90,10 @@ async def _parse( remaining_count=getattr(star_gift, "availability_remains", None), total_count=getattr(star_gift, "availability_total", None), first_send_date=utils.timestamp_to_datetime( - getattr(star_gift, "first_sale_date", None) + getattr(star_gift, "first_sale_date", None), ), last_send_date=utils.timestamp_to_datetime( - getattr(star_gift, "last_sale_date", None) + getattr(star_gift, "last_sale_date", None), ), is_limited=getattr(star_gift, "limited", None), is_sold_out=getattr(star_gift, "sold_out", None), diff --git a/pyrogram/types/payments/user_gift.py b/pyrogram/types/payments/user_gift.py index cedffe4f..fea2fb30 100644 --- a/pyrogram/types/payments/user_gift.py +++ b/pyrogram/types/payments/user_gift.py @@ -57,7 +57,7 @@ def __init__( gift: types.Gift | None = None, message_id: int | None = None, sell_star_count: int | None = None, - ): + ) -> None: super().__init__(client) self.date = date @@ -72,7 +72,9 @@ def __init__( @staticmethod async def _parse( - client, user_star_gift: raw.types.UserStarGift, users: dict + client, + user_star_gift: raw.types.UserStarGift, + users: dict, ) -> UserGift: text, entities = None, None if getattr(user_star_gift, "message", None): @@ -102,7 +104,9 @@ async def _parse( @staticmethod async def _parse_action( - client, message: raw.base.Message, users: dict + client, + message: raw.base.Message, + users: dict, ) -> UserGift: action = message.action @@ -132,7 +136,8 @@ async def _parse_action( is_private=getattr(action, "name_hidden", None), is_saved=getattr(action, "saved", None), sender_user=types.User._parse( - client, users.get(utils.get_raw_peer_id(message.peer_id)) + client, + users.get(utils.get_raw_peer_id(message.peer_id)), ), message_id=message.id, text=Str(text).init(entities) if text else None, diff --git a/pyrogram/types/user_and_chats/__init__.py b/pyrogram/types/user_and_chats/__init__.py index 74e1d02c..5e891d8b 100644 --- a/pyrogram/types/user_and_chats/__init__.py +++ b/pyrogram/types/user_and_chats/__init__.py @@ -53,41 +53,41 @@ "BusinessWeeklyOpen", "BusinessWorkingHours", "Chat", + "ChatAdminWithInviteLinks", + "ChatColor", + "ChatEvent", + "ChatEventFilter", + "ChatInviteLink", + "ChatJoinRequest", + "ChatJoinedByRequest", + "ChatJoiner", "ChatMember", + "ChatMemberUpdated", "ChatPermissions", "ChatPhoto", "ChatPreview", + "ChatPrivileges", + "ChatReactions", "Dialog", + "EmojiStatus", "Folder", - "FoundContacts", - "User", - "Username", - "Restriction", - "ChatEvent", - "ChatEventFilter", - "ChatInviteLink", - "InviteLinkImporter", - "ChatAdminWithInviteLinks", - "ChatColor", "ForumTopic", - "ForumTopicCreated", "ForumTopicClosed", - "ForumTopicReopened", + "ForumTopicCreated", "ForumTopicEdited", + "ForumTopicReopened", + "FoundContacts", "GeneralTopicHidden", "GeneralTopicUnhidden", + "InviteLinkImporter", "PeerChannel", "PeerUser", "PrivacyRule", - "VideoChatStarted", + "Restriction", + "User", + "Username", "VideoChatEnded", "VideoChatMembersInvited", - "ChatMemberUpdated", "VideoChatScheduled", - "ChatJoinRequest", - "ChatJoinedByRequest", - "ChatPrivileges", - "ChatJoiner", - "EmojiStatus", - "ChatReactions", + "VideoChatStarted", ] diff --git a/pyrogram/types/user_and_chats/business_info.py b/pyrogram/types/user_and_chats/business_info.py index 92b90451..956a3bd5 100644 --- a/pyrogram/types/user_and_chats/business_info.py +++ b/pyrogram/types/user_and_chats/business_info.py @@ -56,10 +56,13 @@ def _parse( return BusinessInfo( address=getattr(location, "address", None), location=types.Location._parse( - client, getattr(location, "geo_point", None) + client, + getattr(location, "geo_point", None), ), greeting_message=types.BusinessMessage._parse( - client, greeting_message, users + client, + greeting_message, + users, ), away_message=types.BusinessMessage._parse(client, away_message, users), working_hours=types.BusinessWorkingHours._parse(working_hours), diff --git a/pyrogram/types/user_and_chats/business_message.py b/pyrogram/types/user_and_chats/business_message.py index d7b77750..eba8193b 100644 --- a/pyrogram/types/user_and_chats/business_message.py +++ b/pyrogram/types/user_and_chats/business_message.py @@ -100,7 +100,9 @@ def _parse( no_activity_days=getattr(message, "no_activity_days", None), offline_only=getattr(message, "offline_only", None), recipients=types.BusinessRecipients._parse( - client, message.recipients, users + client, + message.recipients, + users, ), schedule=schedule, start_date=utils.timestamp_to_datetime(message.schedule.start_date) diff --git a/pyrogram/types/user_and_chats/chat.py b/pyrogram/types/user_and_chats/chat.py index 7a8a6caf..1d6e7072 100644 --- a/pyrogram/types/user_and_chats/chat.py +++ b/pyrogram/types/user_and_chats/chat.py @@ -323,16 +323,19 @@ def _parse_user_chat(client, user: raw.types.User) -> Chat: first_name=user.first_name, last_name=user.last_name, photo=types.ChatPhoto._parse( - client, user.photo, peer_id, user.access_hash + client, + user.photo, + peer_id, + user.access_hash, ), restrictions=types.List( - [types.Restriction._parse(r) for r in user.restriction_reason] + [types.Restriction._parse(r) for r in user.restriction_reason], ) or None, dc_id=getattr(getattr(user, "photo", None), "dc_id", None), reply_color=types.ChatColor._parse(getattr(user, "color", None)), profile_color=types.ChatColor._parse_profile_color( - getattr(user, "profile_color", None) + getattr(user, "profile_color", None), ), client=client, ) @@ -353,10 +356,13 @@ def _parse_chat_chat(client, chat: raw.types.Chat) -> Chat: title=chat.title, is_creator=getattr(chat, "creator", None), photo=types.ChatPhoto._parse( - client, getattr(chat, "photo", None), peer_id, 0 + client, + getattr(chat, "photo", None), + peer_id, + 0, ), permissions=types.ChatPermissions._parse( - getattr(chat, "default_banned_rights", None) + getattr(chat, "default_banned_rights", None), ), members_count=getattr(chat, "participants_count", None), join_requests_count=getattr(chat, "requests_pending", None), @@ -408,17 +414,17 @@ def _parse_channel_chat(client, channel: raw.types.Channel) -> Chat: getattr(channel, "access_hash", 0), ), restrictions=types.List( - [types.Restriction._parse(r) for r in restriction_reason] + [types.Restriction._parse(r) for r in restriction_reason], ) or None, permissions=types.ChatPermissions._parse( - getattr(channel, "default_banned_rights", None) + getattr(channel, "default_banned_rights", None), ), members_count=getattr(channel, "participants_count", None), dc_id=getattr(getattr(channel, "photo", None), "dc_id", None), has_protected_content=getattr(channel, "noforwards", None), subscription_until_date=utils.timestamp_to_datetime( - getattr(channel, "subscription_until_date", None) + getattr(channel, "subscription_until_date", None), ), reply_color=types.ChatColor._parse(getattr(channel, "color", None)), client=client, @@ -467,7 +473,9 @@ async def _parse_full( parsed_chat.bio = full_user.about parsed_chat.folder_id = getattr(full_user, "folder_id", None) parsed_chat.business_info = types.BusinessInfo._parse( - client, full_user, users + client, + full_user, + users, ) birthday = getattr(full_user, "birthday", None) parsed_chat.birthday = ( @@ -479,13 +487,14 @@ async def _parse_full( raw.functions.channels.GetChannels( id=[ await client.resolve_peer( - utils.get_channel_id(personal_chat_id) - ) - ] - ) + utils.get_channel_id(personal_chat_id), + ), + ], + ), ) parsed_chat.personal_chat = Chat._parse_chat( - client, personal_chat.chats[0] + client, + personal_chat.chats[0], ) if full_user.pinned_msg_id: @@ -494,22 +503,25 @@ async def _parse_full( message_ids=full_user.pinned_msg_id, ) - if getattr(full_user, "stories"): + if full_user.stories: peer_stories: raw.types.PeerStories = full_user.stories parsed_chat.stories = ( types.List( [ await types.Story._parse( - client, story, peer_stories.peer + client, + story, + peer_stories.peer, ) for story in peer_stories.stories - ] + ], ) or None ) - if getattr(full_user, "wallpaper") and isinstance( - full_user.wallpaper, raw.types.WallPaper + if full_user.wallpaper and isinstance( + full_user.wallpaper, + raw.types.WallPaper, ): parsed_chat.wallpaper = types.Document._parse( client, @@ -526,21 +538,27 @@ async def _parse_full( if isinstance(full_chat.participants, raw.types.ChatParticipants): parsed_chat.members_count = len( - full_chat.participants.participants + full_chat.participants.participants, ) else: parsed_chat = Chat._parse_channel_chat(client, chat_raw) parsed_chat.members_count = full_chat.participants_count parsed_chat.slow_mode_delay = getattr( - full_chat, "slowmode_seconds", None + full_chat, + "slowmode_seconds", + None, ) parsed_chat.is_paid_reactions_available = getattr( - full_chat, "paid_reactions_available", None + full_chat, + "paid_reactions_available", + None, ) parsed_chat.description = full_chat.about or None parsed_chat.can_set_sticker_set = full_chat.can_set_stickers parsed_chat.sticker_set_name = getattr( - full_chat.stickerset, "short_name", None + full_chat.stickerset, + "short_name", + None, ) parsed_chat.is_participants_hidden = full_chat.participants_hidden parsed_chat.is_antispam = full_chat.antispam @@ -553,7 +571,8 @@ async def _parse_full( if linked_chat_raw: parsed_chat.linked_chat = Chat._parse_channel_chat( - client, linked_chat_raw + client, + linked_chat_raw, ) default_send_as = full_chat.default_send_as @@ -566,22 +585,25 @@ async def _parse_full( parsed_chat.send_as_chat = Chat._parse_chat(client, send_as_raw) - if getattr(full_chat, "stories"): + if full_chat.stories: peer_stories: raw.types.PeerStories = full_chat.stories parsed_chat.stories = ( types.List( [ await types.Story._parse( - client, story, peer_stories.peer + client, + story, + peer_stories.peer, ) for story in peer_stories.stories - ] + ], ) or None ) - if getattr(full_chat, "wallpaper") and isinstance( - full_chat.wallpaper, raw.types.WallPaper + if full_chat.wallpaper and isinstance( + full_chat.wallpaper, + raw.types.WallPaper, ): parsed_chat.wallpaper = types.Document._parse( client, @@ -602,13 +624,18 @@ async def _parse_full( parsed_chat.invite_link = full_chat.exported_invite.link parsed_chat.available_reactions = types.ChatReactions._parse( - client, full_chat.available_reactions + client, + full_chat.available_reactions, ) parsed_chat.join_requests_count = getattr( - full_chat, "requests_pending", None + full_chat, + "requests_pending", + None, ) parsed_chat.max_reaction_count = getattr( - full_chat, "reactions_limit", 11 + full_chat, + "reactions_limit", + 11, ) return parsed_chat @@ -822,7 +849,8 @@ async def set_description(self, description: str) -> bool: """ return await self._client.set_chat_description( - chat_id=self.id, description=description + chat_id=self.id, + description=description, ) async def set_photo( @@ -891,7 +919,7 @@ async def set_photo( async def ban_member( self, user_id: int | str, - until_date: datetime = utils.zero_datetime(), + until_date: datetime | None = None, revoke_messages: bool | None = None, ) -> types.Message | bool: """Bound method *ban_member* of :obj:`~pyrogram.types.Chat`. @@ -937,6 +965,8 @@ async def ban_member( RPCError: In case of a Telegram RPC error. """ + if until_date is None: + until_date = utils.zero_datetime() return await self._client.ban_chat_member( chat_id=self.id, user_id=user_id, @@ -982,7 +1012,7 @@ async def restrict_member( self, user_id: int | str, permissions: types.ChatPermissions, - until_date: datetime = utils.zero_datetime(), + until_date: datetime | None = None, ) -> types.Chat: """Bound method *unban_member* of :obj:`~pyrogram.types.Chat`. @@ -1021,6 +1051,8 @@ async def restrict_member( RPCError: In case of a Telegram RPC error. """ + if until_date is None: + until_date = utils.zero_datetime() return await self._client.restrict_chat_member( chat_id=self.id, user_id=user_id, @@ -1231,7 +1263,10 @@ def get_members( """ return self._client.get_chat_members( - self.id, query=query, limit=limit, filter=filter + self.id, + query=query, + limit=limit, + filter=filter, ) async def add_members( @@ -1257,7 +1292,9 @@ async def add_members( """ return await self._client.add_chat_members( - self.id, user_ids=user_ids, forward_limit=forward_limit + self.id, + user_ids=user_ids, + forward_limit=forward_limit, ) async def mark_unread( @@ -1305,7 +1342,8 @@ async def set_protected_content(self, enabled: bool) -> bool: """ return await self._client.set_chat_protected_content( - self.id, enabled=enabled + self.id, + enabled=enabled, ) async def unpin_all_messages(self) -> bool: diff --git a/pyrogram/types/user_and_chats/chat_event.py b/pyrogram/types/user_and_chats/chat_event.py index e1a71f90..d79d66da 100644 --- a/pyrogram/types/user_and_chats/chat_event.py +++ b/pyrogram/types/user_and_chats/chat_event.py @@ -222,7 +222,7 @@ def __init__( old_forum_topic: types.ForumTopic = None, new_forum_topic: types.ForumTopic = None, deleted_forum_topic: types.ForumTopic = None, - ): + ) -> None: super().__init__() self.id = id @@ -391,17 +391,20 @@ async def _parse( action = enums.ChatEventAction.DESCRIPTION_CHANGED elif isinstance( - action, raw.types.ChannelAdminLogEventActionChangeHistoryTTL + action, + raw.types.ChannelAdminLogEventActionChangeHistoryTTL, ): old_history_ttl = action.prev_value new_history_ttl = action.new_value action = enums.ChatEventAction.HISTORY_TTL_CHANGED elif isinstance( - action, raw.types.ChannelAdminLogEventActionChangeLinkedChat + action, + raw.types.ChannelAdminLogEventActionChangeLinkedChat, ): old_linked_chat = types.Chat._parse_chat( - client, chats[action.prev_value] + client, + chats[action.prev_value], ) new_linked_chat = types.Chat._parse_chat(client, chats[action.new_value]) action = enums.ChatEventAction.LINKED_CHAT_CHANGED @@ -423,72 +426,103 @@ async def _parse( elif isinstance(action, raw.types.ChannelAdminLogEventActionChangeUsernames): old_usernames = types.List( - [types.Username(username=p) for p in action.prev_value] + [types.Username(username=p) for p in action.prev_value], ) new_usernames = types.List( - [types.Username(username=n) for n in action.new_value] + [types.Username(username=n) for n in action.new_value], ) action = enums.ChatEventAction.USERNAMES_CHANGED elif isinstance( - action, raw.types.ChannelAdminLogEventActionDefaultBannedRights + action, + raw.types.ChannelAdminLogEventActionDefaultBannedRights, ): old_chat_permissions = types.ChatPermissions._parse( - action.prev_banned_rights + action.prev_banned_rights, ) new_chat_permissions = types.ChatPermissions._parse( - action.new_banned_rights + action.new_banned_rights, ) action = enums.ChatEventAction.CHAT_PERMISSIONS_CHANGED elif isinstance(action, raw.types.ChannelAdminLogEventActionDeleteMessage): deleted_message = await types.Message._parse( - client, action.message, users, chats + client, + action.message, + users, + chats, ) action = enums.ChatEventAction.MESSAGE_DELETED elif isinstance(action, raw.types.ChannelAdminLogEventActionEditMessage): old_message = await types.Message._parse( - client, action.prev_message, users, chats + client, + action.prev_message, + users, + chats, ) new_message = await types.Message._parse( - client, action.new_message, users, chats + client, + action.new_message, + users, + chats, ) action = enums.ChatEventAction.MESSAGE_EDITED elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantInvite + action, + raw.types.ChannelAdminLogEventActionParticipantInvite, ): invited_member = types.ChatMember._parse( - client, action.participant, users, chats + client, + action.participant, + users, + chats, ) action = enums.ChatEventAction.MEMBER_INVITED elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantToggleAdmin + action, + raw.types.ChannelAdminLogEventActionParticipantToggleAdmin, ): old_administrator_privileges = types.ChatMember._parse( - client, action.prev_participant, users, chats + client, + action.prev_participant, + users, + chats, ) new_administrator_privileges = types.ChatMember._parse( - client, action.new_participant, users, chats + client, + action.new_participant, + users, + chats, ) action = enums.ChatEventAction.ADMINISTRATOR_PRIVILEGES_CHANGED elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantToggleBan + action, + raw.types.ChannelAdminLogEventActionParticipantToggleBan, ): old_member_permissions = types.ChatMember._parse( - client, action.prev_participant, users, chats + client, + action.prev_participant, + users, + chats, ) new_member_permissions = types.ChatMember._parse( - client, action.new_participant, users, chats + client, + action.new_participant, + users, + chats, ) action = enums.ChatEventAction.MEMBER_PERMISSIONS_CHANGED elif isinstance(action, raw.types.ChannelAdminLogEventActionStopPoll): stopped_poll = await types.Message._parse( - client, action.message, users, chats + client, + action.message, + users, + chats, ) action = enums.ChatEventAction.POLL_STOPPED @@ -496,7 +530,8 @@ async def _parse( action = enums.ChatEventAction.MEMBER_JOINED elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantLeave + action, + raw.types.ChannelAdminLogEventActionParticipantLeave, ): action = enums.ChatEventAction.MEMBER_LEFT @@ -505,13 +540,15 @@ async def _parse( action = enums.ChatEventAction.INVITES_ENABLED elif isinstance( - action, raw.types.ChannelAdminLogEventActionTogglePreHistoryHidden + action, + raw.types.ChannelAdminLogEventActionTogglePreHistoryHidden, ): history_hidden = action.new_value action = enums.ChatEventAction.HISTORY_HIDDEN elif isinstance( - action, raw.types.ChannelAdminLogEventActionToggleSignatures + action, + raw.types.ChannelAdminLogEventActionToggleSignatures, ): signatures_enabled = action.new_value action = enums.ChatEventAction.SIGNATURES_ENABLED @@ -527,69 +564,96 @@ async def _parse( if isinstance(action.message, raw.types.Message): if message.pinned: pinned_message = await types.Message._parse( - client, message, users, chats + client, + message, + users, + chats, ) action = enums.ChatEventAction.MESSAGE_PINNED else: unpinned_message = await types.Message._parse( - client, message, users, chats + client, + message, + users, + chats, ) action = enums.ChatEventAction.MESSAGE_UNPINNED elif isinstance( - action, raw.types.ChannelAdminLogEventActionExportedInviteEdit + action, + raw.types.ChannelAdminLogEventActionExportedInviteEdit, ): old_invite_link = types.ChatInviteLink._parse( - client, action.prev_invite, users + client, + action.prev_invite, + users, ) new_invite_link = types.ChatInviteLink._parse( - client, action.new_invite, users + client, + action.new_invite, + users, ) action = enums.ChatEventAction.INVITE_LINK_EDITED elif isinstance( - action, raw.types.ChannelAdminLogEventActionExportedInviteRevoke + action, + raw.types.ChannelAdminLogEventActionExportedInviteRevoke, ): revoked_invite_link = types.ChatInviteLink._parse( - client, action.invite, users + client, + action.invite, + users, ) action = enums.ChatEventAction.INVITE_LINK_REVOKED elif isinstance( - action, raw.types.ChannelAdminLogEventActionExportedInviteDelete + action, + raw.types.ChannelAdminLogEventActionExportedInviteDelete, ): deleted_invite_link = types.ChatInviteLink._parse( - client, action.invite, users + client, + action.invite, + users, ) action = enums.ChatEventAction.INVITE_LINK_DELETED elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantJoinByInvite + action, + raw.types.ChannelAdminLogEventActionParticipantJoinByInvite, ): invite_link = types.ChatInviteLink._parse(client, action.invite, users) via_chat_folder_invite_link = getattr(action, "via_chatlist", None) action = enums.ChatEventAction.MEMBER_JOINED_BY_LINK elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantJoinByRequest + action, + raw.types.ChannelAdminLogEventActionParticipantJoinByRequest, ): invite_link = types.ChatInviteLink._parse(client, action.invite, users) approver_user = types.User._parse(client, users[action.approved_by]) action = enums.ChatEventAction.MEMBER_JOINED_BY_REQUEST elif isinstance( - action, raw.types.ChannelAdminLogEventActionParticipantSubExtend + action, + raw.types.ChannelAdminLogEventActionParticipantSubExtend, ): old_chat_member = types.ChatMember._parse( - client, action.prev_participant, users, chats + client, + action.prev_participant, + users, + chats, ) new_chat_member = types.ChatMember._parse( - client, action.new_participant, users, chats + client, + action.new_participant, + users, + chats, ) action = enums.ChatEventAction.MEMBER_SUBSCRIPTION_EXTENDED elif isinstance( - action, raw.types.ChannelAdminLogEventActionToggleSignatureProfiles + action, + raw.types.ChannelAdminLogEventActionToggleSignatureProfiles, ): show_message_sender_enabled = action.new_value action = enums.ChatEventAction.SHOW_MESSAGE_SENDER_ENABLED @@ -599,7 +663,8 @@ async def _parse( action = enums.ChatEventAction.AGGRESSIVE_ANTI_SPAM_TOGGLED elif isinstance( - action, raw.types.ChannelAdminLogEventActionToggleNoForwards + action, + raw.types.ChannelAdminLogEventActionToggleNoForwards, ): has_protected_content = action.new_value action = enums.ChatEventAction.PROTECTED_CONTENT_TOGGLED diff --git a/pyrogram/types/user_and_chats/chat_event_filter.py b/pyrogram/types/user_and_chats/chat_event_filter.py index b0864e62..acb64f20 100644 --- a/pyrogram/types/user_and_chats/chat_event_filter.py +++ b/pyrogram/types/user_and_chats/chat_event_filter.py @@ -80,7 +80,7 @@ def __init__( video_chats: bool = False, forum_changes: bool = False, subscription_extensions: bool = False, - ): + ) -> None: super().__init__() self.new_restrictions = new_restrictions diff --git a/pyrogram/types/user_and_chats/chat_join_request.py b/pyrogram/types/user_and_chats/chat_join_request.py index 3a7f627b..88ac484a 100644 --- a/pyrogram/types/user_and_chats/chat_join_request.py +++ b/pyrogram/types/user_and_chats/chat_join_request.py @@ -91,7 +91,8 @@ async def approve(self) -> bool: RPCError: In case of a Telegram RPC error. """ return await self._client.approve_chat_join_request( - chat_id=self.chat.id, user_id=self.from_user.id + chat_id=self.chat.id, + user_id=self.from_user.id, ) async def decline(self) -> bool: @@ -118,5 +119,6 @@ async def decline(self) -> bool: RPCError: In case of a Telegram RPC error. """ return await self._client.decline_chat_join_request( - chat_id=self.chat.id, user_id=self.from_user.id + chat_id=self.chat.id, + user_id=self.from_user.id, ) diff --git a/pyrogram/types/user_and_chats/chat_member.py b/pyrogram/types/user_and_chats/chat_member.py index 8d20ecd6..dd72f956 100644 --- a/pyrogram/types/user_and_chats/chat_member.py +++ b/pyrogram/types/user_and_chats/chat_member.py @@ -129,7 +129,7 @@ def _parse( user=types.User._parse(client, users[member.user_id]), joined_date=utils.timestamp_to_datetime(member.date), until_date=utils.timestamp_to_datetime( - member.subscription_until_date + member.subscription_until_date, ), client=client, ) @@ -174,7 +174,7 @@ def _parse( user=user, chat=chat, until_date=utils.timestamp_to_datetime( - member.banned_rights.until_date + member.banned_rights.until_date, ), joined_date=utils.timestamp_to_datetime(member.date), is_member=not member.left, @@ -219,7 +219,7 @@ def _parse( joined_date=utils.timestamp_to_datetime(member.date), invited_by=types.User._parse(client, users[member.inviter_id]), until_date=utils.timestamp_to_datetime( - member.subscription_until_date + member.subscription_until_date, ), client=client, ) diff --git a/pyrogram/types/user_and_chats/chat_member_updated.py b/pyrogram/types/user_and_chats/chat_member_updated.py index 26152ce7..ec8af6c9 100644 --- a/pyrogram/types/user_and_chats/chat_member_updated.py +++ b/pyrogram/types/user_and_chats/chat_member_updated.py @@ -105,7 +105,7 @@ def _parse( client=client, ) - chat_id = getattr(update, "chat_id", None) or getattr(update, "channel_id") + chat_id = getattr(update, "chat_id", None) or update.channel_id old_chat_member = None new_chat_member = None @@ -114,12 +114,18 @@ def _parse( if update.prev_participant: old_chat_member = types.ChatMember._parse( - client, update.prev_participant, users, chats + client, + update.prev_participant, + users, + chats, ) if update.new_participant: new_chat_member = types.ChatMember._parse( - client, update.new_participant, users, chats + client, + update.new_participant, + users, + chats, ) if update.invite: diff --git a/pyrogram/types/user_and_chats/chat_reactions.py b/pyrogram/types/user_and_chats/chat_reactions.py index 47202593..61778be2 100644 --- a/pyrogram/types/user_and_chats/chat_reactions.py +++ b/pyrogram/types/user_and_chats/chat_reactions.py @@ -39,7 +39,9 @@ def __init__( @staticmethod def _parse( - client, chat_reactions: raw.base.ChatReactions, reactions_limit: int = 11 + client, + chat_reactions: raw.base.ChatReactions, + reactions_limit: int = 11, ) -> ChatReactions | None: if isinstance(chat_reactions, raw.types.ChatReactionsAll): return ChatReactions( diff --git a/pyrogram/types/user_and_chats/folder.py b/pyrogram/types/user_and_chats/folder.py index e1da9a29..ac1fa5d8 100644 --- a/pyrogram/types/user_and_chats/folder.py +++ b/pyrogram/types/user_and_chats/folder.py @@ -106,20 +106,20 @@ def _parse(client, folder: raw.types.DialogFilter, users, chats) -> Folder: for peer in folder.include_peers: with contextlib.suppress(KeyError): included_chats.append( - types.Chat._parse_dialog(client, peer, users, chats) + types.Chat._parse_dialog(client, peer, users, chats), ) if getattr(folder, "exclude_peers", None): for peer in folder.exclude_peers: with contextlib.suppress(KeyError): excluded_chats.append( - types.Chat._parse_dialog(client, peer, users, chats) + types.Chat._parse_dialog(client, peer, users, chats), ) for peer in folder.pinned_peers: with contextlib.suppress(KeyError): pinned_chats.append( - types.Chat._parse_dialog(client, peer, users, chats) + types.Chat._parse_dialog(client, peer, users, chats), ) return Folder( diff --git a/pyrogram/types/user_and_chats/forum_topic.py b/pyrogram/types/user_and_chats/forum_topic.py index 275b78b8..a9c3c0ef 100644 --- a/pyrogram/types/user_and_chats/forum_topic.py +++ b/pyrogram/types/user_and_chats/forum_topic.py @@ -116,10 +116,14 @@ def _parse(forum_topic: raw.types.forum_topic) -> ForumTopic: read_outbox_max_id=getattr(forum_topic, "read_outbox_max_id", None), unread_count=getattr(forum_topic, "unread_count", None), unread_mentions_count=getattr( - forum_topic, "unread_mentions_count", None + forum_topic, + "unread_mentions_count", + None, ), unread_reactions_count=getattr( - forum_topic, "unread_reactions_count", None + forum_topic, + "unread_reactions_count", + None, ), from_id=peer, my=getattr(forum_topic, "my", None), diff --git a/pyrogram/types/user_and_chats/invite_link_importer.py b/pyrogram/types/user_and_chats/invite_link_importer.py index 8cd57533..b8355680 100644 --- a/pyrogram/types/user_and_chats/invite_link_importer.py +++ b/pyrogram/types/user_and_chats/invite_link_importer.py @@ -40,7 +40,7 @@ def _parse( InviteLinkImporter( date=utils.timestamp_to_datetime(j.date), user=types.User._parse(client=None, user=d[j.user_id]), - ) + ), ) return importers diff --git a/pyrogram/types/user_and_chats/user.py b/pyrogram/types/user_and_chats/user.py index 809135b9..24f66bf7 100644 --- a/pyrogram/types/user_and_chats/user.py +++ b/pyrogram/types/user_and_chats/user.py @@ -273,15 +273,18 @@ def _parse(client, user: raw.base.User) -> User | None: dc_id=getattr(user.photo, "dc_id", None), phone_number=user.phone, photo=types.ChatPhoto._parse( - client, user.photo, user.id, user.access_hash + client, + user.photo, + user.id, + user.access_hash, ), restrictions=types.List( - [types.Restriction._parse(r) for r in user.restriction_reason] + [types.Restriction._parse(r) for r in user.restriction_reason], ) or None, reply_color=types.ChatColor._parse(getattr(user, "color", None)), profile_color=types.ChatColor._parse_profile_color( - getattr(user, "profile_color", None) + getattr(user, "profile_color", None), ), active_users=active_users, client=client, diff --git a/pyrogram/types/user_and_chats/video_chat_scheduled.py b/pyrogram/types/user_and_chats/video_chat_scheduled.py index 3a6fa126..2301540d 100644 --- a/pyrogram/types/user_and_chats/video_chat_scheduled.py +++ b/pyrogram/types/user_and_chats/video_chat_scheduled.py @@ -27,5 +27,5 @@ def _parse( action: raw.types.MessageActionGroupCallScheduled, ) -> VideoChatScheduled: return VideoChatScheduled( - start_date=utils.timestamp_to_datetime(action.schedule_date) + start_date=utils.timestamp_to_datetime(action.schedule_date), ) diff --git a/pyrogram/utils.py b/pyrogram/utils.py index 36c99925..3995435d 100644 --- a/pyrogram/utils.py +++ b/pyrogram/utils.py @@ -41,14 +41,14 @@ def get_input_media_from_file_id( except Exception: raise ValueError( f'Failed to decode "{file_id}". The value does not represent an existing local file, ' - f"HTTP URL, or valid file id." - ) + f"HTTP URL, or valid file id.", + ) from None file_type = decoded.file_type if expected_file_type is not None and file_type != expected_file_type: raise ValueError( - f"Expected {expected_file_type.name}, got {file_type.name} file id instead" + f"Expected {expected_file_type.name}, got {file_type.name} file id instead", ) if file_type in (FileType.THUMBNAIL, FileType.CHAT_PHOTO): @@ -104,10 +104,11 @@ async def parse_messages( users, chats, is_scheduled=isinstance( - u, raw.types.UpdateNewScheduledMessage + u, + raw.types.UpdateNewScheduledMessage, ), replies=1, - ) + ), ) elif isinstance(u, raw.types.UpdateBotNewBusinessMessage): @@ -118,11 +119,13 @@ async def parse_messages( users, chats, business_connection_id=getattr( - u, "connection_id", business_connection_id + u, + "connection_id", + business_connection_id, ), raw_reply_to_message=u.reply_to_message, replies=0, - ) + ), ) return types.List(parsed_messages) @@ -144,14 +147,16 @@ async def parse_messages( replies=1, ) for message in messages.messages - ] + ], ) return types.List(parsed_messages) def parse_deleted_messages( - client, update, business_connection_id: str | None = None + client, + update, + business_connection_id: str | None = None, ) -> list[types.Message]: messages = update.messages channel_id = getattr(update, "channel_id", None) @@ -180,7 +185,10 @@ def pack_inline_message_id( ): if isinstance(msg_id, raw.types.InputBotInlineMessageID): inline_message_id_packed = struct.pack( - " bytes: def xor(a: bytes, b: bytes) -> bytes: - return bytes(i ^ j for i, j in zip(a, b)) + return bytes(i ^ j for i, j in zip(a, b, strict=False)) def compute_password_hash( @@ -297,7 +307,8 @@ def compute_password_hash( def compute_password_check( - r: raw.types.account.Password, password: str + r: raw.types.account.Password, + password: str, ) -> raw.types.InputCheckPasswordSRP: algo = r.current_algo @@ -349,7 +360,7 @@ def compute_password_check( + sha256(algo.salt2) + A_bytes + B_bytes - + K_bytes + + K_bytes, ) return raw.types.InputCheckPasswordSRP(srp_id=srp_id, A=A_bytes, M1=M1_bytes) @@ -385,7 +396,9 @@ def datetime_to_timestamp(dt: datetime | None) -> int | None: async def run_sync( - func: Callable[..., TypeVar("Result")], *args: Any, **kwargs: Any + func: Callable[..., TypeVar("Result")], + *args: Any, + **kwargs: Any, ) -> TypeVar("Result"): loop = asyncio.get_event_loop() return await loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) diff --git a/tests/parser/test_html.py b/tests/parser/test_html.py index f3627314..b941fb0a 100644 --- a/tests/parser/test_html.py +++ b/tests/parser/test_html.py @@ -13,8 +13,8 @@ def test_html_unparse_bold() -> None: type=pyrogram.enums.MessageEntityType.BOLD, offset=0, length=4, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -29,8 +29,8 @@ def test_html_unparse_italic() -> None: type=pyrogram.enums.MessageEntityType.ITALIC, offset=0, length=6, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -45,8 +45,8 @@ def test_html_unparse_underline() -> None: type=pyrogram.enums.MessageEntityType.UNDERLINE, offset=0, length=9, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -61,8 +61,8 @@ def test_html_unparse_strike() -> None: type=pyrogram.enums.MessageEntityType.STRIKETHROUGH, offset=0, length=6, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -77,8 +77,8 @@ def test_html_unparse_spoiler() -> None: type=pyrogram.enums.MessageEntityType.SPOILER, offset=0, length=7, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -94,8 +94,8 @@ def test_html_unparse_url() -> None: offset=0, length=3, url="https://pyrogram.org/", - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -110,8 +110,8 @@ def test_html_unparse_code() -> None: type=pyrogram.enums.MessageEntityType.CODE, offset=0, length=4, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -131,8 +131,8 @@ def test_html_unparse_pre() -> None: offset=0, length=32, language="python", - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -201,7 +201,7 @@ def test_html_unparse_mixed() -> None: offset=57, length=10, ), - ] + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -216,8 +216,8 @@ def test_html_unparse_escaped() -> None: type=pyrogram.enums.MessageEntityType.BOLD, offset=0, length=11, - ) - ] + ), + ], ) assert HTML.unparse(text=text, entities=entities) == expected @@ -240,7 +240,7 @@ def test_html_unparse_escaped_nested() -> None: offset=8, length=16, ), - ] + ], ) assert HTML.unparse(text=text, entities=entities) == expected diff --git a/tests/parser/test_markdown.py b/tests/parser/test_markdown.py new file mode 100644 index 00000000..556d6009 --- /dev/null +++ b/tests/parser/test_markdown.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import pyrogram +from pyrogram.parser.markdown import Markdown + + +def test_markdown_unparse_bold(): + expected = "**bold**" + text = "bold" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.BOLD, + offset=0, + length=4, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_italic(): + expected = "__italic__" + text = "italic" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.ITALIC, + offset=0, + length=6, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_strike(): + expected = "~~strike~~" + text = "strike" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.STRIKETHROUGH, + offset=0, + length=6, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_spoiler(): + expected = "||spoiler||" + text = "spoiler" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.SPOILER, + offset=0, + length=7, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_url(): + expected = "[URL](https://pyrogram.org/)" + text = "URL" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.TEXT_LINK, + offset=0, + length=3, + url="https://pyrogram.org/", + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_code(): + expected = "`code`" + text = "code" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.CODE, + offset=0, + length=4, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_pre(): + expected = """```python +for i in range(10): + print(i) +```""" + + text = """for i in range(10): + print(i)""" + + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.PRE, + offset=0, + length=32, + language="python", + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_blockquote(): + expected = """> Hello +> from + +> pyrogram!""" + + text = """Hello\nfrom\n\npyrogram!""" + + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.BLOCKQUOTE, + offset=0, + length=10, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.BLOCKQUOTE, + offset=12, + length=9, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_mixed(): + expected = "**aaaaaaa__aaabbb**__~~dddddddd||ddeee~~||||eeeeeeefff||ffff`fffggggggg`ggghhhhhhhhhh" + text = "aaaaaaaaaabbbddddddddddeeeeeeeeeeffffffffffgggggggggghhhhhhhhhh" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.BOLD, + offset=0, + length=13, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.ITALIC, + offset=7, + length=6, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.STRIKETHROUGH, + offset=13, + length=13, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.SPOILER, + offset=21, + length=5, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.SPOILER, + offset=26, + length=10, + ), + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.CODE, + offset=40, + length=10, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_no_entities(): + expected = "text" + text = "text" + entities = [] + + assert Markdown.unparse(text=text, entities=entities) == expected + + +def test_markdown_unparse_html(): + expected = "__This works, it's ok__ This shouldn't" + text = "This works, it's ok This shouldn't" + entities = pyrogram.types.List( + [ + pyrogram.types.MessageEntity( + type=pyrogram.enums.MessageEntityType.ITALIC, + offset=0, + length=19, + ), + ], + ) + + assert Markdown.unparse(text=text, entities=entities) == expected diff --git a/tests/test_file_id.py b/tests/test_file_id.py index 92a8d06a..dd642c25 100644 --- a/tests/test_file_id.py +++ b/tests/test_file_id.py @@ -18,7 +18,8 @@ def check(file_id: str, expected_file_type: FileType) -> None: def check_unique( - file_unique_id: str, expected_file_unique_type: FileUniqueType + file_unique_id: str, + expected_file_unique_type: FileUniqueType, ) -> None: decoded = FileUniqueId.decode(file_unique_id)