Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions readthedocs/custom_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ def make_link_node(rawtext, app, name, options):
base += '/'

set_classes(options)
node = nodes.reference(rawtext, utils.unescape(name),
refuri='{}?q={}'.format(base, name),
**options)
return node
return nodes.reference(
rawtext, utils.unescape(name), refuri=f'{base}?q={name}', **options
)
Comment on lines -25 to +27
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_link_node refactored with the following changes:



# noinspection PyUnusedLocal
Expand Down
10 changes: 6 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,12 @@ def main(argv):
return

remove_dirs = ['__pycache__', 'build', 'dist', 'Telethon.egg-info']
for root, _dirs, _files in os.walk(LIBRARY_DIR, topdown=False):
# setuptools is including __pycache__ for some reason (#1605)
if root.endswith('/__pycache__'):
remove_dirs.append(root)
remove_dirs.extend(
root
for root, _dirs, _files in os.walk(LIBRARY_DIR, topdown=False)
if root.endswith('/__pycache__')
)

Comment on lines -169 to +174
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

This removes the following comments ( why? ):

# setuptools is including __pycache__ for some reason (#1605)

for x in remove_dirs:
shutil.rmtree(x, ignore_errors=True)

Expand Down
2 changes: 1 addition & 1 deletion telethon/client/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def __getattr__(self, name):
return value

def __setattr__(self, name, value):
if name.startswith('_{}__'.format(type(self).__name__.lstrip('_'))):
if name.startswith(f"_{type(self).__name__.lstrip('_')}__"):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _TakeoutClient.__setattr__ refactored with the following changes:

