python-telegram-bot/telegram/_files/inputfile.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

110 lines
4.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2015-08-11 21:58:17 +02:00
#
# A library that provides a Python interface to the Telegram Bot API
2022-01-03 08:15:18 +01:00
# Copyright (C) 2015-2022
# 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
import logging
import mimetypes
from pathlib import Path
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
from telegram._utils.types import FieldTuple
_DEFAULT_MIME_TYPE = "application/octet-stream"
logger = logging.getLogger(__name__)
class InputFile:
2017-09-01 08:43:08 +02:00
"""This object represents a Telegram InputFile.
.. 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.
Args:
obj (:term:`file object` | :obj:`bytes` | :obj:`str`): An open file descriptor or the files
content as bytes or string.
Note:
If :paramref:`obj` is a string, it will be encoded as bytes via
:external:obj:`obj.encode('utf-8') <str.encode>`.
.. versionchanged:: 20.0
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`.
2017-09-01 08:43:08 +02:00
Attributes:
input_file_content (:obj:`bytes`): The binary content of the file to send.
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.
"""
__slots__ = ("filename", "attach_name", "input_file_content", "mimetype")
def __init__(
self, obj: Union[IO[bytes], bytes, str], filename: str = None, attach: bool = False
):
if isinstance(obj, bytes):
self.input_file_content = obj
elif isinstance(obj, str):
self.input_file_content = obj.encode("utf-8")
else:
self.input_file_content = obj.read()
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
2021-11-21 12:39:04 +01:00
if (
not filename
and hasattr(obj, "name")
and not isinstance(obj.name, int) # type: ignore[union-attr]
):
filename = Path(obj.name).name # type: ignore[union-attr]
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:
self.mimetype = mimetypes.guess_type(filename, strict=False)[0] or _DEFAULT_MIME_TYPE
else:
self.mimetype = _DEFAULT_MIME_TYPE
2021-11-21 12:39:04 +01:00
self.filename = filename or self.mimetype.replace("/", ".")
@property
def field_tuple(self) -> FieldTuple:
"""Field tuple representing the contents of the file for upload to the Telegram servers.
Returns:
Tuple[:obj:`str`, :obj:`bytes`, :obj:`str`]:
"""
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