Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle bytes file input #2233

Merged
merged 7 commits into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions telegram/files/inputfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import logging
import mimetypes
import os
from typing import IO, Optional, Tuple
from typing import IO, Optional, Tuple, Union
from uuid import uuid4

DEFAULT_MIME_TYPE = 'application/octet-stream'
Expand All @@ -39,7 +39,7 @@ class InputFile:
attach (:obj:`str`): Optional. Attach id for sending multiple files.

Args:
obj (:obj:`File handler`): An open file descriptor.
obj (:obj:`File handler` | :obj:`bytes`): An open file descriptor.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The doc string needs to be adapted.

filename (:obj:`str`, optional): Filename for this InputFile.
attach (:obj:`bool`, optional): Whether this should be send as one file or is part of a
collection of files.
Expand All @@ -49,15 +49,18 @@ class InputFile:

"""

def __init__(self, obj: IO, filename: str = None, attach: bool = None):
def __init__(self, obj: Union[IO, bytes], filename: str = None, attach: bool = None):
self.filename = None
self.input_file_content = obj.read()
if isinstance(obj, bytes):
self.input_file_content = obj
else:
self.input_file_content = obj.read()
self.attach = 'attached' + uuid4().hex if attach else None

if filename:
self.filename = filename
elif hasattr(obj, 'name') and not isinstance(obj.name, int):
self.filename = os.path.basename(obj.name)
elif hasattr(obj, 'name') and not isinstance(obj.name, int): # type: ignore[union-attr]
self.filename = os.path.basename(obj.name) # type: ignore[union-attr]

image_mime_type = self.is_image(self.input_file_content)
if image_mime_type:
Expand Down Expand Up @@ -99,6 +102,8 @@ def is_image(stream: bytes) -> Optional[str]:

@staticmethod
def is_file(obj: object) -> bool:
if isinstance(obj, bytes):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well. It's not accurate that it's a file
What are the implications of reverting this change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could make this check in parse_file_input instead. yeah, maybe the cleaner idea.

return True
return hasattr(obj, 'read')

def to_dict(self) -> Optional[str]:
Expand Down
2 changes: 1 addition & 1 deletion telegram/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def parse_file_input(
return file_input
if isinstance(file_input, (str, Path)):
if is_local_file(file_input):
out = f'file://{Path(file_input).absolute()}'
out = Path(file_input).absolute().as_uri()
else:
out = file_input # type: ignore[assignment]
return out
Expand Down
11 changes: 11 additions & 0 deletions tests/test_inputfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,14 @@ def read(self):
InputFile(MockedFileobject('tests/data/telegram'), filename='blah.jpg').filename
== 'blah.jpg'
)

def test_send_bytes(self, bot, chat_id):
# We test this here and not at the respective test modules because it's not worth
# duplicating the test for the different methods
with open('tests/data/text_file.txt', 'rb') as file:
message = bot.send_document(chat_id, file.read())

out = BytesIO()
assert message.document.get_file().download(out=out)
out.seek(0)
assert out.read().decode('utf-8') == 'PTB Rocks!'