Skip to content

fix download without path arguments #1591

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 8 additions & 4 deletions telegram/files/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"""This module contains an object that represents a Telegram File."""
from base64 import b64decode
from os.path import basename
import os

from future.backports.urllib import parse as urllib_parse

Expand Down Expand Up @@ -76,9 +77,10 @@ def de_json(cls, data, bot):
def download(self, custom_path=None, out=None, timeout=None):
"""
Download this file. By default, the file is saved in the current working directory with its
original filename as reported by Telegram. If a :attr:`custom_path` is supplied, it will be
saved to that path instead. If :attr:`out` is defined, the file contents will be saved to
that object using the ``out.write`` method.
original filename as reported by Telegram. If the file has no filename, it the file ID will
be used as filename. If a :attr:`custom_path` is supplied, it will be saved to that path
instead. If :attr:`out` is defined, the file contents will be saved to that object using
the ``out.write`` method.

Note:
:attr:`custom_path` and :attr:`out` are mutually exclusive.
Expand Down Expand Up @@ -116,8 +118,10 @@ def download(self, custom_path=None, out=None, timeout=None):
else:
if custom_path:
filename = custom_path
else:
elif self.file_path:
filename = basename(self.file_path)
else:
filename = os.path.join(os.getcwd(), self.file_id)

buf = self.bot.request.retrieve(url, timeout=timeout)
if self._credentials:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ def test(*args, **kwargs):
os.close(file_handle)
os.unlink(custom_path)

def test_download_no_filename(self, monkeypatch, file):
def test(*args, **kwargs):
return self.file_content

file.file_path = None

monkeypatch.setattr('telegram.utils.request.Request.retrieve', test)
out_file = file.download()

assert out_file[-len(file.file_id):] == file.file_id
try:
with open(out_file, 'rb') as fobj:
assert fobj.read() == self.file_content
finally:
os.unlink(out_file)

def test_download_file_obj(self, monkeypatch, file):
def test(*args, **kwargs):
return self.file_content
Expand Down