From 7dfaa5e9aecc4b8551e258a8bce377c27fe2731d Mon Sep 17 00:00:00 2001 From: Vexs Date: Fri, 26 Apr 2019 00:49:13 -0500 Subject: [PATCH] Add read method to attachment objects Refactor save to use new read method --- discord/message.py | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/discord/message.py b/discord/message.py index c82c5d183..980a38a2a 100644 --- a/discord/message.py +++ b/discord/message.py @@ -112,8 +112,7 @@ class Attachment: :class:`int` The number of bytes written. """ - url = self.proxy_url if use_cached else self.url - data = await self._http.get_from_cdn(url) + data = await self.read(use_cached=use_cached) if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: @@ -123,6 +122,42 @@ class Attachment: with open(fp, 'wb') as f: return f.write(data) + async def read(self, *, use_cached=False): + """|coro| + + Retrieves the content of this attachment as a :class:`bytes` object. + + Parameters + ----------- + use_cached: :class:`bool` + Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading + the attachment. This will allow attachments to be saved after deletion + more often, compared to the regular URL which is generally deleted right + after the message is deleted. Note that this can still fail to download + deleted attachments if too much time has passed and it does not work + on some type of attachments. + + .. versionadded:: 1.1.0 + + Raises + ------ + HTTPException + Downloading the attachment failed. + Forbidden + You do not have permissions to access this attachment + NotFound + The attachment was deleted. + + Returns + ------- + :class:`bytes` + The contents of the attachment. + """ + url = self.proxy_url if use_cached else self.url + data = await self._http.get_from_cdn(url) + return data + + class Message: r"""Represents a message from Discord.