2018-06-09 23:05:06 +03:00
|
|
|
import hashlib
|
|
|
|
import io
|
2019-06-15 17:59:16 +03:00
|
|
|
import itertools
|
2018-06-09 23:05:06 +03:00
|
|
|
import os
|
2018-06-16 18:01:20 +03:00
|
|
|
import pathlib
|
2018-06-26 17:39:22 +03:00
|
|
|
import re
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2018-06-09 23:05:06 +03:00
|
|
|
from io import BytesIO
|
|
|
|
|
2020-03-04 18:12:34 +03:00
|
|
|
from ..crypto import AES
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
from .. import utils, helpers, hints
|
2018-06-09 23:05:06 +03:00
|
|
|
from ..tl import types, functions, custom
|
|
|
|
|
2019-02-13 11:50:00 +03:00
|
|
|
try:
|
|
|
|
import PIL
|
|
|
|
import PIL.Image
|
|
|
|
except ImportError:
|
|
|
|
PIL = None
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
|
|
|
|
|
|
|
|
2018-12-25 19:02:33 +03:00
|
|
|
class _CacheType:
|
|
|
|
"""Like functools.partial but pretends to be the wrapped class."""
|
|
|
|
def __init__(self, cls):
|
|
|
|
self._cls = cls
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
return self._cls(*args, file_reference=b'', **kwargs)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return self._cls == other
|
|
|
|
|
|
|
|
|
2019-02-14 14:10:34 +03:00
|
|
|
def _resize_photo_if_needed(
|
2023-01-18 19:37:56 +03:00
|
|
|
file, is_image, width=2560, height=2560, background=(255, 255, 255)):
|
2019-02-14 14:10:34 +03:00
|
|
|
|
2019-02-13 11:58:02 +03:00
|
|
|
# https://github.com/telegramdesktop/tdesktop/blob/12905f0dcb9d513378e7db11989455a1b764ef75/Telegram/SourceFiles/boxes/photo_crop_box.cpp#L254
|
2019-02-13 11:50:00 +03:00
|
|
|
if (not is_image
|
|
|
|
or PIL is None
|
|
|
|
or (isinstance(file, io.IOBase) and not file.seekable())):
|
|
|
|
return file
|
|
|
|
|
|
|
|
if isinstance(file, bytes):
|
|
|
|
file = io.BytesIO(file)
|
|
|
|
|
2023-07-23 22:58:10 +03:00
|
|
|
if isinstance(file, io.IOBase):
|
|
|
|
# Pillow seeks to 0 unconditionally later anyway
|
|
|
|
old_pos = file.tell()
|
|
|
|
file.seek(0, io.SEEK_END)
|
|
|
|
before = file.tell()
|
|
|
|
elif isinstance(file, str) and os.path.exists(file):
|
|
|
|
# Check if file exists as a path and if so, get its size on disk
|
|
|
|
before = os.path.getsize(file)
|
|
|
|
else:
|
|
|
|
# Would be weird...
|
|
|
|
before = None
|
2019-04-09 08:29:06 +03:00
|
|
|
|
2019-02-13 11:50:00 +03:00
|
|
|
try:
|
2019-03-06 11:14:06 +03:00
|
|
|
# Don't use a `with` block for `image`, or `file` would be closed.
|
|
|
|
# See https://github.com/LonamiWebs/Telethon/issues/1121 for more.
|
|
|
|
image = PIL.Image.open(file)
|
2021-01-26 23:44:11 +03:00
|
|
|
try:
|
|
|
|
kwargs = {'exif': image.info['exif']}
|
|
|
|
except KeyError:
|
|
|
|
kwargs = {}
|
|
|
|
|
2023-07-23 22:58:10 +03:00
|
|
|
# Check if image is within acceptable bounds, if so, check if the image is at or below 10 MB, or assume it isn't if size is None or 0
|
|
|
|
if image.width <= width and image.height <= height and (before <= 10000000 if before else False):
|
2019-03-06 11:14:06 +03:00
|
|
|
return file
|
|
|
|
|
2023-07-23 22:58:10 +03:00
|
|
|
image.thumbnail((width, height), PIL.Image.LANCZOS)
|
2019-03-06 11:14:06 +03:00
|
|
|
|
|
|
|
alpha_index = image.mode.find('A')
|
|
|
|
if alpha_index == -1:
|
|
|
|
# If the image mode doesn't have alpha
|
|
|
|
# channel then don't bother masking it away.
|
|
|
|
result = image
|
|
|
|
else:
|
|
|
|
# We could save the resized image with the original format, but
|
|
|
|
# JPEG often compresses better -> smaller size -> faster upload
|
|
|
|
# We need to mask away the alpha channel ([3]), since otherwise
|
|
|
|
# IOError is raised when trying to save alpha channels in JPEG.
|
|
|
|
result = PIL.Image.new('RGB', image.size, background)
|
|
|
|
result.paste(image, mask=image.split()[alpha_index])
|
|
|
|
|
|
|
|
buffer = io.BytesIO()
|
2023-04-13 21:11:52 +03:00
|
|
|
result.save(buffer, 'JPEG', progressive=True, **kwargs)
|
2019-03-06 11:14:06 +03:00
|
|
|
buffer.seek(0)
|
2023-11-12 23:12:27 +03:00
|
|
|
buffer.name = 'a.jpg'
|
2019-03-06 11:14:06 +03:00
|
|
|
return buffer
|
2019-02-13 11:50:00 +03:00
|
|
|
except IOError:
|
|
|
|
return file
|
|
|
|
finally:
|
2023-07-23 22:58:10 +03:00
|
|
|
# The original position might matter
|
|
|
|
if isinstance(file, io.IOBase):
|
|
|
|
file.seek(old_pos)
|
2019-02-13 11:50:00 +03:00
|
|
|
|
|
|
|
|
2019-06-24 18:48:46 +03:00
|
|
|
class UploadMethods:
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
|
|
|
async def send_file(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
2019-05-08 18:16:09 +03:00
|
|
|
entity: 'hints.EntityLike',
|
2019-06-15 17:59:16 +03:00
|
|
|
file: 'typing.Union[hints.FileLike, typing.Sequence[hints.FileLike]]',
|
2019-05-03 22:37:27 +03:00
|
|
|
*,
|
2019-06-15 17:59:16 +03:00
|
|
|
caption: typing.Union[str, typing.Sequence[str]] = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
force_document: bool = False,
|
2020-07-15 15:35:42 +03:00
|
|
|
file_size: int = None,
|
2020-01-22 16:16:27 +03:00
|
|
|
clear_draft: bool = False,
|
2019-05-08 18:16:09 +03:00
|
|
|
progress_callback: 'hints.ProgressCallback' = None,
|
|
|
|
reply_to: 'hints.MessageIDLike' = None,
|
|
|
|
attributes: 'typing.Sequence[types.TypeDocumentAttribute]' = None,
|
|
|
|
thumb: 'hints.FileLike' = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
allow_cache: bool = True,
|
|
|
|
parse_mode: str = (),
|
2024-10-05 12:13:20 +03:00
|
|
|
formatting_entities: typing.Optional[
|
|
|
|
typing.Union[
|
|
|
|
typing.List[types.TypeMessageEntity], typing.List[typing.List[types.TypeMessageEntity]]
|
|
|
|
]
|
|
|
|
] = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
voice_note: bool = False,
|
|
|
|
video_note: bool = False,
|
2022-09-20 19:03:16 +03:00
|
|
|
buttons: typing.Optional['hints.MarkupLike'] = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
silent: bool = None,
|
2021-08-05 11:54:07 +03:00
|
|
|
background: bool = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
supports_streaming: bool = False,
|
2019-09-06 14:45:31 +03:00
|
|
|
schedule: 'hints.DateLike' = None,
|
2021-01-28 23:05:00 +03:00
|
|
|
comment_to: 'typing.Union[int, types.Message]' = None,
|
2021-09-11 12:02:19 +03:00
|
|
|
ttl: int = None,
|
2023-04-14 23:03:03 +03:00
|
|
|
nosound_video: bool = None,
|
2024-11-18 19:04:07 +03:00
|
|
|
**kwargs) -> typing.Union[typing.List[typing.Any], typing.Any]:
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Sends message with the given file to the specified entity.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
If the ``hachoir3`` package (``hachoir`` module) is installed,
|
|
|
|
it will be used to determine metadata from audio and video files.
|
|
|
|
|
|
|
|
If the ``pillow`` package is installed and you are sending a photo,
|
|
|
|
it will be resized to fit within the maximum dimensions allowed
|
|
|
|
by Telegram to avoid ``errors.PhotoInvalidDimensionsError``. This
|
|
|
|
cannot be done if you are sending :tl:`InputFile`, however.
|
|
|
|
|
|
|
|
Arguments
|
2018-06-09 23:05:06 +03:00
|
|
|
entity (`entity`):
|
|
|
|
Who will receive the file.
|
|
|
|
|
|
|
|
file (`str` | `bytes` | `file` | `media`):
|
2019-03-10 15:29:34 +03:00
|
|
|
The file to send, which can be one of:
|
|
|
|
|
|
|
|
* A local file path to an in-disk file. The file name
|
|
|
|
will be the path's base name.
|
|
|
|
|
|
|
|
* A `bytes` byte array with the file's data to send
|
|
|
|
(for example, by using ``text.encode('utf-8')``).
|
|
|
|
A default file name will be used.
|
|
|
|
|
|
|
|
* A bytes `io.IOBase` stream over the file to send
|
|
|
|
(for example, by using ``open(file, 'rb')``).
|
|
|
|
Its ``.name`` property will be used for the file name,
|
|
|
|
or a default if it doesn't have one.
|
|
|
|
|
|
|
|
* An external URL to a file over the internet. This will
|
|
|
|
send the file as "external" media, and Telegram is the
|
|
|
|
one that will fetch the media and send it.
|
|
|
|
|
|
|
|
* A Bot API-like ``file_id``. You can convert previously
|
|
|
|
sent media to file IDs for later reusing with
|
|
|
|
`telethon.utils.pack_bot_file_id`.
|
|
|
|
|
|
|
|
* A handle to an existing file (for example, if you sent a
|
|
|
|
message with media before, you can use its ``message.media``
|
|
|
|
as a file here).
|
|
|
|
|
|
|
|
* A handle to an uploaded file (from `upload_file`).
|
|
|
|
|
2020-05-05 10:28:37 +03:00
|
|
|
* A :tl:`InputMedia` instance. For example, if you want to
|
|
|
|
send a dice use :tl:`InputMediaDice`, or if you want to
|
|
|
|
send a contact use :tl:`InputMediaContact`.
|
|
|
|
|
2019-03-10 15:29:34 +03:00
|
|
|
To send an album, you should provide a list in this parameter.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
If a list or similar is provided, the files in it will be
|
|
|
|
sent as an album in the order in which they appear, sliced
|
|
|
|
in chunks of 10 if more than 10 are given.
|
|
|
|
|
|
|
|
caption (`str`, optional):
|
2019-03-18 19:30:45 +03:00
|
|
|
Optional caption for the sent media message. When sending an
|
|
|
|
album, the caption may be a list of strings, which will be
|
|
|
|
assigned to the files pairwise.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
force_document (`bool`, optional):
|
2019-07-06 13:10:25 +03:00
|
|
|
If left to `False` and the file is a path that ends with
|
2018-06-09 23:05:06 +03:00
|
|
|
the extension of an image file or a video file, it will be
|
|
|
|
sent as such. Otherwise always as a document.
|
|
|
|
|
2020-07-15 15:35:42 +03:00
|
|
|
file_size (`int`, optional):
|
|
|
|
The size of the file to be uploaded if it needs 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.
|
|
|
|
|
2020-01-22 16:16:27 +03:00
|
|
|
clear_draft (`bool`, optional):
|
|
|
|
Whether the existing draft should be cleared or not.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
progress_callback (`callable`, optional):
|
|
|
|
A callback function accepting two parameters:
|
|
|
|
``(sent bytes, total)``.
|
|
|
|
|
2019-01-12 15:06:14 +03:00
|
|
|
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`):
|
2018-06-09 23:05:06 +03:00
|
|
|
Same as `reply_to` from `send_message`.
|
|
|
|
|
|
|
|
attributes (`list`, optional):
|
|
|
|
Optional attributes that override the inferred ones, like
|
|
|
|
:tl:`DocumentAttributeFilename` and so on.
|
|
|
|
|
|
|
|
thumb (`str` | `bytes` | `file`, optional):
|
2018-07-07 13:01:42 +03:00
|
|
|
Optional JPEG thumbnail (for documents). **Telegram will
|
|
|
|
ignore this parameter** unless you pass a ``.jpg`` file!
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2021-01-26 23:10:21 +03:00
|
|
|
The file must also be small in dimensions and in disk size.
|
|
|
|
Successful thumbnails were files below 20kB and 320x320px.
|
2018-10-06 21:20:11 +03:00
|
|
|
Width/height and dimensions/size ratios may be important.
|
2021-01-26 23:10:21 +03:00
|
|
|
For Telegram to accept a thumbnail, you must provide the
|
|
|
|
dimensions of the underlying media through ``attributes=``
|
|
|
|
with :tl:`DocumentAttributesVideo` or by installing the
|
|
|
|
optional ``hachoir`` dependency.
|
|
|
|
|
2018-10-06 21:20:11 +03:00
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
allow_cache (`bool`, optional):
|
2019-09-27 16:12:17 +03:00
|
|
|
This parameter currently does nothing, but is kept for
|
|
|
|
backward-compatibility (and it may get its use back in
|
|
|
|
the future).
|
2018-12-25 18:50:11 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
parse_mode (`object`, optional):
|
2019-01-12 15:06:14 +03:00
|
|
|
See the `TelegramClient.parse_mode
|
|
|
|
<telethon.client.messageparse.MessageParseMethods.parse_mode>`
|
|
|
|
property for allowed values. Markdown parsing will be used by
|
|
|
|
default.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2020-10-02 23:06:48 +03:00
|
|
|
formatting_entities (`list`, optional):
|
2024-10-05 12:13:20 +03:00
|
|
|
Optional formatting entities for the sent media message. When sending an album,
|
|
|
|
`formatting_entities` can be a list of lists, where each inner list contains
|
|
|
|
`types.TypeMessageEntity`. Each inner list will be assigned to the corresponding
|
|
|
|
file in a pairwise manner with the caption. If provided, the ``parse_mode``
|
|
|
|
parameter will be ignored.
|
2020-10-02 23:06:48 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
voice_note (`bool`, optional):
|
2019-07-06 13:10:25 +03:00
|
|
|
If `True` the audio will be sent as a voice note.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
video_note (`bool`, optional):
|
2019-07-06 13:10:25 +03:00
|
|
|
If `True` the video will be sent as a video note,
|
2018-06-09 23:05:06 +03:00
|
|
|
also known as a round video message.
|
|
|
|
|
2018-10-06 21:20:11 +03:00
|
|
|
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`):
|
2018-07-10 14:11:56 +03:00
|
|
|
The matrix (list of lists), row list or button to be shown
|
|
|
|
after sending the message. This parameter will only work if
|
|
|
|
you have signed in as a bot. You can also pass your own
|
|
|
|
:tl:`ReplyMarkup` here.
|
|
|
|
|
2018-07-11 11:16:21 +03:00
|
|
|
silent (`bool`, optional):
|
2019-08-10 10:06:05 +03:00
|
|
|
Whether the message should notify people with sound or not.
|
|
|
|
Defaults to `False` (send with a notification sound unless
|
|
|
|
the person has the chat muted). Set it to `True` to alter
|
|
|
|
this behaviour.
|
2018-07-11 11:16:21 +03:00
|
|
|
|
2021-08-05 11:54:07 +03:00
|
|
|
background (`bool`, optional):
|
|
|
|
Whether the message should be send in background.
|
|
|
|
|
2019-01-21 21:46:33 +03:00
|
|
|
supports_streaming (`bool`, optional):
|
|
|
|
Whether the sent video supports streaming or not. Note that
|
|
|
|
Telegram only recognizes as streamable some formats like MP4,
|
|
|
|
and others like AVI or MKV will not work. You should convert
|
|
|
|
these to MP4 before sending if you want them to be streamable.
|
|
|
|
Unsupported formats will result in ``VideoContentTypeError``.
|
|
|
|
|
2019-09-06 14:45:31 +03:00
|
|
|
schedule (`hints.DateLike`, optional):
|
|
|
|
If set, the file won't send immediately, and instead
|
|
|
|
it will be scheduled to be automatically sent at a later
|
|
|
|
time.
|
|
|
|
|
2021-01-28 23:05:00 +03:00
|
|
|
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
|
|
|
|
Similar to ``reply_to``, but replies in the linked group of a
|
|
|
|
broadcast channel instead (effectively leaving a "comment to"
|
|
|
|
the specified message).
|
|
|
|
|
|
|
|
This parameter takes precedence over ``reply_to``. If there is
|
|
|
|
no linked chat, `telethon.errors.sgIdInvalidError` is raised.
|
|
|
|
|
2021-09-11 12:02:19 +03:00
|
|
|
ttl (`int`. optional):
|
|
|
|
The Time-To-Live of the file (also known as "self-destruct timer"
|
|
|
|
or "self-destructing media"). If set, files can only be viewed for
|
|
|
|
a short period of time before they disappear from the message
|
|
|
|
history automatically.
|
|
|
|
|
|
|
|
The value must be at least 1 second, and at most 60 seconds,
|
|
|
|
otherwise Telegram will ignore this parameter.
|
|
|
|
|
|
|
|
Not all types of media can be used with this parameter, such
|
|
|
|
as text documents, which will fail with ``TtlMediaInvalidError``.
|
|
|
|
|
2023-04-14 23:03:03 +03:00
|
|
|
nosound_video (`bool`, optional):
|
|
|
|
Only applicable when sending a video file without an audio
|
|
|
|
track. If set to ``True``, the video will be displayed in
|
|
|
|
Telegram as a video. If set to ``False``, Telegram will attempt
|
|
|
|
to display the video as an animated gif. (It may still display
|
|
|
|
as a video due to other factors.) The value is ignored if set
|
|
|
|
on non-video files. This is set to ``True`` for albums, as gifs
|
|
|
|
cannot be sent in albums.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2019-06-01 17:27:53 +03:00
|
|
|
The `Message <telethon.tl.custom.message.Message>` (or messages)
|
|
|
|
containing the sent file, or messages if a list of them was passed.
|
2019-05-09 13:24:37 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
2019-05-09 13:24:37 +03:00
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Normal files like photos
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, '/my/photos/me.jpg', caption="It's me!")
|
2019-05-09 13:24:37 +03:00
|
|
|
# or
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_message(chat, "It's me!", file='/my/photos/me.jpg')
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# Voice notes or round videos
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, '/my/songs/song.mp3', voice_note=True)
|
|
|
|
await client.send_file(chat, '/my/videos/video.mp4', video_note=True)
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# Custom thumbnails
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, '/my/documents/doc.txt', thumb='photo.jpg')
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# Only documents
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, '/my/photos/photo.png', force_document=True)
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# Albums
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, [
|
2019-05-09 13:24:37 +03:00
|
|
|
'/my/photos/holiday1.jpg',
|
|
|
|
'/my/photos/holiday2.jpg',
|
|
|
|
'/my/drawings/portrait.png'
|
|
|
|
])
|
2020-02-28 13:50:16 +03:00
|
|
|
|
|
|
|
# Printing upload progress
|
|
|
|
def callback(current, total):
|
|
|
|
print('Uploaded', current, 'out of', total,
|
|
|
|
'bytes: {:.2%}'.format(current / total))
|
|
|
|
|
|
|
|
await client.send_file(chat, file, progress_callback=callback)
|
2020-05-05 10:28:37 +03:00
|
|
|
|
|
|
|
# Dices, including dart and other future emoji
|
|
|
|
from telethon.tl import types
|
|
|
|
await client.send_file(chat, types.InputMediaDice(''))
|
|
|
|
await client.send_file(chat, types.InputMediaDice('🎯'))
|
|
|
|
|
|
|
|
# Contacts
|
|
|
|
await client.send_file(chat, types.InputMediaContact(
|
|
|
|
phone_number='+34 123 456 789',
|
|
|
|
first_name='Example',
|
|
|
|
last_name='',
|
|
|
|
vcard=''
|
|
|
|
))
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
2019-09-27 16:12:17 +03:00
|
|
|
# TODO Properly implement allow_cache to reuse the sha256 of the file
|
2019-07-06 13:10:25 +03:00
|
|
|
# i.e. `None` was used
|
2019-02-19 18:41:51 +03:00
|
|
|
if not file:
|
|
|
|
raise TypeError('Cannot use {!r} as file'.format(file))
|
|
|
|
|
2018-12-20 12:50:16 +03:00
|
|
|
if not caption:
|
|
|
|
caption = ''
|
|
|
|
|
2024-10-05 12:13:20 +03:00
|
|
|
if not formatting_entities:
|
|
|
|
formatting_entities = []
|
|
|
|
|
2021-01-28 23:05:00 +03:00
|
|
|
entity = await self.get_input_entity(entity)
|
|
|
|
if comment_to is not None:
|
|
|
|
entity, reply_to = await self._get_comment_data(entity, comment_to)
|
|
|
|
else:
|
2021-01-30 12:32:42 +03:00
|
|
|
reply_to = utils.get_message_id(reply_to)
|
2021-01-28 23:05:00 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
# First check if the user passed an iterable, in which case
|
2020-11-07 19:32:00 +03:00
|
|
|
# we may want to send grouped.
|
2018-06-09 23:05:06 +03:00
|
|
|
if utils.is_list_like(file):
|
2023-03-28 19:15:57 +03:00
|
|
|
sent_count = 0
|
|
|
|
used_callback = None if not progress_callback else (
|
|
|
|
lambda s, t: progress_callback(sent_count + s, len(file))
|
|
|
|
)
|
|
|
|
|
2019-06-15 17:59:16 +03:00
|
|
|
if utils.is_list_like(caption):
|
|
|
|
captions = caption
|
|
|
|
else:
|
|
|
|
captions = [caption]
|
|
|
|
|
2024-10-05 12:13:20 +03:00
|
|
|
# Check that formatting_entities list is valid
|
|
|
|
if all(utils.is_list_like(obj) for obj in formatting_entities):
|
|
|
|
formatting_entities = formatting_entities
|
|
|
|
elif utils.is_list_like(formatting_entities):
|
|
|
|
formatting_entities = [formatting_entities]
|
|
|
|
else:
|
|
|
|
raise TypeError('The formatting_entities argument must be a list or a sequence of lists')
|
|
|
|
|
|
|
|
# Check that all entities in all lists are of the correct type
|
|
|
|
if not all(isinstance(ent, types.TypeMessageEntity) for sublist in formatting_entities for ent in sublist):
|
|
|
|
raise TypeError('All entities must be instances of <types.TypeMessageEntity>')
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
result = []
|
2020-11-07 19:32:00 +03:00
|
|
|
while file:
|
2018-06-09 23:05:06 +03:00
|
|
|
result += await self._send_album(
|
2024-10-05 12:13:20 +03:00
|
|
|
entity, file[:10], caption=captions[:10], formatting_entities=formatting_entities[:10],
|
2023-03-28 19:15:57 +03:00
|
|
|
progress_callback=used_callback, reply_to=reply_to,
|
2020-01-17 13:12:20 +03:00
|
|
|
parse_mode=parse_mode, silent=silent, schedule=schedule,
|
2020-11-07 19:32:00 +03:00
|
|
|
supports_streaming=supports_streaming, clear_draft=clear_draft,
|
2021-08-05 11:54:07 +03:00
|
|
|
force_document=force_document, background=background,
|
2018-06-09 23:05:06 +03:00
|
|
|
)
|
2020-11-07 19:32:00 +03:00
|
|
|
file = file[10:]
|
|
|
|
captions = captions[10:]
|
2024-10-05 12:13:20 +03:00
|
|
|
formatting_entities = formatting_entities[10:]
|
2023-03-28 19:15:57 +03:00
|
|
|
sent_count += 10
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
return result
|
|
|
|
|
2024-10-20 20:50:08 +03:00
|
|
|
if formatting_entities:
|
2020-10-02 23:06:48 +03:00
|
|
|
msg_entities = formatting_entities
|
2018-06-09 23:05:06 +03:00
|
|
|
else:
|
|
|
|
caption, msg_entities =\
|
|
|
|
await self._parse_message_text(caption, parse_mode)
|
|
|
|
|
2019-03-06 11:38:17 +03:00
|
|
|
file_handle, media, image = await self._file_to_media(
|
2018-06-26 17:39:43 +03:00
|
|
|
file, force_document=force_document,
|
2020-07-15 15:35:42 +03:00
|
|
|
file_size=file_size,
|
2018-06-26 17:39:43 +03:00
|
|
|
progress_callback=progress_callback,
|
2024-10-05 12:13:20 +03:00
|
|
|
attributes=attributes, allow_cache=allow_cache, thumb=thumb,
|
2019-01-21 21:46:33 +03:00
|
|
|
voice_note=voice_note, video_note=video_note,
|
2023-04-14 23:03:03 +03:00
|
|
|
supports_streaming=supports_streaming, ttl=ttl,
|
|
|
|
nosound_video=nosound_video,
|
2018-06-26 17:39:43 +03:00
|
|
|
)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-02-19 18:41:51 +03:00
|
|
|
# e.g. invalid cast from :tl:`MessageMediaWebPage`
|
|
|
|
if not media:
|
|
|
|
raise TypeError('Cannot use {!r} as file'.format(file))
|
|
|
|
|
2018-07-21 14:54:36 +03:00
|
|
|
markup = self.build_reply_markup(buttons)
|
2023-07-21 23:44:35 +03:00
|
|
|
reply_to = None if reply_to is None else types.InputReplyToMessage(reply_to)
|
2018-06-09 23:05:06 +03:00
|
|
|
request = functions.messages.SendMediaRequest(
|
2023-07-21 23:44:35 +03:00
|
|
|
entity, media, reply_to=reply_to, message=caption,
|
2019-09-06 14:45:31 +03:00
|
|
|
entities=msg_entities, reply_markup=markup, silent=silent,
|
2021-08-05 11:54:07 +03:00
|
|
|
schedule_date=schedule, clear_draft=clear_draft,
|
|
|
|
background=background
|
2018-06-09 23:05:06 +03:00
|
|
|
)
|
2020-03-11 12:07:21 +03:00
|
|
|
return self._get_response_message(request, await self(request), entity)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _send_album(self: 'TelegramClient', entity, files, caption='',
|
2024-10-05 12:13:20 +03:00
|
|
|
formatting_entities=None,
|
2019-01-11 17:52:30 +03:00
|
|
|
progress_callback=None, reply_to=None,
|
2020-01-17 13:12:20 +03:00
|
|
|
parse_mode=(), silent=None, schedule=None,
|
2020-11-07 19:32:00 +03:00
|
|
|
supports_streaming=None, clear_draft=None,
|
2021-09-11 12:02:19 +03:00
|
|
|
force_document=False, background=None, ttl=None):
|
2018-06-09 23:05:06 +03:00
|
|
|
"""Specialized version of .send_file for albums"""
|
2018-12-25 18:50:11 +03:00
|
|
|
# We don't care if the user wants to avoid cache, we will use it
|
|
|
|
# anyway. Why? The cached version will be exactly the same thing
|
|
|
|
# we need to produce right now to send albums (uploadMedia), and
|
|
|
|
# cache only makes a difference for documents where the user may
|
|
|
|
# want the attributes used on them to change.
|
|
|
|
#
|
2024-10-05 12:13:20 +03:00
|
|
|
# In theory documents can be sent inside the albums, but they appear
|
2018-12-25 18:50:11 +03:00
|
|
|
# as different messages (not inside the album), and the logic to set
|
|
|
|
# the attributes/avoid cache is already written in .send_file().
|
2018-06-09 23:05:06 +03:00
|
|
|
entity = await self.get_input_entity(entity)
|
|
|
|
if not utils.is_list_like(caption):
|
|
|
|
caption = (caption,)
|
2024-10-05 12:13:20 +03:00
|
|
|
if not all(isinstance(obj, list) for obj in formatting_entities):
|
|
|
|
formatting_entities = (formatting_entities,)
|
2018-06-20 21:18:16 +03:00
|
|
|
|
|
|
|
captions = []
|
2024-10-05 12:13:20 +03:00
|
|
|
# If the formatting_entities argument is provided, we don't use parse_mode
|
|
|
|
if formatting_entities:
|
|
|
|
# Pop from the end (so reverse)
|
|
|
|
capt_with_ent = itertools.zip_longest(reversed(caption), reversed(formatting_entities), fillvalue=None)
|
|
|
|
for msg_caption, msg_entities in capt_with_ent:
|
|
|
|
captions.append((msg_caption, msg_entities))
|
|
|
|
else:
|
|
|
|
for c in reversed(caption): # Pop from the end (so reverse)
|
|
|
|
captions.append(await self._parse_message_text(c or '', parse_mode))
|
2018-06-20 21:18:16 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
reply_to = utils.get_message_id(reply_to)
|
|
|
|
|
2023-03-28 19:15:57 +03:00
|
|
|
used_callback = None if not progress_callback else (
|
|
|
|
# use an integer when sent matches total, to easily determine a file has been fully sent
|
|
|
|
lambda s, t: progress_callback(sent_count + 1 if s == t else sent_count + s / t, len(files))
|
|
|
|
)
|
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
# Need to upload the media first, but only if they're not cached yet
|
2018-06-09 23:05:06 +03:00
|
|
|
media = []
|
2023-03-28 19:15:57 +03:00
|
|
|
for sent_count, file in enumerate(files):
|
2019-02-25 20:23:39 +03:00
|
|
|
# Albums want :tl:`InputMedia` which, in theory, includes
|
2023-04-14 23:03:03 +03:00
|
|
|
# :tl:`InputMediaUploadedPhoto`. However, using that will
|
2019-02-25 20:23:39 +03:00
|
|
|
# make it `raise MediaInvalidError`, so we need to upload
|
|
|
|
# it as media and then convert that to :tl:`InputMediaPhoto`.
|
2020-01-17 13:12:20 +03:00
|
|
|
fh, fm, _ = await self._file_to_media(
|
2020-11-07 19:32:00 +03:00
|
|
|
file, supports_streaming=supports_streaming,
|
2023-03-28 19:15:57 +03:00
|
|
|
force_document=force_document, ttl=ttl,
|
2023-04-14 23:03:03 +03:00
|
|
|
progress_callback=used_callback, nosound_video=True)
|
2021-01-25 10:31:25 +03:00
|
|
|
if isinstance(fm, (types.InputMediaUploadedPhoto, types.InputMediaPhotoExternal)):
|
2018-06-09 23:05:06 +03:00
|
|
|
r = await self(functions.messages.UploadMediaRequest(
|
2019-02-25 20:23:39 +03:00
|
|
|
entity, media=fm
|
2018-06-09 23:05:06 +03:00
|
|
|
))
|
2019-02-25 20:25:49 +03:00
|
|
|
|
|
|
|
fm = utils.get_input_media(r.photo)
|
2020-01-17 13:12:20 +03:00
|
|
|
elif isinstance(fm, types.InputMediaUploadedDocument):
|
|
|
|
r = await self(functions.messages.UploadMediaRequest(
|
|
|
|
entity, media=fm
|
|
|
|
))
|
|
|
|
|
|
|
|
fm = utils.get_input_media(
|
2024-10-05 12:13:20 +03:00
|
|
|
r.document, supports_streaming=supports_streaming)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
if captions:
|
|
|
|
caption, msg_entities = captions.pop()
|
|
|
|
else:
|
|
|
|
caption, msg_entities = '', None
|
2018-07-15 12:31:14 +03:00
|
|
|
media.append(types.InputSingleMedia(
|
2019-02-25 20:23:39 +03:00
|
|
|
fm,
|
2018-07-15 12:31:14 +03:00
|
|
|
message=caption,
|
|
|
|
entities=msg_entities
|
2019-11-10 16:56:28 +03:00
|
|
|
# random_id is autogenerated
|
2018-07-15 12:31:14 +03:00
|
|
|
))
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# Now we can construct the multi-media request
|
2019-11-10 16:56:28 +03:00
|
|
|
request = functions.messages.SendMultiMediaRequest(
|
2023-07-24 18:23:09 +03:00
|
|
|
entity, reply_to=None if reply_to is None else types.InputReplyToMessage(reply_to), multi_media=media,
|
2021-08-05 11:54:07 +03:00
|
|
|
silent=silent, schedule_date=schedule, clear_draft=clear_draft,
|
|
|
|
background=background
|
2019-11-10 16:56:28 +03:00
|
|
|
)
|
|
|
|
result = await self(request)
|
2019-04-09 15:48:36 +03:00
|
|
|
|
2019-11-10 16:56:28 +03:00
|
|
|
random_ids = [m.random_id for m in media]
|
|
|
|
return self._get_response_message(random_ids, result, entity)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
async def upload_file(
|
2019-05-03 22:37:27 +03:00
|
|
|
self: 'TelegramClient',
|
2019-05-08 18:16:09 +03:00
|
|
|
file: 'hints.FileLike',
|
2019-05-03 22:37:27 +03:00
|
|
|
*,
|
|
|
|
part_size_kb: float = None,
|
2020-07-15 15:35:42 +03:00
|
|
|
file_size: int = None,
|
2019-05-03 22:37:27 +03:00
|
|
|
file_name: str = None,
|
|
|
|
use_cache: type = None,
|
2020-03-04 18:12:34 +03:00
|
|
|
key: bytes = None,
|
|
|
|
iv: bytes = None,
|
2019-05-08 18:16:09 +03:00
|
|
|
progress_callback: 'hints.ProgressCallback' = None) -> 'types.TypeInputFile':
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Uploads a file to Telegram's servers, without sending it.
|
|
|
|
|
2020-02-28 13:50:16 +03:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
Generally, you want to use `send_file` instead.
|
|
|
|
|
2019-05-06 12:38:26 +03:00
|
|
|
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).
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-09 23:05:06 +03:00
|
|
|
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).
|
|
|
|
|
2020-07-15 15:35:42 +03:00
|
|
|
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.
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
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``
|
2019-07-06 13:10:25 +03:00
|
|
|
and if this is not a `str`, it will be ``"unnamed"``.
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-12-25 18:50:11 +03:00
|
|
|
use_cache (`type`, optional):
|
2019-09-27 16:12:17 +03:00
|
|
|
This parameter currently does nothing, but is kept for
|
|
|
|
backward-compatibility (and it may get its use back in
|
|
|
|
the future).
|
2018-12-25 18:50:11 +03:00
|
|
|
|
2020-03-04 18:12:34 +03:00
|
|
|
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
|
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
progress_callback (`callable`, optional):
|
|
|
|
A callback function accepting two parameters:
|
|
|
|
``(sent bytes, total)``.
|
|
|
|
|
2023-03-28 19:15:57 +03:00
|
|
|
When sending an album, the callback will receive a number
|
|
|
|
between 0 and the amount of files as the "sent" parameter,
|
|
|
|
and the amount of files as the "total". Note that the first
|
|
|
|
parameter will be a floating point number to indicate progress
|
|
|
|
within a file (e.g. ``2.5`` means it has sent 50% of the third
|
|
|
|
file, because it's between 2 and 3).
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-09 23:05:06 +03:00
|
|
|
:tl:`InputFileBig` if the file size is larger than 10MB,
|
2019-06-01 17:27:53 +03:00
|
|
|
`InputSizedFile <telethon.tl.custom.inputsizedfile.InputSizedFile>`
|
2018-06-09 23:05:06 +03:00
|
|
|
(subclass of :tl:`InputFile`) otherwise.
|
2019-05-09 13:24:37 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
2019-05-09 13:24:37 +03:00
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# Photos as photo and document
|
2019-08-14 00:33:39 +03:00
|
|
|
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
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
file.name = 'not a photo.jpg'
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.send_file(chat, file, force_document=True) # document, new name
|
2019-05-09 13:24:37 +03:00
|
|
|
|
|
|
|
# As song or as voice note
|
2019-08-14 00:33:39 +03:00
|
|
|
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
|
2018-06-09 23:05:06 +03:00
|
|
|
"""
|
|
|
|
if isinstance(file, (types.InputFile, types.InputFileBig)):
|
|
|
|
return file # Already uploaded
|
|
|
|
|
2020-07-15 15:35:42 +03:00
|
|
|
pos = 0
|
2020-09-14 17:20:44 +03:00
|
|
|
async with helpers._FileStream(file, file_size=file_size) as stream:
|
|
|
|
# Opening the stream will determine the correct file size
|
|
|
|
file_size = stream.file_size
|
|
|
|
|
|
|
|
if not part_size_kb:
|
|
|
|
part_size_kb = utils.get_appropriated_part_size(file_size)
|
|
|
|
|
|
|
|
if part_size_kb > 512:
|
|
|
|
raise ValueError('The part size must be less or equal to 512KB')
|
|
|
|
|
|
|
|
part_size = int(part_size_kb * 1024)
|
|
|
|
if part_size % 1024 != 0:
|
|
|
|
raise ValueError(
|
|
|
|
'The part size must be evenly divisible by 1024')
|
|
|
|
|
|
|
|
# Set a default file name if None was specified
|
|
|
|
file_id = helpers.generate_random_long()
|
|
|
|
if not file_name:
|
|
|
|
file_name = stream.name or str(file_id)
|
|
|
|
|
|
|
|
# If the file name lacks extension, add it if possible.
|
|
|
|
# Else Telegram complains with `PHOTO_EXT_INVALID_ERROR`
|
|
|
|
# even if the uploaded image is indeed a photo.
|
|
|
|
if not os.path.splitext(file_name)[-1]:
|
|
|
|
file_name += utils._get_extension(stream)
|
|
|
|
|
|
|
|
# Determine whether the file is too big (over 10MB) or not
|
|
|
|
# Telegram does make a distinction between smaller or larger files
|
|
|
|
is_big = file_size > 10 * 1024 * 1024
|
|
|
|
hash_md5 = hashlib.md5()
|
|
|
|
|
|
|
|
part_count = (file_size + part_size - 1) // part_size
|
|
|
|
self._log[__name__].info('Uploading file of %d bytes in %d chunks of %d',
|
2024-10-05 12:13:20 +03:00
|
|
|
file_size, part_count, part_size)
|
2020-09-14 17:20:44 +03:00
|
|
|
|
|
|
|
pos = 0
|
2018-06-09 23:05:06 +03:00
|
|
|
for part_index in range(part_count):
|
|
|
|
# Read the file by in chunks of size part_size
|
2020-07-15 15:35:42 +03:00
|
|
|
part = await helpers._maybe_await(stream.read(part_size))
|
|
|
|
|
|
|
|
if not isinstance(part, bytes):
|
|
|
|
raise TypeError(
|
|
|
|
'file descriptor returned {}, not bytes (you must '
|
|
|
|
'open the file in bytes mode)'.format(type(part)))
|
|
|
|
|
|
|
|
# `file_size` could be wrong in which case `part` may not be
|
|
|
|
# `part_size` before reaching the end.
|
|
|
|
if len(part) != part_size and part_index < part_count - 1:
|
|
|
|
raise ValueError(
|
|
|
|
'read less than {} before reaching the end; either '
|
|
|
|
'`file_size` or `read` are wrong'.format(part_size))
|
|
|
|
|
|
|
|
pos += len(part)
|
|
|
|
|
2021-04-10 22:46:14 +03:00
|
|
|
# Encryption part if needed
|
|
|
|
if key and iv:
|
|
|
|
part = AES.encrypt_ige(part, key, iv)
|
|
|
|
|
2020-07-15 15:35:42 +03:00
|
|
|
if not is_big:
|
|
|
|
# Bit odd that MD5 is only needed for small files and not
|
|
|
|
# big ones with more chance for corruption, but that's
|
|
|
|
# what Telegram wants.
|
|
|
|
hash_md5.update(part)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# The SavePartRequest is different depending on whether
|
|
|
|
# the file is too large or not (over or less than 10MB)
|
2020-07-15 15:35:42 +03:00
|
|
|
if is_big:
|
2018-06-09 23:05:06 +03:00
|
|
|
request = functions.upload.SaveBigFilePartRequest(
|
|
|
|
file_id, part_index, part_count, part)
|
|
|
|
else:
|
|
|
|
request = functions.upload.SaveFilePartRequest(
|
|
|
|
file_id, part_index, part)
|
|
|
|
|
|
|
|
result = await self(request)
|
|
|
|
if result:
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].debug('Uploaded %d/%d',
|
|
|
|
part_index + 1, part_count)
|
2018-06-09 23:05:06 +03:00
|
|
|
if progress_callback:
|
2020-07-15 15:35:42 +03:00
|
|
|
await helpers._maybe_await(progress_callback(pos, file_size))
|
2018-06-09 23:05:06 +03:00
|
|
|
else:
|
|
|
|
raise RuntimeError(
|
|
|
|
'Failed to upload file part {}.'.format(part_index))
|
|
|
|
|
2020-07-15 15:35:42 +03:00
|
|
|
if is_big:
|
2018-06-09 23:05:06 +03:00
|
|
|
return types.InputFileBig(file_id, part_count, file_name)
|
|
|
|
else:
|
|
|
|
return custom.InputSizedFile(
|
|
|
|
file_id, part_count, file_name, md5=hash_md5, size=file_size
|
|
|
|
)
|
|
|
|
|
|
|
|
# endregion
|
|
|
|
|
|
|
|
async def _file_to_media(
|
2020-07-15 15:35:42 +03:00
|
|
|
self, file, force_document=False, file_size=None,
|
2018-06-09 23:05:06 +03:00
|
|
|
progress_callback=None, attributes=None, thumb=None,
|
2019-01-21 21:46:33 +03:00
|
|
|
allow_cache=True, voice_note=False, video_note=False,
|
2021-09-11 12:02:19 +03:00
|
|
|
supports_streaming=False, mime_type=None, as_image=None,
|
2023-04-14 23:03:03 +03:00
|
|
|
ttl=None, nosound_video=None):
|
2018-06-09 23:05:06 +03:00
|
|
|
if not file:
|
2019-03-06 11:38:17 +03:00
|
|
|
return None, None, None
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-16 18:01:20 +03:00
|
|
|
if isinstance(file, pathlib.Path):
|
|
|
|
file = str(file.absolute())
|
|
|
|
|
2020-08-10 17:09:39 +03:00
|
|
|
is_image = utils.is_image(file)
|
2019-05-01 17:02:21 +03:00
|
|
|
if as_image is None:
|
2020-08-10 17:09:39 +03:00
|
|
|
as_image = is_image and not force_document
|
2019-02-13 14:33:11 +03:00
|
|
|
|
2019-12-27 14:04:08 +03:00
|
|
|
# `aiofiles` do not base `io.IOBase` but do have `read`, so we
|
|
|
|
# just check for the read attribute to see if it's file-like.
|
2024-10-05 12:13:20 +03:00
|
|
|
if not isinstance(file, (str, bytes, types.InputFile, types.InputFileBig)) \
|
2020-03-14 14:16:52 +03:00
|
|
|
and not hasattr(file, 'read'):
|
2018-06-09 23:05:06 +03:00
|
|
|
# The user may pass a Message containing media (or the media,
|
|
|
|
# or anything similar) that should be treated as a file. Try
|
|
|
|
# getting the input media for whatever they passed and send it.
|
2019-02-13 14:33:11 +03:00
|
|
|
#
|
|
|
|
# We pass all attributes since these will be used if the user
|
|
|
|
# passed :tl:`InputFile`, and all information may be relevant.
|
2018-06-09 23:05:06 +03:00
|
|
|
try:
|
2019-02-13 14:33:11 +03:00
|
|
|
return (None, utils.get_input_media(
|
|
|
|
file,
|
|
|
|
is_photo=as_image,
|
|
|
|
attributes=attributes,
|
|
|
|
force_document=force_document,
|
|
|
|
voice_note=voice_note,
|
|
|
|
video_note=video_note,
|
2021-09-11 12:02:19 +03:00
|
|
|
supports_streaming=supports_streaming,
|
|
|
|
ttl=ttl
|
2019-03-06 11:38:17 +03:00
|
|
|
), as_image)
|
2018-06-09 23:05:06 +03:00
|
|
|
except TypeError:
|
2019-03-06 11:38:17 +03:00
|
|
|
# Can't turn whatever was given into media
|
|
|
|
return None, None, as_image
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-26 17:39:22 +03:00
|
|
|
media = None
|
2018-08-01 00:35:22 +03:00
|
|
|
file_handle = None
|
2020-03-14 14:16:52 +03:00
|
|
|
|
|
|
|
if isinstance(file, (types.InputFile, types.InputFileBig)):
|
|
|
|
file_handle = file
|
|
|
|
elif not isinstance(file, str) or os.path.isfile(file):
|
2018-08-01 00:35:22 +03:00
|
|
|
file_handle = await self.upload_file(
|
2019-02-13 11:50:00 +03:00
|
|
|
_resize_photo_if_needed(file, as_image),
|
2020-07-15 15:35:42 +03:00
|
|
|
file_size=file_size,
|
2019-09-27 16:12:17 +03:00
|
|
|
progress_callback=progress_callback
|
2018-08-01 00:35:22 +03:00
|
|
|
)
|
|
|
|
elif re.match('https?://', file):
|
2018-06-26 17:39:22 +03:00
|
|
|
if as_image:
|
2021-09-11 12:02:19 +03:00
|
|
|
media = types.InputMediaPhotoExternal(file, ttl_seconds=ttl)
|
2018-06-26 17:39:22 +03:00
|
|
|
else:
|
2021-09-11 12:02:19 +03:00
|
|
|
media = types.InputMediaDocumentExternal(file, ttl_seconds=ttl)
|
2018-06-26 17:39:22 +03:00
|
|
|
else:
|
2018-08-01 00:35:22 +03:00
|
|
|
bot_file = utils.resolve_bot_file_id(file)
|
|
|
|
if bot_file:
|
2021-09-11 12:02:19 +03:00
|
|
|
media = utils.get_input_media(bot_file, ttl=ttl)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2018-06-26 17:39:22 +03:00
|
|
|
if media:
|
|
|
|
pass # Already have media, don't check the rest
|
2018-08-06 19:03:42 +03:00
|
|
|
elif not file_handle:
|
|
|
|
raise ValueError(
|
|
|
|
'Failed to convert {} to media. Not an existing file, '
|
|
|
|
'an HTTP URL or a valid bot-API-like file ID'.format(file)
|
|
|
|
)
|
2018-06-09 23:05:06 +03:00
|
|
|
elif as_image:
|
2021-09-11 12:02:19 +03:00
|
|
|
media = types.InputMediaUploadedPhoto(file_handle, ttl_seconds=ttl)
|
2018-06-09 23:05:06 +03:00
|
|
|
else:
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes, mime_type = utils.get_attributes(
|
|
|
|
file,
|
2019-05-01 17:02:21 +03:00
|
|
|
mime_type=mime_type,
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes=attributes,
|
2020-08-10 17:09:39 +03:00
|
|
|
force_document=force_document and not is_image,
|
2018-07-15 12:31:14 +03:00
|
|
|
voice_note=voice_note,
|
2019-01-21 21:46:33 +03:00
|
|
|
video_note=video_note,
|
2021-01-17 19:31:26 +03:00
|
|
|
supports_streaming=supports_streaming,
|
|
|
|
thumb=thumb
|
2018-07-15 12:31:14 +03:00
|
|
|
)
|
2018-06-09 23:05:06 +03:00
|
|
|
|
2020-03-14 14:16:52 +03:00
|
|
|
if not thumb:
|
|
|
|
thumb = None
|
|
|
|
else:
|
|
|
|
if isinstance(thumb, pathlib.Path):
|
|
|
|
thumb = str(thumb.absolute())
|
2020-07-15 15:35:42 +03:00
|
|
|
thumb = await self.upload_file(thumb, file_size=file_size)
|
2020-03-14 14:16:52 +03:00
|
|
|
|
2022-10-15 21:01:29 +03:00
|
|
|
# setting `nosound_video` to `True` doesn't affect videos with sound
|
|
|
|
# instead it prevents sending silent videos as GIFs
|
2023-04-14 23:03:03 +03:00
|
|
|
nosound_video = nosound_video if mime_type.split("/")[0] == 'video' else None
|
2022-10-15 21:01:29 +03:00
|
|
|
|
2018-06-09 23:05:06 +03:00
|
|
|
media = types.InputMediaUploadedDocument(
|
|
|
|
file=file_handle,
|
|
|
|
mime_type=mime_type,
|
2018-07-15 12:31:14 +03:00
|
|
|
attributes=attributes,
|
2020-07-26 14:03:59 +03:00
|
|
|
thumb=thumb,
|
2021-09-11 12:02:19 +03:00
|
|
|
force_file=force_document and not is_image,
|
2022-10-15 21:01:29 +03:00
|
|
|
ttl_seconds=ttl,
|
|
|
|
nosound_video=nosound_video
|
2018-06-09 23:05:06 +03:00
|
|
|
)
|
2019-03-06 11:38:17 +03:00
|
|
|
return file_handle, media, as_image
|
2018-06-09 23:05:06 +03:00
|
|
|
|
|
|
|
# endregion
|