X Tutup
Skip to content

Commit c3984e1

Browse files
OctoNezdjh0ker
authored andcommitted
Download changed (python-telegram-bot#459)
* DownBytes added * File.downbyte changed * Changed file.download();Remove downbyte() * Fixed typo * add docstring, make custom_path and out mutually exclusive, rename downbytes to retrieve * remove trailing whitespace * run pre-commit hooks
1 parent a37add3 commit c3984e1

File tree

2 files changed

+35
-9
lines changed

2 files changed

+35
-9
lines changed

telegram/file.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,35 @@ def de_json(data, bot):
6565

6666
return File(bot=bot, **data)
6767

68-
def download(self, custom_path=None):
68+
def download(self, custom_path=None, out=None):
6969
"""
70-
Args:
71-
custom_path (str):
72-
70+
Download this file. By default, the file is saved in the current working directory with its
71+
original filename as reported by Telegram. If a ``custom_path`` is supplied, it will be
72+
saved to that path instead. If ``out`` is defined, the file contents will be saved to that
73+
object using the ``out.write`` method. ``custom_path`` and ``out`` are mutually exclusive.
74+
75+
Keyword Args:
76+
custom_path (Optional[str]): Custom path.
77+
out (Optional[object]): A file-like object. Must be opened in binary mode, if
78+
applicable.
79+
80+
Raises:
81+
ValueError: If both ``custom_path`` and ``out`` are passed.
7382
"""
83+
84+
if custom_path is not None and out is not None:
85+
raise ValueError('custom_path and out are mutually exclusive')
86+
7487
url = self.file_path
7588

76-
if custom_path:
77-
filename = custom_path
89+
if out:
90+
buf = self.bot.request.retrieve(url)
91+
out.write(buf)
92+
7893
else:
79-
filename = basename(url)
94+
if custom_path:
95+
filename = custom_path
96+
else:
97+
filename = basename(url)
8098

81-
self.bot.request.download(url, filename)
99+
self.bot.request.download(url, filename)

telegram/utils/request.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,14 @@ def post(self, url, data, timeout=None):
208208

209209
return self._parse(result)
210210

211+
def retrieve(self, url):
212+
"""Retrieve the contents of a file by its URL.
213+
Args:
214+
url:
215+
The web location we want to retrieve.
216+
"""
217+
return self._request_wrapper('GET', url)
218+
211219
def download(self, url, filename):
212220
"""Download a file by its URL.
213221
Args:
@@ -218,6 +226,6 @@ def download(self, url, filename):
218226
The filename within the path to download the file.
219227
220228
"""
221-
buf = self._request_wrapper('GET', url)
229+
buf = self.retrieve(url)
222230
with open(filename, 'wb') as fobj:
223231
fobj.write(buf)

0 commit comments

Comments
 (0)
X Tutup