From c27f811620bd0fdd52b5111040ce9daa20822b96 Mon Sep 17 00:00:00 2001 From: Mendel E <31070530+mendelmaleh@users.noreply.github.com> Date: Mon, 20 Jul 2020 22:04:24 -0400 Subject: [PATCH 01/16] Add parse_mode property to Client (#443) * Add parse_mode property to Client This breaks set_parse_mode * Add back set_parse_mode for backwards compatibility --- pyrogram/client/client.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py index af67cc1a..79275103 100644 --- a/pyrogram/client/client.py +++ b/pyrogram/client/client.py @@ -143,6 +143,11 @@ class Client(Methods, BaseClient): Your Smart Plugins settings as dict, e.g.: *dict(root="plugins")*. This is an alternative way to setup plugins if you don't want to use the *config.ini* file. + parse_mode (``str``, *optional*): + The parse mode, can be any of: *"combined"*, for the default combined mode. *"markdown"* or *"md"* + to force Markdown-only styles. *"html"* to force HTML-only styles. *None* to disable the parser + completely. + no_updates (``bool``, *optional*): Pass True to completely disable incoming updates for the current session. When updates are disabled your client can't receive any new message. @@ -184,6 +189,7 @@ class Client(Methods, BaseClient): workdir: str = BaseClient.WORKDIR, config_file: str = BaseClient.CONFIG_FILE, plugins: dict = None, + parse_mode: str = BaseClient.PARSE_MODES[0], no_updates: bool = None, takeout: bool = None, sleep_threshold: int = Session.SLEEP_THRESHOLD @@ -210,6 +216,7 @@ class Client(Methods, BaseClient): self.workdir = Path(workdir) self.config_file = Path(config_file) self.plugins = plugins + self.parse_mode = parse_mode self.no_updates = no_updates self.takeout = takeout self.sleep_threshold = sleep_threshold @@ -1131,6 +1138,21 @@ class Client(Methods, BaseClient): """ return self.storage.export_session_string() + @property + def parse_mode(self): + return self._parse_mode + + @parse_mode.setter + def parse_mode(self, parse_mode: Union[str, None] = "combined"): + if parse_mode not in self.PARSE_MODES: + raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format( + ", ".join('"{}"'.format(m) for m in self.PARSE_MODES[:-1]), + parse_mode + )) + + self._parse_mode = parse_mode + + # TODO: redundant, remove in next major version def set_parse_mode(self, parse_mode: Union[str, None] = "combined"): """Set the parse mode to be used globally by the client. @@ -1176,12 +1198,6 @@ class Client(Methods, BaseClient): app.send_message("haskell", "5. **markdown** and html") """ - if parse_mode not in self.PARSE_MODES: - raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format( - ", ".join('"{}"'.format(m) for m in self.PARSE_MODES[:-1]), - parse_mode - )) - self.parse_mode = parse_mode def fetch_peers(self, peers: List[Union[types.User, types.Chat, types.Channel]]) -> bool: From e5fda6f9a0833e99aa433c0f24b2e573df2a25f0 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sun, 26 Jul 2020 12:28:15 +0200 Subject: [PATCH 02/16] Update API schema to Layer 116 --- compiler/api/source/main_api.tl | 43 ++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/compiler/api/source/main_api.tl b/compiler/api/source/main_api.tl index 3d48a8cb..3c073c43 100644 --- a/compiler/api/source/main_api.tl +++ b/compiler/api/source/main_api.tl @@ -40,10 +40,9 @@ inputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector< inputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia; inputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia; inputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia; -inputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia; +inputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia; inputMediaDocument#23ab23d2 flags:# id:InputDocument ttl_seconds:flags.0?int = InputMedia; inputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia; -inputMediaGifExternal#4843b0fd url:string q:string = InputMedia; inputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia; inputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia; inputMediaGame#d33f43f3 id:InputGame = InputMedia; @@ -53,7 +52,7 @@ inputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector s inputMediaDice#e66fbf7b emoticon:string = InputMedia; inputChatPhotoEmpty#1ca48f57 = InputChatPhoto; -inputChatUploadedPhoto#927c55b4 file:InputFile = InputChatPhoto; +inputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto; inputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto; inputGeoPointEmpty#e4c123d6 = InputGeoPoint; @@ -91,7 +90,7 @@ userEmpty#200250ba id:int = User; user#938458c1 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 id:int 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 = User; userProfilePhotoEmpty#4f11bae1 = UserProfilePhoto; -userProfilePhoto#ecd75d8c photo_id:long photo_small:FileLocation photo_big:FileLocation dc_id:int = UserProfilePhoto; +userProfilePhoto#69d3ab26 flags:# has_video:flags.0?true photo_id:long photo_small:FileLocation photo_big:FileLocation dc_id:int = UserProfilePhoto; userStatusEmpty#9d05049 = UserStatus; userStatusOnline#edb93949 expires:int = UserStatus; @@ -117,7 +116,7 @@ chatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0? chatParticipants#3f460fed chat_id:int participants:Vector version:int = ChatParticipants; chatPhotoEmpty#37c1011c = ChatPhoto; -chatPhoto#475cdbd5 photo_small:FileLocation photo_big:FileLocation dc_id:int = ChatPhoto; +chatPhoto#d20b9f3c flags:# has_video:flags.0?true photo_small:FileLocation photo_big:FileLocation dc_id:int = ChatPhoto; messageEmpty#83e5de54 id:int = Message; message#452c0e65 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 id:int from_id:flags.8?int to_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to_msg_id:flags.3?int date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector = Message; @@ -165,7 +164,7 @@ dialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer t dialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog; photoEmpty#2331b22d id:long = Photo; -photo#d07504a5 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector dc_id:int = Photo; +photo#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo; photoSizeEmpty#e17e23c type:string = PhotoSize; photoSize#77bfb61b type:string location:FileLocation w:int h:int size:int = PhotoSize; @@ -191,7 +190,7 @@ inputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags peerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings; -peerSettings#818426cd flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true = PeerSettings; +peerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true geo_distance:flags.6?int = PeerSettings; wallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper; wallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper; @@ -336,6 +335,7 @@ updateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update; updateDialogFilterOrder#a5d72105 order:Vector = Update; updateDialogFilters#3504914f = Update; updatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update; +updateChannelParticipant#65d2b464 flags:# channel_id:int date:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant qts:int = Update; updates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State; @@ -373,7 +373,7 @@ help.inviteText#18cb9f78 message:string = help.InviteText; encryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat; encryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat; -encryptedChatRequested#c878527e id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat; +encryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat; encryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long = EncryptedChat; encryptedChatDiscarded#13d6dd27 id:int = EncryptedChat; @@ -507,6 +507,7 @@ chatInviteExported#fc2e05bc link:string = ExportedChatInvite; chatInviteAlready#5a686d7c chat:Chat = ChatInvite; chatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite; +chatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite; inputStickerSetEmpty#ffb62b95 = InputStickerSet; inputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet; @@ -597,11 +598,6 @@ channels.channelParticipant#d0d9b163 participant:ChannelParticipant users:Vector help.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService; -foundGif#162ecc1f url:string thumb_url:string content_url:string content_type:string w:int h:int = FoundGif; -foundGifCached#9c750409 url:string photo:Photo document:Document = FoundGif; - -messages.foundGifs#450a1c0a next_offset:int results:Vector = messages.FoundGifs; - messages.savedGifsNotModified#e8025ca2 = messages.SavedGifs; messages.savedGifs#2e0709a5 hash:int gifs:Vector = messages.SavedGifs; @@ -1119,7 +1115,17 @@ stats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueA help.promoDataEmpty#98f6ac75 expires:int = help.PromoData; help.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData; -videoSize#435bb987 type:string location:FileLocation w:int h:int size:int = VideoSize; +videoSize#e831c556 flags:# type:string location:FileLocation w:int h:int size:int video_start_ts:flags.0?double = VideoSize; + +statsGroupTopPoster#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster; + +statsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin; + +statsGroupTopInviter#31962a4c user_id:int invitations:int = StatsGroupTopInviter; + +stats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats; + +globalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings; ---functions--- @@ -1215,6 +1221,8 @@ account.getThemes#285946f8 format:string hash:int = account.Themes; account.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool; account.getContentSettings#8b9b4dae = account.ContentSettings; account.getMultiWallPapers#65ad71dc wallpapers:Vector = Vector; +account.getGlobalPrivacySettings#eb2b4cf6 = GlobalPrivacySettings; +account.setGlobalPrivacySettings#1edaaac2 settings:GlobalPrivacySettings = GlobalPrivacySettings; users.getUsers#d91a548 id:Vector = Vector; users.getFullUser#ca30a5b1 id:InputUser = UserFull; @@ -1290,7 +1298,6 @@ messages.migrateChat#15a3b8e3 chat_id:int = Updates; messages.searchGlobal#bf7225a4 flags:# folder_id:flags.0?int q:string offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages; messages.reorderStickerSets#78337739 flags:# masks:flags.0?true order:Vector = Bool; messages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document; -messages.searchGifs#bf9a776b q:string offset:int = messages.FoundGifs; messages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs; messages.saveGif#327a30cb id:InputDocument unsave:Bool = Bool; messages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults; @@ -1370,7 +1377,7 @@ updates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date: updates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference; photos.updateProfilePhoto#f0bb5152 id:InputPhoto = UserProfilePhoto; -photos.uploadProfilePhoto#4f32c098 file:InputFile = photos.Photo; +photos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo; photos.deletePhotos#87cf7f2f id:Vector = Vector; photos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos; @@ -1403,6 +1410,7 @@ help.getUserInfo#38a08d3 user_id:InputUser = help.UserInfo; help.editUserInfo#66b91b70 user_id:InputUser message:string entities:Vector = help.UserInfo; help.getPromoData#c0977421 = help.PromoData; help.hidePromoData#1e251c95 peer:InputPeer = Bool; +help.dismissSuggestion#77fa99f suggestion:string = Bool; channels.readHistory#cc104937 channel:InputChannel max_id:int = Bool; channels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages; @@ -1479,5 +1487,6 @@ folders.deleteFolder#1c295881 folder_id:int = Updates; stats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats; stats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph; +stats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats; -// LAYER 114 \ No newline at end of file +// LAYER 116 \ No newline at end of file From b29c5fdc69e4d3af274761dac22acc962c6f6ff1 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sun, 26 Jul 2020 20:23:58 +0200 Subject: [PATCH 03/16] Force document when using send_document --- pyrogram/client/methods/messages/send_document.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pyrogram/client/methods/messages/send_document.py b/pyrogram/client/methods/messages/send_document.py index 2241754b..8faf8374 100644 --- a/pyrogram/client/methods/messages/send_document.py +++ b/pyrogram/client/methods/messages/send_document.py @@ -152,6 +152,7 @@ class SendDocument(BaseClient): media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(document) or "application/zip", file=file, + force_file=True, thumb=thumb, attributes=[ types.DocumentAttributeFilename(file_name=file_name or os.path.basename(document)) From aaedeffff9cf489d46b397964d8d2120d2c9cb17 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sun, 26 Jul 2020 23:17:53 +0200 Subject: [PATCH 04/16] Update instructions for accessing test servers in tdesktop --- docs/source/topics/test-servers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/topics/test-servers.rst b/docs/source/topics/test-servers.rst index 451fc98a..1906c2f1 100644 --- a/docs/source/topics/test-servers.rst +++ b/docs/source/topics/test-servers.rst @@ -30,7 +30,7 @@ Test Mode in Official Apps You can also login yourself into test servers using official desktop apps, such as Webogram and TDesktop: - **Webogram**: Login here: https://web.telegram.org/?test=1 -- **TDesktop**: Open settings and type ``testmode``. +- **TDesktop**: Hold ``Alt+Shift`` and right click on "Add account", then choose "Test server". Test Numbers ------------ From 9a8057074bacbd1983c379b30a447808f52ee3af Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sun, 26 Jul 2020 23:18:26 +0200 Subject: [PATCH 05/16] Allow uploading profile photos using file-like objects --- pyrogram/client/methods/users/set_profile_photo.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pyrogram/client/methods/users/set_profile_photo.py b/pyrogram/client/methods/users/set_profile_photo.py index ae627110..e7357030 100644 --- a/pyrogram/client/methods/users/set_profile_photo.py +++ b/pyrogram/client/methods/users/set_profile_photo.py @@ -18,22 +18,26 @@ from pyrogram.api import functions from ...ext import BaseClient +from typing import Union, BinaryIO class SetProfilePhoto(BaseClient): def set_profile_photo( self, - photo: str + photo: Union[str, BinaryIO] ) -> bool: """Set a new profile photo. + If you want to set a profile video instead, use :meth:`~Client.set_profile_video` + This method only works for Users. Bots profile photos must be set using BotFather. Parameters: photo (``str``): Profile photo to set. - Pass a file path as string to upload a new photo that exists on your local machine. + Pass a file path as string to upload a new photo that exists on your local machine or + pass a binary file-like object with its attribute ".name" set for in-memory uploads. Returns: ``bool``: True on success. From 2034a785f4492850850318e3b3368fe48cdd97a0 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sun, 26 Jul 2020 23:18:52 +0200 Subject: [PATCH 06/16] Add set_profile_video method --- compiler/docs/compiler.py | 1 + pyrogram/client/methods/users/__init__.py | 4 +- .../client/methods/users/set_profile_video.py | 57 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 pyrogram/client/methods/users/set_profile_video.py diff --git a/compiler/docs/compiler.py b/compiler/docs/compiler.py index 8afd99f8..d0c1f61c 100644 --- a/compiler/docs/compiler.py +++ b/compiler/docs/compiler.py @@ -225,6 +225,7 @@ def pyrogram_api(): get_profile_photos_count iter_profile_photos set_profile_photo + set_profile_video delete_profile_photos update_username update_profile diff --git a/pyrogram/client/methods/users/__init__.py b/pyrogram/client/methods/users/__init__.py index 65171af6..e80a1c76 100644 --- a/pyrogram/client/methods/users/__init__.py +++ b/pyrogram/client/methods/users/__init__.py @@ -25,6 +25,7 @@ from .get_profile_photos_count import GetProfilePhotosCount from .get_users import GetUsers from .iter_profile_photos import IterProfilePhotos from .set_profile_photo import SetProfilePhoto +from .set_profile_video import SetProfileVideo from .unblock_user import UnblockUser from .update_profile import UpdateProfile from .update_username import UpdateUsername @@ -42,6 +43,7 @@ class Users( GetProfilePhotosCount, IterProfilePhotos, UnblockUser, - UpdateProfile + UpdateProfile, + SetProfileVideo ): pass diff --git a/pyrogram/client/methods/users/set_profile_video.py b/pyrogram/client/methods/users/set_profile_video.py new file mode 100644 index 00000000..82213a65 --- /dev/null +++ b/pyrogram/client/methods/users/set_profile_video.py @@ -0,0 +1,57 @@ +# Pyrogram - Telegram MTProto API Client Library for Python +# Copyright (C) 2017-2020 Dan +# +# This file is part of Pyrogram. +# +# Pyrogram is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Pyrogram is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Pyrogram. If not, see . + +from typing import Union, BinaryIO + +from pyrogram.api import functions +from ...ext import BaseClient + + +class SetProfileVideo(BaseClient): + def set_profile_video( + self, + video: Union[str, BinaryIO] + ) -> bool: + """Set a new profile video (H.264/MPEG-4 AVC video, max 5 seconds). + + If you want to set a profile photo instead, use :meth:`~Client.set_profile_photo` + + This method only works for Users. + + Parameters: + video (``str``): + Profile video to set. + Pass a file path as string to upload a new video that exists on your local machine or + pass a binary file-like object with its attribute ".name" set for in-memory uploads. + + Returns: + ``bool``: True on success. + + Example: + .. code-block:: python + + app.set_profile_video("new_video.mp4") + """ + + return bool( + self.send( + functions.photos.UploadProfilePhoto( + video=self.save_file(video) + ) + ) + ) From 8a14f5842123276aa3cd2434e3fbf0ba0c6aa3a7 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 13:33:17 +0200 Subject: [PATCH 07/16] Allow uploading chat photos using BytesIO objects --- .../client/methods/chats/set_chat_photo.py | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/pyrogram/client/methods/chats/set_chat_photo.py b/pyrogram/client/methods/chats/set_chat_photo.py index e22b6819..593da47a 100644 --- a/pyrogram/client/methods/chats/set_chat_photo.py +++ b/pyrogram/client/methods/chats/set_chat_photo.py @@ -17,7 +17,7 @@ # along with Pyrogram. If not, see . import os -from typing import Union +from typing import Union, BinaryIO from pyrogram.api import functions, types from ...ext import BaseClient, utils @@ -27,7 +27,7 @@ class SetChatPhoto(BaseClient): def set_chat_photo( self, chat_id: Union[int, str], - photo: str, + photo: Union[str, BinaryIO], file_ref: str = None ) -> bool: """Set a new profile photo for the chat. @@ -39,12 +39,13 @@ class SetChatPhoto(BaseClient): Unique identifier (int) or username (str) of the target chat. photo (``str``): - New chat photo. You can pass a :obj:`Photo` file_id or a file path to upload a new photo from your local - machine. + New chat photo. You can pass a :obj:`Photo` file_id (in pair with a valid file_ref), a file path to + upload a new photo from your local machine or a binary file-like object with its attribute ".name" + set for in-memory uploads. file_ref (``str``, *optional*): A valid file reference obtained by a recently fetched media message. - To be used in combination with a file id in case a file reference is needed. + To be used in combination with a file_id in case a file reference is needed. Returns: ``bool``: True on success. @@ -63,11 +64,14 @@ class SetChatPhoto(BaseClient): """ peer = self.resolve_peer(chat_id) - if os.path.isfile(photo): - photo = types.InputChatUploadedPhoto(file=self.save_file(photo)) + if isinstance(photo, str): + if os.path.isfile(photo): + photo = types.InputChatUploadedPhoto(file=self.save_file(photo)) + else: + photo = utils.get_input_media_from_file_id(photo, file_ref, 2) + photo = types.InputChatPhoto(id=photo.id) else: - photo = utils.get_input_media_from_file_id(photo, file_ref, 2) - photo = types.InputChatPhoto(id=photo.id) + photo = types.InputChatUploadedPhoto(file=self.save_file(photo)) if isinstance(peer, types.InputPeerChat): self.send( From 66e7573730dcc68452431d7d3e49ad2308228346 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 13:42:05 +0200 Subject: [PATCH 08/16] Add new RPC errors --- compiler/error/source/400_BAD_REQUEST.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/error/source/400_BAD_REQUEST.tsv b/compiler/error/source/400_BAD_REQUEST.tsv index ba6f6815..608bcc9d 100644 --- a/compiler/error/source/400_BAD_REQUEST.tsv +++ b/compiler/error/source/400_BAD_REQUEST.tsv @@ -145,3 +145,5 @@ BROADCAST_PUBLIC_VOTERS_FORBIDDEN Polls with public voters cannot be sent in cha INPUT_FILTER_INVALID The filter is invalid for this query EMOTICON_EMPTY The emoticon parameter is empty EMOTICON_INVALID The emoticon parameter is invalid +VIDEO_FILE_INVALID The video file is invalid +PRIVACY_TOO_LONG Your privacy exception list has exceeded the maximum capacity \ No newline at end of file From 293e63008bd2637d0b021458e88dc6f07e2a210d Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 13:42:27 +0200 Subject: [PATCH 09/16] Add set_chat_video method --- compiler/docs/compiler.py | 1 + pyrogram/client/methods/chats/__init__.py | 7 +- .../client/methods/chats/set_chat_video.py | 79 +++++++++++++++++++ 3 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 pyrogram/client/methods/chats/set_chat_video.py diff --git a/compiler/docs/compiler.py b/compiler/docs/compiler.py index d0c1f61c..b26a4a8f 100644 --- a/compiler/docs/compiler.py +++ b/compiler/docs/compiler.py @@ -190,6 +190,7 @@ def pyrogram_api(): set_administrator_title export_chat_invite_link set_chat_photo + set_chat_video delete_chat_photo set_chat_title set_chat_description diff --git a/pyrogram/client/methods/chats/__init__.py b/pyrogram/client/methods/chats/__init__.py index 8c7fb340..2987133a 100644 --- a/pyrogram/client/methods/chats/__init__.py +++ b/pyrogram/client/methods/chats/__init__.py @@ -45,11 +45,13 @@ from .set_chat_description import SetChatDescription from .set_chat_permissions import SetChatPermissions from .set_chat_photo import SetChatPhoto from .set_chat_title import SetChatTitle +from .set_chat_video import SetChatVideo +from .set_slow_mode import SetSlowMode from .unarchive_chats import UnarchiveChats from .unban_chat_member import UnbanChatMember from .unpin_chat_message import UnpinChatMessage from .update_chat_username import UpdateChatUsername -from .set_slow_mode import SetSlowMode + class Chats( GetChat, @@ -85,6 +87,7 @@ class Chats( DeleteSupergroup, GetNearbyChats, SetAdministratorTitle, - SetSlowMode + SetSlowMode, + SetChatVideo ): pass diff --git a/pyrogram/client/methods/chats/set_chat_video.py b/pyrogram/client/methods/chats/set_chat_video.py new file mode 100644 index 00000000..3f299488 --- /dev/null +++ b/pyrogram/client/methods/chats/set_chat_video.py @@ -0,0 +1,79 @@ +# Pyrogram - Telegram MTProto API Client Library for Python +# Copyright (C) 2017-2020 Dan +# +# This file is part of Pyrogram. +# +# Pyrogram is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Pyrogram is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Pyrogram. If not, see . + +from typing import Union, BinaryIO + +from pyrogram.api import functions, types +from ...ext import BaseClient + + +class SetChatVideo(BaseClient): + def set_chat_video( + self, + chat_id: Union[int, str], + video: Union[str, BinaryIO], + ) -> bool: + """Set a new profile video for the chat (H.264/MPEG-4 AVC video, max 5 seconds). + + You must be an administrator in the chat for this to work and must have the appropriate admin rights. + + Parameters: + chat_id (``int`` | ``str``): + Unique identifier (int) or username (str) of the target chat. + + video (``str``): + New chat photo. You can pass a :obj:`Photo` file_id (in pair with a valid file_ref), a file path to + upload a new photo from your local machine or a binary file-like object with its attribute ".name" + set for in-memory uploads. + + Returns: + ``bool``: True on success. + + Raises: + ValueError: if a chat_id belongs to user. + + Example: + .. code-block:: python + + # Set chat using a local file + app.set_chat_video(chat_id, "video.mp4") + + # Set chat photo using an exiting Photo file_id + app.set_chat_photo(chat_id, photo.file_id, photo.file_ref) + """ + peer = self.resolve_peer(chat_id) + photo = types.InputChatUploadedPhoto(video=self.save_file(video)) + + if isinstance(peer, types.InputPeerChat): + self.send( + functions.messages.EditChatPhoto( + chat_id=peer.chat_id, + photo=photo + ) + ) + elif isinstance(peer, types.InputPeerChannel): + self.send( + functions.channels.EditPhoto( + channel=peer, + photo=photo + ) + ) + else: + raise ValueError("The chat_id \"{}\" belongs to a user".format(chat_id)) + + return True From d5fc21e6f4c9664dc0781b65c0257ab9ce2cf727 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 14:27:09 +0200 Subject: [PATCH 10/16] Get the proper biggest photo size --- pyrogram/client/types/messages_and_media/photo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyrogram/client/types/messages_and_media/photo.py b/pyrogram/client/types/messages_and_media/photo.py index 36d37cac..fe0678ab 100644 --- a/pyrogram/client/types/messages_and_media/photo.py +++ b/pyrogram/client/types/messages_and_media/photo.py @@ -82,7 +82,7 @@ class Photo(Object): @staticmethod def _parse(client, photo: types.Photo, ttl_seconds: int = None) -> "Photo": if isinstance(photo, types.Photo): - big = photo.sizes[-1] + big = list(filter(lambda p: isinstance(p, types.PhotoSize), photo.sizes))[-1] return Photo( file_id=encode_file_id( From b745ce95ed5d0a7ac596680218f22571364bd200 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 15:03:23 +0200 Subject: [PATCH 11/16] Remove set_chat/profile_video --- compiler/docs/compiler.py | 2 - pyrogram/client/methods/chats/__init__.py | 4 +- .../client/methods/chats/set_chat_photo.py | 37 +++++++-- .../client/methods/chats/set_chat_video.py | 79 ------------------- pyrogram/client/methods/users/__init__.py | 2 - .../client/methods/users/set_profile_photo.py | 34 +++++--- .../client/methods/users/set_profile_video.py | 57 ------------- 7 files changed, 56 insertions(+), 159 deletions(-) delete mode 100644 pyrogram/client/methods/chats/set_chat_video.py delete mode 100644 pyrogram/client/methods/users/set_profile_video.py diff --git a/compiler/docs/compiler.py b/compiler/docs/compiler.py index b26a4a8f..8afd99f8 100644 --- a/compiler/docs/compiler.py +++ b/compiler/docs/compiler.py @@ -190,7 +190,6 @@ def pyrogram_api(): set_administrator_title export_chat_invite_link set_chat_photo - set_chat_video delete_chat_photo set_chat_title set_chat_description @@ -226,7 +225,6 @@ def pyrogram_api(): get_profile_photos_count iter_profile_photos set_profile_photo - set_profile_video delete_profile_photos update_username update_profile diff --git a/pyrogram/client/methods/chats/__init__.py b/pyrogram/client/methods/chats/__init__.py index 2987133a..6e4a9228 100644 --- a/pyrogram/client/methods/chats/__init__.py +++ b/pyrogram/client/methods/chats/__init__.py @@ -45,7 +45,6 @@ from .set_chat_description import SetChatDescription from .set_chat_permissions import SetChatPermissions from .set_chat_photo import SetChatPhoto from .set_chat_title import SetChatTitle -from .set_chat_video import SetChatVideo from .set_slow_mode import SetSlowMode from .unarchive_chats import UnarchiveChats from .unban_chat_member import UnbanChatMember @@ -87,7 +86,6 @@ class Chats( DeleteSupergroup, GetNearbyChats, SetAdministratorTitle, - SetSlowMode, - SetChatVideo + SetSlowMode ): pass diff --git a/pyrogram/client/methods/chats/set_chat_photo.py b/pyrogram/client/methods/chats/set_chat_photo.py index 593da47a..f5ef954f 100644 --- a/pyrogram/client/methods/chats/set_chat_photo.py +++ b/pyrogram/client/methods/chats/set_chat_photo.py @@ -27,10 +27,15 @@ class SetChatPhoto(BaseClient): def set_chat_photo( self, chat_id: Union[int, str], - photo: Union[str, BinaryIO], + *, + photo: Union[str, BinaryIO] = None, + video: Union[str, BinaryIO] = None, file_ref: str = None ) -> bool: - """Set a new profile photo for the chat. + """Set a new chat photo or video (H.264/MPEG-4 AVC video, max 5 seconds). + + The ``photo`` and ``video`` arguments are mutually exclusive. + Pass either one as named argument (see examples below). You must be an administrator in the chat for this to work and must have the appropriate admin rights. @@ -38,11 +43,16 @@ class SetChatPhoto(BaseClient): chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. - photo (``str``): + photo (``str`` | ``BinaryIO``, *optional*): New chat photo. You can pass a :obj:`Photo` file_id (in pair with a valid file_ref), a file path to upload a new photo from your local machine or a binary file-like object with its attribute ".name" set for in-memory uploads. + video (``str`` | ``BinaryIO``, *optional*): + New chat video. You can pass a :obj:`Video` file_id (in pair with a valid file_ref), a file path to + upload a new video from your local machine or a binary file-like object with its attribute ".name" + set for in-memory uploads. + file_ref (``str``, *optional*): A valid file reference obtained by a recently fetched media message. To be used in combination with a file_id in case a file reference is needed. @@ -57,21 +67,34 @@ class SetChatPhoto(BaseClient): .. code-block:: python # Set chat photo using a local file - app.set_chat_photo(chat_id, "photo.jpg") + app.set_chat_photo(chat_id, photo="photo.jpg") # Set chat photo using an exiting Photo file_id - app.set_chat_photo(chat_id, photo.file_id, photo.file_ref) + app.set_chat_photo(chat_id, photo=photo.file_id, file_ref=photo.file_ref) + + + # Set chat video using a local file + app.set_chat_photo(chat_id, video="video.mp4") + + # Set chat photo using an exiting Video file_id + app.set_chat_photo(chat_id, video=video.file_id, file_ref=video.file_ref) """ peer = self.resolve_peer(chat_id) if isinstance(photo, str): if os.path.isfile(photo): - photo = types.InputChatUploadedPhoto(file=self.save_file(photo)) + photo = types.InputChatUploadedPhoto( + file=self.save_file(photo), + video=self.save_file(video) + ) else: photo = utils.get_input_media_from_file_id(photo, file_ref, 2) photo = types.InputChatPhoto(id=photo.id) else: - photo = types.InputChatUploadedPhoto(file=self.save_file(photo)) + photo = types.InputChatUploadedPhoto( + file=self.save_file(photo), + video=self.save_file(video) + ) if isinstance(peer, types.InputPeerChat): self.send( diff --git a/pyrogram/client/methods/chats/set_chat_video.py b/pyrogram/client/methods/chats/set_chat_video.py deleted file mode 100644 index 3f299488..00000000 --- a/pyrogram/client/methods/chats/set_chat_video.py +++ /dev/null @@ -1,79 +0,0 @@ -# Pyrogram - Telegram MTProto API Client Library for Python -# Copyright (C) 2017-2020 Dan -# -# This file is part of Pyrogram. -# -# Pyrogram is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as published -# by the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Pyrogram is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with Pyrogram. If not, see . - -from typing import Union, BinaryIO - -from pyrogram.api import functions, types -from ...ext import BaseClient - - -class SetChatVideo(BaseClient): - def set_chat_video( - self, - chat_id: Union[int, str], - video: Union[str, BinaryIO], - ) -> bool: - """Set a new profile video for the chat (H.264/MPEG-4 AVC video, max 5 seconds). - - You must be an administrator in the chat for this to work and must have the appropriate admin rights. - - Parameters: - chat_id (``int`` | ``str``): - Unique identifier (int) or username (str) of the target chat. - - video (``str``): - New chat photo. You can pass a :obj:`Photo` file_id (in pair with a valid file_ref), a file path to - upload a new photo from your local machine or a binary file-like object with its attribute ".name" - set for in-memory uploads. - - Returns: - ``bool``: True on success. - - Raises: - ValueError: if a chat_id belongs to user. - - Example: - .. code-block:: python - - # Set chat using a local file - app.set_chat_video(chat_id, "video.mp4") - - # Set chat photo using an exiting Photo file_id - app.set_chat_photo(chat_id, photo.file_id, photo.file_ref) - """ - peer = self.resolve_peer(chat_id) - photo = types.InputChatUploadedPhoto(video=self.save_file(video)) - - if isinstance(peer, types.InputPeerChat): - self.send( - functions.messages.EditChatPhoto( - chat_id=peer.chat_id, - photo=photo - ) - ) - elif isinstance(peer, types.InputPeerChannel): - self.send( - functions.channels.EditPhoto( - channel=peer, - photo=photo - ) - ) - else: - raise ValueError("The chat_id \"{}\" belongs to a user".format(chat_id)) - - return True diff --git a/pyrogram/client/methods/users/__init__.py b/pyrogram/client/methods/users/__init__.py index e80a1c76..8ecf45f6 100644 --- a/pyrogram/client/methods/users/__init__.py +++ b/pyrogram/client/methods/users/__init__.py @@ -25,7 +25,6 @@ from .get_profile_photos_count import GetProfilePhotosCount from .get_users import GetUsers from .iter_profile_photos import IterProfilePhotos from .set_profile_photo import SetProfilePhoto -from .set_profile_video import SetProfileVideo from .unblock_user import UnblockUser from .update_profile import UpdateProfile from .update_username import UpdateUsername @@ -44,6 +43,5 @@ class Users( IterProfilePhotos, UnblockUser, UpdateProfile, - SetProfileVideo ): pass diff --git a/pyrogram/client/methods/users/set_profile_photo.py b/pyrogram/client/methods/users/set_profile_photo.py index e7357030..01741df9 100644 --- a/pyrogram/client/methods/users/set_profile_photo.py +++ b/pyrogram/client/methods/users/set_profile_photo.py @@ -16,42 +16,58 @@ # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see . +from typing import Union, BinaryIO + from pyrogram.api import functions from ...ext import BaseClient -from typing import Union, BinaryIO class SetProfilePhoto(BaseClient): def set_profile_photo( self, - photo: Union[str, BinaryIO] + *, + photo: Union[str, BinaryIO] = None, + video: Union[str, BinaryIO] = None ) -> bool: - """Set a new profile photo. + """Set a new profile photo or video (H.264/MPEG-4 AVC video, max 5 seconds). - If you want to set a profile video instead, use :meth:`~Client.set_profile_video` + The ``photo`` and ``video`` arguments are mutually exclusive. + Pass either one as named argument (see examples below). - This method only works for Users. - Bots profile photos must be set using BotFather. + .. note:: + + This method only works for Users. + Bots profile photos must be set using BotFather. Parameters: - photo (``str``): + photo (``str`` | ``BinaryIO``, *optional*): Profile photo to set. Pass a file path as string to upload a new photo that exists on your local machine or pass a binary file-like object with its attribute ".name" set for in-memory uploads. + video (``str`` | ``BinaryIO``, *optional*): + Profile video to set. + Pass a file path as string to upload a new video that exists on your local machine or + pass a binary file-like object with its attribute ".name" set for in-memory uploads. + Returns: ``bool``: True on success. Example: .. code-block:: python - app.set_profile_photo("new_photo.jpg") + # Set a new profile photo + app.set_profile_photo(photo="new_photo.jpg") + + # Set a new profile video + app.set_profile_photo(video="new_video.mp4") """ return bool( self.send( functions.photos.UploadProfilePhoto( - file=self.save_file(photo) + file=self.save_file(photo), + video=self.save_file(video) ) ) ) diff --git a/pyrogram/client/methods/users/set_profile_video.py b/pyrogram/client/methods/users/set_profile_video.py deleted file mode 100644 index 82213a65..00000000 --- a/pyrogram/client/methods/users/set_profile_video.py +++ /dev/null @@ -1,57 +0,0 @@ -# Pyrogram - Telegram MTProto API Client Library for Python -# Copyright (C) 2017-2020 Dan -# -# This file is part of Pyrogram. -# -# Pyrogram is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as published -# by the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Pyrogram is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with Pyrogram. If not, see . - -from typing import Union, BinaryIO - -from pyrogram.api import functions -from ...ext import BaseClient - - -class SetProfileVideo(BaseClient): - def set_profile_video( - self, - video: Union[str, BinaryIO] - ) -> bool: - """Set a new profile video (H.264/MPEG-4 AVC video, max 5 seconds). - - If you want to set a profile photo instead, use :meth:`~Client.set_profile_photo` - - This method only works for Users. - - Parameters: - video (``str``): - Profile video to set. - Pass a file path as string to upload a new video that exists on your local machine or - pass a binary file-like object with its attribute ".name" set for in-memory uploads. - - Returns: - ``bool``: True on success. - - Example: - .. code-block:: python - - app.set_profile_video("new_video.mp4") - """ - - return bool( - self.send( - functions.photos.UploadProfilePhoto( - video=self.save_file(video) - ) - ) - ) From 516e0a13d59c5c3f72d9a22616bbf5121cd8a2b4 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 15:06:18 +0200 Subject: [PATCH 12/16] Simplify None checks for file uploads --- pyrogram/client/client.py | 3 +++ pyrogram/client/methods/messages/edit_message_media.py | 8 ++++---- pyrogram/client/methods/messages/send_animation.py | 4 ++-- pyrogram/client/methods/messages/send_audio.py | 4 ++-- pyrogram/client/methods/messages/send_document.py | 4 ++-- pyrogram/client/methods/messages/send_media_group.py | 2 +- pyrogram/client/methods/messages/send_video.py | 4 ++-- pyrogram/client/methods/messages/send_video_note.py | 4 ++-- 8 files changed, 18 insertions(+), 15 deletions(-) diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py index 79275103..d2add202 100644 --- a/pyrogram/client/client.py +++ b/pyrogram/client/client.py @@ -1783,6 +1783,9 @@ class Client(Methods, BaseClient): Raises: RPCError: In case of a Telegram RPC error. """ + if path is None: + return None + part_size = 512 * 1024 if isinstance(path, str): diff --git a/pyrogram/client/methods/messages/edit_message_media.py b/pyrogram/client/methods/messages/edit_message_media.py index 3ab90744..6950c255 100644 --- a/pyrogram/client/methods/messages/edit_message_media.py +++ b/pyrogram/client/methods/messages/edit_message_media.py @@ -109,7 +109,7 @@ class EditMessageMedia(BaseClient): peer=self.resolve_peer(chat_id), media=types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(media.media) or "video/mp4", - thumb=None if media.thumb is None else self.save_file(media.thumb), + thumb=self.save_file(media.thumb), file=self.save_file(media.media), attributes=[ types.DocumentAttributeVideo( @@ -146,7 +146,7 @@ class EditMessageMedia(BaseClient): peer=self.resolve_peer(chat_id), media=types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(media.media) or "audio/mpeg", - thumb=None if media.thumb is None else self.save_file(media.thumb), + thumb=self.save_file(media.thumb), file=self.save_file(media.media), attributes=[ types.DocumentAttributeAudio( @@ -182,7 +182,7 @@ class EditMessageMedia(BaseClient): peer=self.resolve_peer(chat_id), media=types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(media.media) or "video/mp4", - thumb=None if media.thumb is None else self.save_file(media.thumb), + thumb=self.save_file(media.thumb), file=self.save_file(media.media), attributes=[ types.DocumentAttributeVideo( @@ -220,7 +220,7 @@ class EditMessageMedia(BaseClient): peer=self.resolve_peer(chat_id), media=types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(media.media) or "application/zip", - thumb=None if media.thumb is None else self.save_file(media.thumb), + thumb=self.save_file(media.thumb), file=self.save_file(media.media), attributes=[ types.DocumentAttributeFilename( diff --git a/pyrogram/client/methods/messages/send_animation.py b/pyrogram/client/methods/messages/send_animation.py index a38856a0..e8d9285f 100644 --- a/pyrogram/client/methods/messages/send_animation.py +++ b/pyrogram/client/methods/messages/send_animation.py @@ -167,7 +167,7 @@ class SendAnimation(BaseClient): try: if isinstance(animation, str): if os.path.isfile(animation): - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(animation, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(animation) or "video/mp4", @@ -191,7 +191,7 @@ class SendAnimation(BaseClient): else: media = utils.get_input_media_from_file_id(animation, file_ref, 10) else: - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(animation, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(animation.name) or "video/mp4", diff --git a/pyrogram/client/methods/messages/send_audio.py b/pyrogram/client/methods/messages/send_audio.py index 08c03d07..8dfabe8c 100644 --- a/pyrogram/client/methods/messages/send_audio.py +++ b/pyrogram/client/methods/messages/send_audio.py @@ -167,7 +167,7 @@ class SendAudio(BaseClient): try: if isinstance(audio, str): if os.path.isfile(audio): - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(audio, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(audio) or "audio/mpeg", @@ -189,7 +189,7 @@ class SendAudio(BaseClient): else: media = utils.get_input_media_from_file_id(audio, file_ref, 9) else: - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(audio, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(audio.name) or "audio/mpeg", diff --git a/pyrogram/client/methods/messages/send_document.py b/pyrogram/client/methods/messages/send_document.py index 8faf8374..8ca7fc4e 100644 --- a/pyrogram/client/methods/messages/send_document.py +++ b/pyrogram/client/methods/messages/send_document.py @@ -147,7 +147,7 @@ class SendDocument(BaseClient): try: if isinstance(document, str): if os.path.isfile(document): - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(document, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(document) or "application/zip", @@ -165,7 +165,7 @@ class SendDocument(BaseClient): else: media = utils.get_input_media_from_file_id(document, file_ref, 5) else: - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(document, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(document.name) or "application/zip", diff --git a/pyrogram/client/methods/messages/send_media_group.py b/pyrogram/client/methods/messages/send_media_group.py index 9ca4473b..2a2cca74 100644 --- a/pyrogram/client/methods/messages/send_media_group.py +++ b/pyrogram/client/methods/messages/send_media_group.py @@ -119,7 +119,7 @@ class SendMediaGroup(BaseClient): peer=self.resolve_peer(chat_id), media=types.InputMediaUploadedDocument( file=self.save_file(i.media), - thumb=None if i.thumb is None else self.save_file(i.thumb), + thumb=self.save_file(i.thumb), mime_type=self.guess_mime_type(i.media) or "video/mp4", attributes=[ types.DocumentAttributeVideo( diff --git a/pyrogram/client/methods/messages/send_video.py b/pyrogram/client/methods/messages/send_video.py index 1f46252f..40691771 100644 --- a/pyrogram/client/methods/messages/send_video.py +++ b/pyrogram/client/methods/messages/send_video.py @@ -164,7 +164,7 @@ class SendVideo(BaseClient): try: if isinstance(video, str): if os.path.isfile(video): - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(video, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(video) or "video/mp4", @@ -187,7 +187,7 @@ class SendVideo(BaseClient): else: media = utils.get_input_media_from_file_id(video, file_ref, 4) else: - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(video, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(video.name) or "video/mp4", diff --git a/pyrogram/client/methods/messages/send_video_note.py b/pyrogram/client/methods/messages/send_video_note.py index 829f1459..d3b32834 100644 --- a/pyrogram/client/methods/messages/send_video_note.py +++ b/pyrogram/client/methods/messages/send_video_note.py @@ -131,7 +131,7 @@ class SendVideoNote(BaseClient): try: if isinstance(video_note, str): if os.path.isfile(video_note): - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(video_note, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(video_note) or "video/mp4", @@ -149,7 +149,7 @@ class SendVideoNote(BaseClient): else: media = utils.get_input_media_from_file_id(video_note, file_ref, 13) else: - thumb = None if thumb is None else self.save_file(thumb) + thumb = self.save_file(thumb) file = self.save_file(video_note, progress=progress, progress_args=progress_args) media = types.InputMediaUploadedDocument( mime_type=self.guess_mime_type(video_note.name) or "video/mp4", From b16c5d5fa3241c8f4ba7222ebfe361dcd3b0e92d Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Mon, 27 Jul 2020 15:12:24 +0200 Subject: [PATCH 13/16] Update Pyrogram's sticker file id --- examples/hello_world.py | 2 +- pyrogram/client/methods/messages/download_media.py | 2 +- pyrogram/client/methods/messages/send_cached_media.py | 2 +- pyrogram/client/methods/messages/send_sticker.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/hello_world.py b/examples/hello_world.py index 19d0ffe7..5764e979 100644 --- a/examples/hello_world.py +++ b/examples/hello_world.py @@ -13,4 +13,4 @@ with app: app.send_location("me", 51.500729, -0.124583) # Send a sticker - app.send_sticker("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI") + app.send_sticker("me", "CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") diff --git a/pyrogram/client/methods/messages/download_media.py b/pyrogram/client/methods/messages/download_media.py index 22054397..01397135 100644 --- a/pyrogram/client/methods/messages/download_media.py +++ b/pyrogram/client/methods/messages/download_media.py @@ -98,7 +98,7 @@ class DownloadMedia(BaseClient): app.download_media(message) # Download from file id - app.download_media("CAADBAADyg4AAvLQYAEYD4F7vcZ43AI") + app.download_media("CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") # Keep track of the progress while downloading def progress(current, total): diff --git a/pyrogram/client/methods/messages/send_cached_media.py b/pyrogram/client/methods/messages/send_cached_media.py index 463e9bef..1ee139f5 100644 --- a/pyrogram/client/methods/messages/send_cached_media.py +++ b/pyrogram/client/methods/messages/send_cached_media.py @@ -91,7 +91,7 @@ class SendCachedMedia(BaseClient): Example: .. code-block:: python - app.send_cached_media("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI") + app.send_cached_media("me", "CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") """ r = self.send( diff --git a/pyrogram/client/methods/messages/send_sticker.py b/pyrogram/client/methods/messages/send_sticker.py index 0de47d64..529a4f8d 100644 --- a/pyrogram/client/methods/messages/send_sticker.py +++ b/pyrogram/client/methods/messages/send_sticker.py @@ -110,7 +110,7 @@ class SendSticker(BaseClient): app.send_sticker("me", "sticker.webp") # Send sticker using file_id - app.send_sticker("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI") + app.send_sticker("me", "CAADBAADzg4AAvLQYAEz_x2EOgdRwBYE") """ file = None From d3a34f1084ee561a252b6bb8298e51f04a468f44 Mon Sep 17 00:00:00 2001 From: Said Date: Mon, 27 Jul 2020 16:21:42 +0300 Subject: [PATCH 14/16] Add file_name parameter in edit_message_media method (#440) * ability to change file_name in editmessagemedia method * ability to change file_name in editmessagemedia method * ability to change file_name in editmessagemedia method * Update edit_message_media.py * Update input_media_document.py Co-authored-by: GadzhievSA Co-authored-by: Dan <14043624+delivrance@users.noreply.github.com> --- .../client/methods/messages/edit_message_media.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/pyrogram/client/methods/messages/edit_message_media.py b/pyrogram/client/methods/messages/edit_message_media.py index 6950c255..9e91e945 100644 --- a/pyrogram/client/methods/messages/edit_message_media.py +++ b/pyrogram/client/methods/messages/edit_message_media.py @@ -36,7 +36,8 @@ class EditMessageMedia(BaseClient): chat_id: Union[int, str], message_id: int, media: InputMedia, - reply_markup: "pyrogram.InlineKeyboardMarkup" = None + reply_markup: "pyrogram.InlineKeyboardMarkup" = None, + file_name: str = None ) -> "pyrogram.Message": """Edit animation, audio, document, photo or video messages. @@ -58,6 +59,10 @@ class EditMessageMedia(BaseClient): reply_markup (:obj:`InlineKeyboardMarkup`, *optional*): An InlineKeyboardMarkup object. + file_name (``str``, *optional*): + File name of the media to be sent. Not applicable to photos. + Defaults to file's path basename. + Returns: :obj:`Message`: On success, the edited message is returned. @@ -119,7 +124,7 @@ class EditMessageMedia(BaseClient): h=media.height ), types.DocumentAttributeFilename( - file_name=os.path.basename(media.media) + file_name=file_name or os.path.basename(media.media) ) ] ) @@ -155,7 +160,7 @@ class EditMessageMedia(BaseClient): title=media.title ), types.DocumentAttributeFilename( - file_name=os.path.basename(media.media) + file_name=file_name or os.path.basename(media.media) ) ] ) @@ -192,7 +197,7 @@ class EditMessageMedia(BaseClient): h=media.height ), types.DocumentAttributeFilename( - file_name=os.path.basename(media.media) + file_name=file_name or os.path.basename(media.media) ), types.DocumentAttributeAnimated() ] @@ -224,7 +229,7 @@ class EditMessageMedia(BaseClient): file=self.save_file(media.media), attributes=[ types.DocumentAttributeFilename( - file_name=os.path.basename(media.media) + file_name=file_name or os.path.basename(media.media) ) ] ) From c5b7a365af6686479c682ed024c36d7dae7bcc6f Mon Sep 17 00:00:00 2001 From: ColinShark Date: Mon, 27 Jul 2020 15:30:49 +0200 Subject: [PATCH 15/16] Add message.link attribute/property (#442) * Add message.link attribute Adds the functionality to access the message link. Either as `t.me/c/` or `t.me/username` format. * Change message.link logic Property now has a returned type, list is a tuple and we use `utils.get_channel_id` to not rely on str.replace * Update message.py - Prepend https:// like official clients do - Use .format() Co-authored-by: Dan <14043624+delivrance@users.noreply.github.com> --- pyrogram/client/types/messages_and_media/message.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pyrogram/client/types/messages_and_media/message.py b/pyrogram/client/types/messages_and_media/message.py index 47606715..f2f6abab 100644 --- a/pyrogram/client/types/messages_and_media/message.py +++ b/pyrogram/client/types/messages_and_media/message.py @@ -251,6 +251,9 @@ class Message(Object, Update): Messages sent from yourself to other chats are outgoing (*outgoing* is True). An exception is made for your own personal chat; messages sent there will be incoming. + link (``str``): + A link to the message, only for groups and channels. + matches (List of regex Matches, *optional*): A list containing all `Match Objects `_ that match the text of this message. Only applicable when using :obj:`Filters.regex `. @@ -670,6 +673,13 @@ class Message(Object, Update): return parsed_message + @property + def link(self) -> str: + if self.chat.type in ("group", "supergroup", "channel") and self.chat.username: + return "https://t.me/{}/{}".format(self.chat.username, self.message_id) + else: + return "https://t.me/c/{}/{}".format(utils.get_channel_id(self.chat.id), self.message_id) + def reply_text( self, text: str, From 0edf08245b800fdb8529c1286a1754067a9cf728 Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Tue, 28 Jul 2020 17:38:58 +0200 Subject: [PATCH 16/16] Add mention to football dice --- pyrogram/client/methods/messages/send_dice.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyrogram/client/methods/messages/send_dice.py b/pyrogram/client/methods/messages/send_dice.py index 4ed9b926..b426f939 100644 --- a/pyrogram/client/methods/messages/send_dice.py +++ b/pyrogram/client/methods/messages/send_dice.py @@ -47,7 +47,7 @@ class SendDice(BaseClient): For a contact that exists in your Telegram address book you can use his phone number (str). emoji (``str``, *optional*): - Emoji on which the dice throw animation is based. Currently, must be one of "🎲", "🎯" or "🏀". + Emoji on which the dice throw animation is based. Currently, must be one of "🎲", "🎯", "🏀" or "⚽️". Defaults to "🎲". disable_notification (``bool``, *optional*):