2015-07-10 18:43:35 +02:00
|
|
|
#!/usr/bin/env python
|
2015-08-11 21:58:17 +02:00
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2024-02-19 20:06:25 +01:00
|
|
|
# Copyright (C) 2015-2024
|
2016-01-05 14:12:03 +01:00
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
2015-08-11 21:58:17 +02:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program 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 Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2016-10-17 00:22:40 +02:00
|
|
|
"""This module contains an object that represents a Telegram InputFile."""
|
2015-08-10 18:57:31 +02:00
|
|
|
|
2015-07-10 18:43:35 +02:00
|
|
|
import mimetypes
|
2022-04-24 12:38:09 +02:00
|
|
|
from typing import IO, Optional, Union
|
Bot API 4.0 (#1168)
Telegram Passport (#1174):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
- PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (#1184):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
- Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
|
|
|
from uuid import uuid4
|
2016-04-25 17:25:10 +02:00
|
|
|
|
2024-08-02 22:28:38 +02:00
|
|
|
from telegram._utils.files import guess_file_name, load_file
|
2024-07-21 21:13:30 +02:00
|
|
|
from telegram._utils.strings import TextEncoding
|
2022-04-24 12:38:09 +02:00
|
|
|
from telegram._utils.types import FieldTuple
|
|
|
|
|
|
|
|
_DEFAULT_MIME_TYPE = "application/octet-stream"
|
2015-07-14 10:24:08 +02:00
|
|
|
|
2015-07-10 18:43:35 +02:00
|
|
|
|
2020-06-15 18:20:51 +02:00
|
|
|
class InputFile:
|
2017-09-01 08:43:08 +02:00
|
|
|
"""This object represents a Telegram InputFile.
|
2017-07-23 22:33:08 +02:00
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionchanged:: 20.0
|
2022-05-29 14:35:26 +02:00
|
|
|
|
|
|
|
* The former attribute ``attach`` was renamed to :attr:`attach_name`.
|
|
|
|
* Method ``is_image`` was removed. If you pass :obj:`bytes` to :paramref:`obj` and would
|
|
|
|
like to have the mime type automatically guessed, please pass :paramref:`filename`
|
|
|
|
in addition.
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2017-07-23 22:33:08 +02:00
|
|
|
Args:
|
2022-04-24 12:38:09 +02:00
|
|
|
obj (:term:`file object` | :obj:`bytes` | :obj:`str`): An open file descriptor or the files
|
|
|
|
content as bytes or string.
|
2017-07-23 22:33:08 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
Note:
|
|
|
|
If :paramref:`obj` is a string, it will be encoded as bytes via
|
|
|
|
:external:obj:`obj.encode('utf-8') <str.encode>`.
|
|
|
|
|
2022-05-06 17:15:23 +02:00
|
|
|
.. versionchanged:: 20.0
|
2022-04-24 12:38:09 +02:00
|
|
|
Accept string input.
|
|
|
|
filename (:obj:`str`, optional): Filename for this InputFile.
|
|
|
|
attach (:obj:`bool`, optional): Pass :obj:`True` if the parameter this file belongs to in
|
|
|
|
the request to Telegram should point to the multipart data via an ``attach://`` URI.
|
|
|
|
Defaults to `False`.
|
2024-08-02 22:28:38 +02:00
|
|
|
read_file_handle (:obj:`bool`, optional): If :obj:`True` and :paramref:`obj` is a file
|
|
|
|
handle, the data will be read from the file handle on initialization of this object.
|
|
|
|
If :obj:`False`, the file handle will be passed on to the
|
|
|
|
`networking backend <telegram.request.BaseRequest.do_request>`_ which will have to
|
|
|
|
handle the reading. Defaults to :obj:`True`.
|
|
|
|
|
|
|
|
Tip:
|
|
|
|
If you upload extremely large files, you may want to set this to :obj:`False` to
|
|
|
|
avoid reading the complete file into memory. Additionally, this may be supported
|
|
|
|
better by the networking backend (in particular it is handled better by
|
|
|
|
the default :class:`~telegram.request.HTTPXRequest`).
|
|
|
|
|
|
|
|
Important:
|
|
|
|
If you set this to :obj:`False`, you have to ensure that the file handle is still
|
|
|
|
open when the request is made. In particular, the following snippet can *not* work
|
|
|
|
as expected.
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
with open('file.txt', 'rb') as file:
|
|
|
|
input_file = InputFile(file, read_file_handle=False)
|
|
|
|
|
|
|
|
# here the file handle is already closed and the upload will fail
|
|
|
|
await bot.send_document(chat_id, input_file)
|
|
|
|
|
2024-09-01 15:25:34 +02:00
|
|
|
.. versionadded:: 21.5
|
2024-08-02 22:28:38 +02:00
|
|
|
|
2017-09-01 08:43:08 +02:00
|
|
|
|
2020-12-30 15:59:50 +01:00
|
|
|
Attributes:
|
2024-08-02 22:28:38 +02:00
|
|
|
input_file_content (:obj:`bytes` | :class:`IO`): The binary content of the file to send.
|
2022-04-24 12:38:09 +02:00
|
|
|
attach_name (:obj:`str`): Optional. If present, the parameter this file belongs to in
|
|
|
|
the request to Telegram should point to the multipart data via a an URI of the form
|
|
|
|
``attach://<attach_name>`` URI.
|
|
|
|
filename (:obj:`str`): Filename for the file to be sent.
|
|
|
|
mimetype (:obj:`str`): The mimetype inferred from the file to be sent.
|
2020-12-30 15:59:50 +01:00
|
|
|
|
2017-07-23 22:33:08 +02:00
|
|
|
"""
|
2015-08-22 04:15:29 +02:00
|
|
|
|
2024-02-05 19:24:00 +01:00
|
|
|
__slots__ = ("attach_name", "filename", "input_file_content", "mimetype")
|
2021-05-29 16:18:16 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
def __init__(
|
2023-05-18 07:57:59 +02:00
|
|
|
self,
|
|
|
|
obj: Union[IO[bytes], bytes, str],
|
|
|
|
filename: Optional[str] = None,
|
|
|
|
attach: bool = False,
|
2024-08-02 22:28:38 +02:00
|
|
|
read_file_handle: bool = True,
|
2022-04-24 12:38:09 +02:00
|
|
|
):
|
2020-12-18 11:20:03 +01:00
|
|
|
if isinstance(obj, bytes):
|
2024-08-02 22:28:38 +02:00
|
|
|
self.input_file_content: Union[bytes, IO[bytes]] = obj
|
2022-04-24 12:38:09 +02:00
|
|
|
elif isinstance(obj, str):
|
2024-07-21 21:13:30 +02:00
|
|
|
self.input_file_content = obj.encode(TextEncoding.UTF_8)
|
2024-08-02 22:28:38 +02:00
|
|
|
elif read_file_handle:
|
2022-09-19 22:31:23 +02:00
|
|
|
reported_filename, self.input_file_content = load_file(obj)
|
|
|
|
filename = filename or reported_filename
|
2024-08-02 22:28:38 +02:00
|
|
|
else:
|
|
|
|
self.input_file_content = obj
|
|
|
|
filename = filename or guess_file_name(obj)
|
Bot API 4.0 (#1168)
Telegram Passport (#1174):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
- PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (#1184):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
- Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
|
|
|
|
2022-09-19 22:31:23 +02:00
|
|
|
self.attach_name: Optional[str] = "attached" + uuid4().hex if attach else None
|
Bot API 4.0 (#1168)
Telegram Passport (#1174):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
- PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (#1184):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
- Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
|
|
|
|
2022-05-29 14:35:26 +02:00
|
|
|
if filename:
|
2023-02-02 18:55:07 +01:00
|
|
|
self.mimetype: str = (
|
|
|
|
mimetypes.guess_type(filename, strict=False)[0] or _DEFAULT_MIME_TYPE
|
|
|
|
)
|
2020-11-24 20:31:34 +01:00
|
|
|
else:
|
2022-04-24 12:38:09 +02:00
|
|
|
self.mimetype = _DEFAULT_MIME_TYPE
|
2020-11-24 20:31:34 +01:00
|
|
|
|
2023-02-02 18:55:07 +01:00
|
|
|
self.filename: str = filename or self.mimetype.replace("/", ".")
|
2015-07-14 10:24:08 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
@property
|
|
|
|
def field_tuple(self) -> FieldTuple:
|
|
|
|
"""Field tuple representing the contents of the file for upload to the Telegram servers.
|
|
|
|
|
2024-09-01 15:25:34 +02:00
|
|
|
.. versionchanged:: 21.5
|
2024-08-02 22:28:38 +02:00
|
|
|
Content may now be a file handle.
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
Returns:
|
2024-08-02 22:28:38 +02:00
|
|
|
Tuple[:obj:`str`, :obj:`bytes` | :class:`IO`, :obj:`str`]:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""
|
|
|
|
return self.filename, self.input_file_content, self.mimetype
|
|
|
|
|
|
|
|
@property
|
|
|
|
def attach_uri(self) -> Optional[str]:
|
|
|
|
"""URI to insert into the JSON data for uploading the file. Returns :obj:`None`, if
|
|
|
|
:attr:`attach_name` is :obj:`None`.
|
|
|
|
"""
|
|
|
|
return f"attach://{self.attach_name}" if self.attach_name else None
|