Skip to content
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
34 changes: 26 additions & 8 deletions telegram/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,35 @@ def de_json(data, bot):

return File(bot=bot, **data)

def download(self, custom_path=None):
def download(self, custom_path=None, out=None):
"""
Args:
custom_path (str):

Download this file. By default, the file is saved in the current working directory with its
original filename as reported by Telegram. If a ``custom_path`` is supplied, it will be
saved to that path instead. If ``out`` is defined, the file contents will be saved to that
object using the ``out.write`` method. ``custom_path`` and ``out`` are mutually exclusive.

Keyword Args:
custom_path (Optional[str]): Custom path.
out (Optional[object]): A file-like object. Must be opened in binary mode, if
applicable.

Raises:
ValueError: If both ``custom_path`` and ``out`` are passed.
"""

if custom_path is not None and out is not None:
raise ValueError('custom_path and out are mutually exclusive')

url = self.file_path

if custom_path:
filename = custom_path
if out:
buf = self.bot.request.retrieve(url)
out.write(buf)

else:
filename = basename(url)
if custom_path:
filename = custom_path
else:
filename = basename(url)

self.bot.request.download(url, filename)
self.bot.request.download(url, filename)
10 changes: 9 additions & 1 deletion telegram/utils/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ def post(self, url, data, timeout=None):

return self._parse(result)

def retrieve(self, url):
"""Retrieve the contents of a file by its URL.
Args:
url:
The web location we want to retrieve.
"""
return self._request_wrapper('GET', url)

def download(self, url, filename):
"""Download a file by its URL.
Args:
Expand All @@ -216,6 +224,6 @@ def download(self, url, filename):
The filename within the path to download the file.

"""
buf = self._request_wrapper('GET', url)
buf = self.retrieve(url)
with open(filename, 'wb') as fobj:
fobj.write(buf)