diff --git a/telegram/file.py b/telegram/file.py index c9c17b77c1e..e0000d440fd 100644 --- a/telegram/file.py +++ b/telegram/file.py @@ -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) diff --git a/telegram/utils/request.py b/telegram/utils/request.py index 0aa071c84d6..3434b352244 100644 --- a/telegram/utils/request.py +++ b/telegram/utils/request.py @@ -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: @@ -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)
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: