Make upload_file private

This commit is contained in:
Lonami Exo 2022-01-26 12:24:45 +01:00
parent 070af28e85
commit f2ef0bfceb
6 changed files with 95 additions and 95 deletions

View File

@ -777,3 +777,5 @@ self-produced updates like getmessage now also trigger a handler
input_peer removed from get_me; input peers should remain mostly an impl detail input_peer removed from get_me; input peers should remain mostly an impl detail
raw api types and fns are now immutable. this can enable optimizations in the future. raw api types and fns are now immutable. this can enable optimizations in the future.
upload_file has been removed from the public methods. it's a low-level method users should not need to use.

View File

@ -476,10 +476,10 @@ async def send_message(
# TODO album # TODO album
if message._file._should_upload_thumb(): if message._file._should_upload_thumb():
message._file._set_uploaded_thumb(await self.upload_file(message._file._thumb)) message._file._set_uploaded_thumb(await self._upload_file(message._file._thumb))
if message._file._should_upload_file(): if message._file._should_upload_file():
message._file._set_uploaded_file(await self.upload_file(message._file._file)) message._file._set_uploaded_file(await self._upload_file(message._file._file))
request = _tl.fn.messages.SendMedia( request = _tl.fn.messages.SendMedia(
entity, message._file._media, reply_to_msg_id=reply_to, message=message._text, entity, message._file._media, reply_to_msg_id=reply_to, message=message._text,

View File

@ -2983,8 +2983,6 @@ class TelegramClient:
message with media before, you can use its ``message.media`` message with media before, you can use its ``message.media``
as a file here). as a file here).
* A handle to an uploaded file (from `upload_file`).
* A :tl:`InputMedia` instance. For example, if you want to * A :tl:`InputMedia` instance. For example, if you want to
send a dice use :tl:`InputMediaDice`, or if you want to send a dice use :tl:`InputMediaDice`, or if you want to
send a contact use :tl:`InputMediaContact`. send a contact use :tl:`InputMediaContact`.
@ -3157,93 +3155,6 @@ class TelegramClient:
)) ))
""" """
@forward_call(uploads.upload_file)
async def upload_file(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
part_size_kb: float = None,
file_size: int = None,
file_name: str = None,
use_cache: type = None,
key: bytes = None,
iv: bytes = None,
progress_callback: 'hints.ProgressCallback' = None) -> '_tl.TypeInputFile':
"""
Uploads a file to Telegram's servers, without sending it.
.. note::
Generally, you want to use `send_file` instead.
This method returns a handle (an instance of :tl:`InputFile` or
:tl:`InputFileBig`, as required) which can be later used before
it expires (they are usable during less than a day).
Uploading a file will simply return a "handle" to the file stored
remotely in the Telegram servers, which can be later used on. This
will **not** upload the file to your own chat or any chat at all.
Arguments
file (`str` | `bytes` | `file`):
The path of the file, byte array, or stream that will be sent.
Note that if a byte array or a stream is given, a filename
or its type won't be inferred, and it will be sent as an
"unnamed application/octet-stream".
part_size_kb (`int`, optional):
Chunk size when uploading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The size of the file to be uploaded, which will be determined
automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
file_name (`str`, optional):
The file name which will be used on the resulting InputFile.
If not specified, the name will be taken from the ``file``
and if this is not a `str`, it will be ``"unnamed"``.
use_cache (`type`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
Returns
:tl:`InputFileBig` if the file size is larger than 10MB,
`InputSizedFile <telethon.tl._custom.inputsizedfile.InputSizedFile>`
(subclass of :tl:`InputFile`) otherwise.
Example
.. code-block:: python
# Photos as photo and document
file = await client.upload_file('photo.jpg')
await client.send_file(chat, file) # sends as photo
await client.send_file(chat, file, force_document=True) # sends as document
file.name = 'not a photo.jpg'
await client.send_file(chat, file, force_document=True) # document, new name
# As song or as voice note
file = await client.upload_file('song.ogg')
await client.send_file(chat, file) # sends as song
await client.send_file(chat, file, voice_note=True) # sends as voice note
"""
# endregion Uploads # endregion Uploads
# region Users # region Users
@ -3508,4 +3419,18 @@ class TelegramClient:
async def _replace_session_state(self, *, save=True, **changes): async def _replace_session_state(self, *, save=True, **changes):
pass pass
@forward_call(uploads.upload_file)
async def _upload_file(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
part_size_kb: float = None,
file_size: int = None,
file_name: str = None,
use_cache: type = None,
key: bytes = None,
iv: bytes = None,
progress_callback: 'hints.ProgressCallback' = None) -> '_tl.TypeInputFile':
pass
# endregion Private # endregion Private

View File

@ -235,6 +235,80 @@ async def upload_file(
key: bytes = None, key: bytes = None,
iv: bytes = None, iv: bytes = None,
progress_callback: 'hints.ProgressCallback' = None) -> '_tl.TypeInputFile': progress_callback: 'hints.ProgressCallback' = None) -> '_tl.TypeInputFile':
"""
Uploads a file to Telegram's servers, without sending it.
.. note::
Generally, you want to use `send_file` instead.
This method returns a handle (an instance of :tl:`InputFile` or
:tl:`InputFileBig`, as required) which can be later used before
it expires (they are usable during less than a day).
Uploading a file will simply return a "handle" to the file stored
remotely in the Telegram servers, which can be later used on. This
will **not** upload the file to your own chat or any chat at all.
Arguments
file (`str` | `bytes` | `file`):
The path of the file, byte array, or stream that will be sent.
Note that if a byte array or a stream is given, a filename
or its type won't be inferred, and it will be sent as an
"unnamed application/octet-stream".
part_size_kb (`int`, optional):
Chunk size when uploading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The size of the file to be uploaded, which will be determined
automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
file_name (`str`, optional):
The file name which will be used on the resulting InputFile.
If not specified, the name will be taken from the ``file``
and if this is not a `str`, it will be ``"unnamed"``.
use_cache (`type`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
Returns
:tl:`InputFileBig` if the file size is larger than 10MB,
`InputSizedFile <telethon.tl._custom.inputsizedfile.InputSizedFile>`
(subclass of :tl:`InputFile`) otherwise.
Example
.. code-block:: python
# Photos as photo and document
file = await client.upload_file('photo.jpg')
await client.send_file(chat, file) # sends as photo
await client.send_file(chat, file, force_document=True) # sends as document
file.name = 'not a photo.jpg'
await client.send_file(chat, file, force_document=True) # document, new name
# As song or as voice note
file = await client.upload_file('song.ogg')
await client.send_file(chat, file) # sends as song
await client.send_file(chat, file, voice_note=True) # sends as voice note
"""
if isinstance(file, (_tl.InputFile, _tl.InputFileBig)): if isinstance(file, (_tl.InputFile, _tl.InputFileBig)):
return file # Already uploaded return file # Already uploaded

View File

@ -23,5 +23,4 @@ messages.MessageMethods,delete_messages,channels.deleteMessages messages.deleteM
messages.MessageMethods,send_read_acknowledge,messages.readMentions channels.readHistory messages.readHistory messages.MessageMethods,send_read_acknowledge,messages.readMentions channels.readHistory messages.readHistory
updates.UpdateMethods,catch_up,updates.getDifference updates.getChannelDifference updates.UpdateMethods,catch_up,updates.getDifference updates.getChannelDifference
uploads.UploadMethods,send_file,messages.sendMedia messages.sendMultiMedia messages.uploadMedia uploads.UploadMethods,send_file,messages.sendMedia messages.sendMultiMedia messages.uploadMedia
uploads.UploadMethods,upload_file,upload.saveFilePart upload.saveBigFilePart
users.UserMethods,get_entity,users.getUsers messages.getChats channels.getChannels contacts.resolveUsername users.UserMethods,get_entity,users.getUsers messages.getChats channels.getChannels contacts.resolveUsername

1 ns friendly raw
23 messages.MessageMethods send_read_acknowledge messages.readMentions channels.readHistory messages.readHistory
24 updates.UpdateMethods catch_up updates.getDifference updates.getChannelDifference
25 uploads.UploadMethods send_file messages.sendMedia messages.sendMultiMedia messages.uploadMedia
uploads.UploadMethods upload_file upload.saveFilePart upload.saveBigFilePart
26 users.UserMethods get_entity users.getUsers messages.getChats channels.getChannels contacts.resolveUsername

View File

@ -37,7 +37,7 @@ KNOWN_NAMED_EXAMPLES = {
('lang_code', 'string'): "'en'", ('lang_code', 'string'): "'en'",
('chat_id', 'int'): '478614198', ('chat_id', 'int'): '478614198',
('client_id', 'long'): 'random.randrange(-2**63, 2**63)', ('client_id', 'long'): 'random.randrange(-2**63, 2**63)',
('video', 'InputFile'): "client.upload_file('/path/to/file.mp4')", ('video', 'InputFile'): "client._upload_file('/path/to/file.mp4')",
} }
KNOWN_TYPED_EXAMPLES = { KNOWN_TYPED_EXAMPLES = {
@ -50,8 +50,8 @@ KNOWN_TYPED_EXAMPLES = {
'double': '7.13', 'double': '7.13',
'Bool': 'False', 'Bool': 'False',
'true': 'True', 'true': 'True',
'InputChatPhoto': "client.upload_file('/path/to/photo.jpg')", 'InputChatPhoto': "client._upload_file('/path/to/photo.jpg')",
'InputFile': "client.upload_file('/path/to/file.jpg')", 'InputFile': "client._upload_file('/path/to/file.jpg')",
'InputPeer': "'username'" 'InputPeer': "'username'"
} }