2015-07-10 18:43:35 +02:00
|
|
|
#!/usr/bin/env python
|
2021-10-08 08:17:00 +02:00
|
|
|
# pylint: disable=redefined-builtin, no-name-in-module
|
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
|
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
|
|
|
|
2016-04-25 17:25:10 +02:00
|
|
|
import imghdr
|
2020-11-24 20:31:34 +01:00
|
|
|
import logging
|
2015-07-10 18:43:35 +02:00
|
|
|
import mimetypes
|
2021-10-05 19:50:11 +02:00
|
|
|
from pathlib import Path
|
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
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
from telegram._utils.types import FieldTuple
|
|
|
|
|
|
|
|
_DEFAULT_MIME_TYPE = 'application/octet-stream'
|
2020-11-24 20:31:34 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
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-04-24 12:38:09 +02:00
|
|
|
.. versionchanged:: 14.0
|
|
|
|
The former attribute ``attach`` was renamed to :attr:`attach_name`.
|
|
|
|
|
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>`.
|
|
|
|
|
|
|
|
.. versionchanged:: 14.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
|
|
|
|
2020-12-30 15:59:50 +01:00
|
|
|
Attributes:
|
|
|
|
input_file_content (:obj:`bytes`): 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
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
__slots__ = ('filename', 'attach_name', 'input_file_content', 'mimetype')
|
2021-05-29 16:18:16 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
def __init__(
|
|
|
|
self, obj: Union[IO[bytes], bytes, str], filename: str = None, attach: bool = False
|
|
|
|
):
|
2020-12-18 11:20:03 +01:00
|
|
|
if isinstance(obj, bytes):
|
|
|
|
self.input_file_content = obj
|
2022-04-24 12:38:09 +02:00
|
|
|
elif isinstance(obj, str):
|
|
|
|
self.input_file_content = obj.encode('utf-8')
|
2020-12-18 11:20:03 +01:00
|
|
|
else:
|
|
|
|
self.input_file_content = obj.read()
|
2022-04-24 12:38:09 +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
|
|
|
|
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
|
|
|
|
2020-11-24 20:31:34 +01:00
|
|
|
image_mime_type = self.is_image(self.input_file_content)
|
|
|
|
if image_mime_type:
|
|
|
|
self.mimetype = image_mime_type
|
2021-11-21 12:39:04 +01:00
|
|
|
elif filename:
|
2022-04-24 12:38:09 +02:00
|
|
|
self.mimetype = mimetypes.guess_type(filename)[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
|
|
|
|
2021-11-21 12:39:04 +01:00
|
|
|
self.filename = filename or self.mimetype.replace('/', '.')
|
2015-07-14 10:24:08 +02:00
|
|
|
|
2015-07-13 23:53:30 +02:00
|
|
|
@staticmethod
|
2020-11-24 20:31:34 +01:00
|
|
|
def is_image(stream: bytes) -> Optional[str]:
|
2017-09-01 08:43:08 +02:00
|
|
|
"""Check if the content file is an image by analyzing its headers.
|
2015-07-14 10:24:08 +02:00
|
|
|
|
|
|
|
Args:
|
2020-10-06 19:28:40 +02:00
|
|
|
stream (:obj:`bytes`): A byte stream representing the content of a file.
|
2015-07-14 10:24:08 +02:00
|
|
|
|
|
|
|
Returns:
|
2020-11-24 20:31:34 +01:00
|
|
|
:obj:`str` | :obj:`None`: The mime-type of an image, if the input is an image, or
|
|
|
|
:obj:`None` else.
|
2017-07-23 22:33:08 +02:00
|
|
|
|
2017-09-01 08:43:08 +02:00
|
|
|
"""
|
2020-11-24 20:31:34 +01:00
|
|
|
try:
|
|
|
|
image = imghdr.what(None, stream)
|
|
|
|
if image:
|
|
|
|
return f'image/{image}'
|
|
|
|
return None
|
|
|
|
except Exception:
|
|
|
|
logger.debug(
|
|
|
|
"Could not parse file content. Assuming that file is not an image.", exc_info=True
|
|
|
|
)
|
|
|
|
return None
|
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.
|
|
|
|
|
|
|
|
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
|