# This is our own name-mangled attribute, keep calm.
return super().__setattr__(name, value)
return setattr(self.__client, name, value)
Expand Down
4 changes: 2 additions & 2 deletions telethon/client/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,10 @@ async def _start(
attempts += 1
else:
raise RuntimeError(
'{} consecutive sign-in attempts failed. Aborting'
.format(max_attempts)
f'{max_attempts} consecutive sign-in attempts failed. Aborting'
)

Comment on lines 225 to 227
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AuthMethods._start refactored with the following changes:


if two_step_detected:
if not password:
raise ValueError(
Expand Down
10 changes: 5 additions & 5 deletions telethon/client/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,9 @@ async def _init(
if not utils.is_list_like(admins):
admins = (admins,)

for admin in admins:
admin_list.append(await self.client.get_input_entity(admin))
admin_list.extend(
await self.client.get_input_entity(admin) for admin in admins
)
Comment on lines -280 to +282
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _AdminLogIter._init refactored with the following changes:


self.request = functions.channels.GetAdminLogRequest(
self.entity, q=search or '', min_id=min_id, max_id=max_id,
Expand Down Expand Up @@ -825,14 +826,13 @@ def action(
try:
action = _ChatAction._str_mapping[action.lower()]
except KeyError:
raise ValueError(
'No such action "{}"'.format(action)) from None
raise ValueError(f'No such action "{action}"') from None
elif not isinstance(action, types.TLObject) or action.SUBCLASS_OF_ID != 0x20b2cc21:
# 0x20b2cc21 = crc32(b'SendMessageAction')
if isinstance(action, type):
raise ValueError('You must pass an instance, not the class')
else:
raise ValueError('Cannot use {} as action'.format(action))
raise ValueError(f'Cannot use {action} as action')
Comment on lines -828 to +835
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChatMethods.action refactored with the following changes:


if isinstance(action, types.SendMessageCancelAction):
# ``SetTypingRequest.resolve`` will get input peer of ``entity``.
Expand Down
27 changes: 9 additions & 18 deletions telethon/client/dialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,8 @@ async def _init(self, entities, **kwargs):
items = r.updates
else:
peers = []
for entity in entities:
peers.append(types.InputDialogPeer(
await self.client.get_input_entity(entity)))

peers.extend(types.InputDialogPeer(
await self.client.get_input_entity(entity)) for entity in entities)
Comment on lines -119 to +120
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _DraftsIter._init refactored with the following changes:

r = await self.client(functions.messages.GetPeerDialogsRequest(peers))
items = r.dialogs

Expand Down Expand Up @@ -310,10 +308,7 @@ async def get_drafts(
print(drafts.text)
"""
items = await self.iter_drafts(entity).collect()
if not entity or utils.is_list_like(entity):
return items
else:
return items[0]
return items if not entity or utils.is_list_like(entity) else items[0]
Comment on lines -313 to +311
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DialogMethods.get_drafts refactored with the following changes:


async def edit_folder(
self: 'TelegramClient',
Expand Down Expand Up @@ -380,11 +375,11 @@ async def edit_folder(
folder_id=unpack
))

if not utils.is_list_like(entity):
entities = [await self.get_input_entity(entity)]
else:
entities = await asyncio.gather(
*(self.get_input_entity(x) for x in entity))
entities = (
await asyncio.gather(*(self.get_input_entity(x) for x in entity))
if utils.is_list_like(entity)
else [await self.get_input_entity(entity)]
)
Comment on lines -383 to +382
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DialogMethods.edit_folder refactored with the following changes:


if folder is None:
raise ValueError('You must specify a folder')
Expand Down Expand Up @@ -443,11 +438,7 @@ async def delete_dialog(
"""
# If we have enough information (`Dialog.delete` gives it to us),
# then we know we don't have to kick ourselves in deactivated chats.
if isinstance(entity, types.Chat):
deactivated = entity.deactivated
else:
deactivated = False

deactivated = entity.deactivated if isinstance(entity, types.Chat) else False
Comment on lines -446 to +441
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DialogMethods.delete_dialog refactored with the following changes:

entity = await self.get_input_entity(entity)
ty = helpers._entity_type(entity)
if ty == helpers._EntityType.CHANNEL:
Expand Down
71 changes: 31 additions & 40 deletions telethon/client/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,33 +256,30 @@ async def download_profile_photo(
if not hasattr(entity, 'photo'):
# Special case: may be a ChatFull with photo:Photo
# This is different from a normal UserProfilePhoto and Chat
if not hasattr(entity, 'chat_photo'):
return None

return await self._download_photo(
entity.chat_photo, file, date=None,
thumb=thumb, progress_callback=None
)

for attr in ('username', 'first_name', 'title'):
possible_names.append(getattr(entity, attr, None))
) if hasattr(entity, 'chat_photo') else None
possible_names.extend(
getattr(entity, attr, None)
for attr in ('username', 'first_name', 'title')
)

photo = entity.photo

if isinstance(photo, (types.UserProfilePhoto, types.ChatPhoto)):
dc_id = photo.dc_id
loc = types.InputPeerPhotoFileLocation(
peer=await self.get_input_entity(entity),
photo_id=photo.photo_id,
big=download_big
)
else:
if not isinstance(photo, (types.UserProfilePhoto, types.ChatPhoto)):
# It doesn't make any sense to check if `photo` can be used
# as input location, because then this method would be able
# to "download the profile photo of a message", i.e. its
# media which should be done with `download_media` instead.
return None

dc_id = photo.dc_id
loc = types.InputPeerPhotoFileLocation(
peer=await self.get_input_entity(entity),
photo_id=photo.photo_id,
big=download_big
)
Comment on lines -259 to +282
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DownloadMethods.download_profile_photo refactored with the following changes:

file = self._get_proper_filename(
file, 'profile_photo', '.jpg',
possible_names=possible_names
Expand All @@ -296,16 +293,15 @@ async def download_profile_photo(
# The fix seems to be using the full channel chat photo.
ie = await self.get_input_entity(entity)
ty = helpers._entity_type(ie)
if ty == helpers._EntityType.CHANNEL:
full = await self(functions.channels.GetFullChannelRequest(ie))
return await self._download_photo(
full.full_chat.chat_photo, file,
date=None, progress_callback=None,
thumb=thumb
)
else:
if ty != helpers._EntityType.CHANNEL:
# Until there's a report for chats, no need to.
return None
full = await self(functions.channels.GetFullChannelRequest(ie))
return await self._download_photo(
full.full_chat.chat_photo, file,
date=None, progress_callback=None,
thumb=thumb
)

async def download_media(
self: 'TelegramClient',
Expand Down Expand Up @@ -398,14 +394,15 @@ def callback(current, total):
if isinstance(media, str):
media = utils.resolve_bot_file_id(media)

if isinstance(media, types.MessageService):
if isinstance(message.action,
types.MessageActionChatEditPhoto):
media = media.photo

if isinstance(media, types.MessageMediaWebPage):
if isinstance(media.webpage, types.WebPage):
media = media.webpage.document or media.webpage.photo
if isinstance(media, types.MessageService) and isinstance(
message.action, types.MessageActionChatEditPhoto
):
media = media.photo

if isinstance(media, types.MessageMediaWebPage) and isinstance(
media.webpage, types.WebPage
):
media = media.webpage.document or media.webpage.photo
Comment on lines -401 to +405
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DownloadMethods.download_media refactored with the following changes:


if isinstance(media, (types.MessageMediaPhoto, types.Photo)):
return await self._download_photo(
Expand Down Expand Up @@ -511,11 +508,7 @@ async def _download_file(
iv: bytes = None,
msg_data: tuple = None) -> typing.Optional[bytes]:
if not part_size_kb:
if not file_size:
part_size_kb = 64 # Reasonable default
else:
part_size_kb = utils.get_appropriated_part_size(file_size)

part_size_kb = utils.get_appropriated_part_size(file_size) if file_size else 64
Comment on lines -514 to +511
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DownloadMethods._download_file refactored with the following changes:

This removes the following comments ( why? ):

# Reasonable default

part_size = int(part_size_kb * 1024)
if part_size % MIN_CHUNK_SIZE != 0:
raise ValueError(
Expand Down Expand Up @@ -846,9 +839,7 @@ def _get_kind_and_names(attributes):
elif isinstance(attr, types.DocumentAttributeAudio):
kind = 'audio'
if attr.performer and attr.title:
possible_names.append('{} - {}'.format(
attr.performer, attr.title
))
possible_names.append(f'{attr.performer} - {attr.title}')
Comment on lines -849 to +842
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DownloadMethods._get_kind_and_names refactored with the following changes:

elif attr.performer:
possible_names.append(attr.performer)
elif attr.title:
Expand Down Expand Up @@ -1035,7 +1026,7 @@ def _get_proper_filename(file, kind, extension,

i = 1
while True:
result = os.path.join(directory, '{} ({}){}'.format(name, i, ext))
result = os.path.join(directory, f'{name} ({i}){ext}')
Comment on lines -1038 to +1029
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DownloadMethods._get_proper_filename refactored with the following changes:

if not os.path.isfile(result):
return result
i += 1
Expand Down
5 changes: 2 additions & 3 deletions telethon/client/messageparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,11 @@ async def _parse_message_text(self: 'TelegramClient', message, parse_mode):
message, msg_entities = parse_mode.parse(message)
if original_message and not message and not msg_entities:
raise ValueError("Failed to parse message")

for i in reversed(range(len(msg_entities))):
e = msg_entities[i]
if isinstance(e, types.MessageEntityTextUrl):
m = re.match(r'^@|\+|tg://user\?id=(\d+)', e.url)
if m:
if m := re.match(r'^@|\+|tg://user\?id=(\d+)', e.url):
Comment on lines -90 to +94
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MessageParseMethods._parse_message_text refactored with the following changes:

user = int(m.group(1)) if m.group(1) else e.url
is_mention = await self._replace_with_mention(msg_entities, i, user)
if not is_mention:
Expand Down
Loading