Skip to content

Commit 1fb0164

Browse files
sourcery-ai[bot]LonamiNew-dev0
authored
Pull (Sourcery refactored) (#5)
* Slightly improve documentation * Deprecate force_sms and sign_up On the 10th of February, Telegram sent the following message to those with an application registered on https://my.telegram.org. -- Telegram API Update. Hello [REDACTED]. Thank you for contributing to the open Telegram ecosystem by developing your app, [REDACTED]. Please note that due to recent updates to Telegram's handling of SMS and the integration of new SMS providers like Firebase, we are changing the way login codes are handled in third-party apps based on the Telegram API. Starting on 18.02.2023, users logging into third-party apps will only be able to receive login codes via Telegram. It will no longer be possible to request an SMS to log into your app - just like when logging into Telegram's own desktop and web clients. Exactly like with the Telegram Desktop and Web apps, if a user doesn't have a Telegram account yet, they will need to create one first using an official mobile Telegram app. We kindly ask you to update your app's login and signup interfaces to reflect these changes before they go live on 18.02.2023 at 13:00 UTC. This change will not significantly affect users since, according to our research, the vast majority of third-party app users also use official Telegram apps. In the coming months, we expect to offer new tools for third-party developers that will help streamline the login process. * Fix ChatAction for groups with hidden members * Move working with messages to the wiki * 'Refactored by Sourcery' --------- Co-authored-by: Lonami Exo <totufals@hotmail.com> Co-authored-by: Devesh Pal <newdev0@outlook.com>
1 parent 5cbf764 commit 1fb0164

10 files changed

Lines changed: 38 additions & 227 deletions

File tree

readthedocs/examples/working-with-messages.rst

Lines changed: 4 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -2,125 +2,12 @@
22
Working with messages
33
=====================
44

5-
65
.. note::
76

87
These examples assume you have read :ref:`full-api`.
98

10-
.. contents::
11-
12-
13-
Sending stickers
14-
================
15-
16-
Stickers are nothing else than ``files``, and when you successfully retrieve
17-
the stickers for a certain sticker set, all you will have are ``handles`` to
18-
these files. Remember, the files Telegram holds on their servers can be
19-
referenced through this pair of ID/hash (unique per user), and you need to
20-
use this handle when sending a "document" message. This working example will
21-
send yourself the very first sticker you have:
22-
23-
.. code-block:: python
24-
25-
# Get all the sticker sets this user has
26-
from telethon.tl.functions.messages import GetAllStickersRequest
27-
sticker_sets = await client(GetAllStickersRequest(0))
28-
29-
# Choose a sticker set
30-
from telethon.tl.functions.messages import GetStickerSetRequest
31-
from telethon.tl.types import InputStickerSetID
32-
sticker_set = sticker_sets.sets[0]
33-
34-
# Get the stickers for this sticker set
35-
stickers = await client(GetStickerSetRequest(
36-
stickerset=InputStickerSetID(
37-
id=sticker_set.id, access_hash=sticker_set.access_hash
38-
),
39-
hash=0
40-
))
41-
42-
# Stickers are nothing more than files, so send that
43-
await client.send_file('me', stickers.documents[0])
44-
45-
46-
Sending reactions
47-
=================
48-
49-
It works very similar to replying to a message. You need to specify the chat,
50-
message ID you wish to react to, and reaction, using :tl:`SendReaction`:
51-
52-
.. code-block:: python
53-
54-
from telethon.tl.functions.messages import SendReactionRequest
55-
56-
await client(SendReactionRequest(
57-
peer=chat,
58-
msg_id=42,
59-
reaction='❤️'
60-
))
61-
62-
Note that you cannot use strings like ``:heart:`` for the reaction. You must
63-
use the desired emoji directly. You can most easily achieve this by
64-
copy-pasting the emoji from an official application such as Telegram Desktop.
65-
66-
If for some reason you cannot embed emoji directly into the code, you can also
67-
use its unicode escape (which you can find using websites like
68-
`unicode-table.com`_), or install a different package, like `emoji`_:
69-
70-
.. code-block:: python
71-
72-
# All of these work exactly the same (you only need one):
73-
import emoji
74-
reaction = emoji.emojize(':red_heart:')
75-
reaction = '❤️'
76-
reaction = '\u2764'
77-
78-
from telethon.tl.functions.messages import SendReactionRequest
79-
await client(SendReactionRequest(
80-
peer=chat,
81-
msg_id=42,
82-
reaction=reaction
83-
))
84-
85-
Please make sure to check the help pages of the respective websites you use
86-
if you need a more in-depth explanation on how they work. Telethon only needs
87-
you to provide the emoji in some form. Some packages or websites can make this
88-
easier.
89-
90-
91-
Sending spoilers (hidden text)
92-
==============================
93-
94-
The current markdown and HTML parsers do not offer a way to send spoilers yet.
95-
You need to use :tl:`MessageEntitySpoiler` so that parts of the message text
96-
are shown under a spoiler.
97-
98-
The simplest way to do this is to `modify the builtin parsers`_ to support
99-
sending these new message entities with the features they already provide.
100-
101-
102-
Sending custom emoji
103-
====================
104-
105-
The current markdown and HTML parsers do not offer a way to send custom emoji
106-
yet. You need to use :tl:`MessageEntityCustomEmoji` so that parts of the
107-
message text with emoji are replaced with a custom one instead.
108-
109-
The simplest way to do this is to `modify the builtin parsers`_ to support
110-
sending these new message entities with the features they already provide.
111-
112-
:tl:`MessageEntityCustomEmoji` must wrap an emoji in order to work (you can't
113-
put it around arbitrary ``"text"``, it won't work), so be sure to keep this in
114-
mind when using it.
115-
116-
To find the ``document_id`` for the custom emoji, the simplest way is to send
117-
a message with an official client containing the custom emoji you want, and
118-
then print the ``message.entities`` to find the ``document_id``.
119-
120-
If you prefer, you can also use :tl:`GetFeaturedEmojiStickers` to find about
121-
the ``document_id`` of featured custom emoji.
122-
9+
This section has been `moved to the wiki`_, where it can be easily edited as new
10+
features arrive and the API changes. Please refer to the linked page to learn how
11+
to send spoilers, custom emoji, stickers, react to messages, and more things.
12312

124-
.. _unicode-table.com: https://unicode-table.com/en/emoji/
125-
.. _emoji: https://pypi.org/project/emoji/
126-
.. _modify the builtin parsers: https://github.com/LonamiWebs/Telethon/wiki/Sending-spoilers-and-custom-emoji
13+
.. _moved to the wiki: https://github.com/LonamiWebs/Telethon/wiki/Sending-more-than-just-messages

readthedocs/quick-references/client-reference.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ Auth
3232
send_code_request
3333
sign_in
3434
qr_login
35-
sign_up
3635
log_out
3736
edit_2fa
3837

readthedocs/quick-references/faq.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,7 @@ However, you may also be part of a limited country, such as Iran or Russia.
6767
In that case, we have bad news for you. Telegram is much more likely to ban
6868
these numbers, as they are often used to spam other accounts, likely through
6969
the use of libraries like this one. The best advice we can give you is to not
70-
abuse the API, like calling many requests really quickly, and to sign up with
71-
these phones through an official application.
70+
abuse the API, like calling many requests really quickly.
7271

7372
We have also had reports from Kazakhstan and China, where connecting
7473
would fail. To solve these connection problems, you should use a proxy.

telethon/client/auth.py

Lines changed: 11 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,6 @@ def start(
3434
By default, this method will be interactive (asking for
3535
user input if needed), and will handle 2FA if enabled too.
3636
37-
If the phone doesn't belong to an existing account (and will hence
38-
`sign_up` for a new one), **you are agreeing to Telegram's
39-
Terms of Service. This is required and your account
40-
will be banned otherwise.** See https://telegram.org/tos
41-
and https://core.telegram.org/api/terms.
42-
4337
If the event loop is already running, this method returns a
4438
coroutine that you should await on your own code; otherwise
4539
the loop is ran until said coroutine completes.
@@ -188,7 +182,6 @@ async def _start(
188182
two_step_detected = False
189183

190184
await self.send_code_request(phone, force_sms=force_sms)
191-
sign_up = False # assume login
192185
while attempts < max_attempts:
193186
try:
194187
value = code_callback()
@@ -201,19 +194,12 @@ async def _start(
201194
if not value:
202195
raise errors.PhoneCodeEmptyError(request=None)
203196

204-
if sign_up:
205-
me = await self.sign_up(value, first_name, last_name)
206-
else:
207-
# Raises SessionPasswordNeededError if 2FA enabled
208-
me = await self.sign_in(phone, code=value)
197+
# Raises SessionPasswordNeededError if 2FA enabled
198+
me = await self.sign_in(phone, code=value)
209199
break
210200
except errors.SessionPasswordNeededError:
211201
two_step_detected = True
212202
break
213-
except errors.PhoneNumberOccupiedError:
214-
sign_up = False
215-
except errors.PhoneNumberUnoccupiedError:
216-
sign_up = True
217203
except (errors.PhoneCodeEmptyError,
218204
errors.PhoneCodeExpiredError,
219205
errors.PhoneCodeHashEmptyError,
@@ -381,91 +367,10 @@ async def sign_up(
381367
phone: str = None,
382368
phone_code_hash: str = None) -> 'types.User':
383369
"""
384-
Signs up to Telegram as a new user account.
385-
386-
Use this if you don't have an account yet.
387-
388-
You must call `send_code_request` first.
389-
390-
**By using this method you're agreeing to Telegram's
391-
Terms of Service. This is required and your account
392-
will be banned otherwise.** See https://telegram.org/tos
393-
and https://core.telegram.org/api/terms.
394-
395-
Arguments
396-
code (`str` | `int`):
397-
The code sent by Telegram
398-
399-
first_name (`str`):
400-
The first name to be used by the new account.
401-
402-
last_name (`str`, optional)
403-
Optional last name.
404-
405-
phone (`str` | `int`, optional):
406-
The phone to sign up. This will be the last phone used by
407-
default (you normally don't need to set this).
408-
409-
phone_code_hash (`str`, optional):
410-
The hash returned by `send_code_request`. This can be left as
411-
`None` to use the last hash known for the phone to be used.
412-
413-
Returns
414-
The new created :tl:`User`.
415-
416-
Example
417-
.. code-block:: python
418-
419-
phone = '+34 123 123 123'
420-
await client.send_code_request(phone)
421-
422-
code = input('enter code: ')
423-
await client.sign_up(code, first_name='Anna', last_name='Banana')
370+
This method can no longer be used, and will immediately raise a ``ValueError``.
371+
See `issue #4050 <https://github.com/LonamiWebs/Telethon/issues/4050>`_ for context.
424372
"""
425-
me = await self.get_me()
426-
if me:
427-
return me
428-
429-
# To prevent abuse, one has to try to sign in before signing up. This
430-
# is the current way in which Telegram validates the code to sign up.
431-
#
432-
# `sign_in` will set `_tos`, so if it's set we don't need to call it
433-
# because the user already tried to sign in.
434-
#
435-
# We're emulating pre-layer 104 behaviour so except the right error:
436-
if not self._tos:
437-
try:
438-
return await self.sign_in(
439-
phone=phone,
440-
code=code,
441-
phone_code_hash=phone_code_hash,
442-
)
443-
except errors.PhoneNumberUnoccupiedError:
444-
pass # code is correct and was used, now need to sign in
445-
446-
if self._tos and self._tos.text:
447-
if self.parse_mode:
448-
t = self.parse_mode.unparse(self._tos.text, self._tos.entities)
449-
else:
450-
t = self._tos.text
451-
sys.stderr.write(f"{t}\n")
452-
sys.stderr.flush()
453-
454-
phone, phone_code_hash = \
455-
self._parse_phone_and_hash(phone, phone_code_hash)
456-
457-
result = await self(functions.auth.SignUpRequest(
458-
phone_number=phone,
459-
phone_code_hash=phone_code_hash,
460-
first_name=first_name,
461-
last_name=last_name
462-
))
463-
464-
if self._tos:
465-
await self(
466-
functions.help.AcceptTermsOfServiceRequest(self._tos.id))
467-
468-
return await self._on_login(result.user)
373+
raise ValueError('Third-party applications cannot sign up for Telegram. See https://github.com/LonamiWebs/Telethon/issues/4050 for details')
469374

470375
async def _on_login(self, user):
471376
"""
@@ -496,7 +401,8 @@ async def send_code_request(
496401
The phone to which the code will be sent.
497402
498403
force_sms (`bool`, optional):
499-
Whether to force sending as SMS.
404+
Whether to force sending as SMS. This has been deprecated.
405+
See `issue #4050 <https://github.com/LonamiWebs/Telethon/issues/4050>`_ for context.
500406
501407
Returns
502408
An instance of :tl:`SentCode`.
@@ -508,6 +414,10 @@ async def send_code_request(
508414
sent = await client.send_code_request(phone)
509415
print(sent)
510416
"""
417+
if force_sms:
418+
warnings.warn('force_sms has been deprecated and no longer works')
419+
force_sms = False
420+
511421
result = None
512422
phone = utils.parse_phone(phone) or self._phone
513423
phone_hash = self._phone_code_hash.get(phone)

telethon/client/downloads.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,8 @@ async def download_profile_photo(
223223
The output file path, directory, or stream-like object.
224224
If the path exists and is a file, it will be overwritten.
225225
If file is the type `bytes`, it will be downloaded in-memory
226-
as a bytestring (e.g. ``file=bytes``).
226+
and returned as a bytestring (i.e. ``file=bytes``, without
227+
parentheses or quotes).
227228
228229
download_big (`bool`, optional):
229230
Whether to use the big version of the available photos.
@@ -335,7 +336,8 @@ async def download_media(
335336
The output file path, directory, or stream-like object.
336337
If the path exists and is a file, it will be overwritten.
337338
If file is the type `bytes`, it will be downloaded in-memory
338-
as a bytestring (e.g. ``file=bytes``).
339+
and returned as a bytestring (i.e. ``file=bytes``, without
340+
parentheses or quotes).
339341
340342
progress_callback (`callable`, optional):
341343
A callback function accepting two parameters:
@@ -378,6 +380,9 @@ async def download_media(
378380
path = await message.download_media()
379381
await message.download_media(filename)
380382
383+
# Downloading to memory
384+
blob = await client.download_media(message, bytes)
385+
381386
# Printing download progress
382387
def callback(current, total):
383388
print('Downloaded', current, 'out of', total,

telethon/events/chataction.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,17 @@ def build(cls, update, others=None, self_id=None):
108108
return cls.Event(msg,
109109
new_score=action.score)
110110

111+
elif isinstance(update, types.UpdateChannelParticipant) \
112+
and bool(update.new_participant) != bool(update.prev_participant):
113+
# If members are hidden, bots will receive this update instead,
114+
# as there won't be a service message. Promotions and demotions
115+
# seem to have both new and prev participant, which are ignored
116+
# by this event.
117+
return cls.Event(types.PeerChannel(update.channel_id),
118+
users=update.user_id,
119+
added_by=update.actor_id if update.new_participant else None,
120+
kicked_by=update.actor_id if update.prev_participant else None)
121+
111122
class Event(EventCommon):
112123
"""
113124
Represents the event of a new chat action.
@@ -142,7 +153,7 @@ class Event(EventCommon):
142153
143154
new_title (`str`, optional):
144155
The new title string for the chat, if applicable.
145-
156+
146157
new_score (`str`, optional):
147158
The new score string for the game, if applicable.
148159

telethon_examples/interactive_telegram_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ async def init(self):
120120
print('Initial connection failed. Retrying...')
121121
await self.connect()
122122

123-
# If the user hasn't called .sign_in() or .sign_up() yet, they won't
123+
# If the user hasn't called .sign_in() yet, they won't
124124
# be authorized. The first thing you must do is authorize. Calling
125125
# .sign_in() should only be done once as the information is saved on
126126
# the *.session file so you don't need to enter the code every time.

telethon_generator/data/errors.csv

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ STICKER_FILE_INVALID,400,Sticker file invalid
427427
STICKER_GIF_DIMENSIONS,400,The specified video sticker has invalid dimensions
428428
STICKER_ID_INVALID,400,The provided sticker ID is invalid
429429
STICKER_INVALID,400,The provided sticker is invalid
430+
STICKER_MIME_INVALID,400,Make sure to pass a valid image file for the right InputFile parameter
430431
STICKER_PNG_DIMENSIONS,400,Sticker png dimensions invalid
431432
STICKER_PNG_NOPNG,400,Stickers must be a png file but the used image was not a png
432433
STICKER_TGS_NODOC,400,You must send the animated sticker as a document

telethon_generator/data/friendly.csv

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
ns,friendly,raw
22
account.AccountMethods,takeout,invokeWithTakeout account.initTakeoutSession account.finishTakeoutSession
33
auth.AuthMethods,sign_in,auth.signIn auth.importBotAuthorization
4-
auth.AuthMethods,sign_up,auth.signUp
54
auth.AuthMethods,send_code_request,auth.sendCode auth.resendCode
65
auth.AuthMethods,log_out,auth.logOut
76
auth.AuthMethods,edit_2fa,account.updatePasswordSettings

telethon_generator/data/methods.csv

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ phone.toggleGroupCallSettings,user,GROUPCALL_NOT_MODIFIED
332332
photos.deletePhotos,user,
333333
photos.getUserPhotos,both,MAX_ID_INVALID USER_ID_INVALID
334334
photos.updateProfilePhoto,user,PHOTO_ID_INVALID
335-
photos.uploadProfilePhoto,user,ALBUM_PHOTOS_TOO_MANY FILE_PARTS_INVALID IMAGE_PROCESS_FAILED PHOTO_CROP_SIZE_SMALL PHOTO_EXT_INVALID VIDEO_FILE_INVALID
335+
photos.uploadProfilePhoto,user,ALBUM_PHOTOS_TOO_MANY FILE_PARTS_INVALID IMAGE_PROCESS_FAILED PHOTO_CROP_SIZE_SMALL PHOTO_EXT_INVALID STICKER_MIME_INVALID VIDEO_FILE_INVALID
336336
ping,both,
337337
reqDHParams,both,
338338
reqPq,both,

0 commit comments

Comments
 (0)