Skip to content
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

Add read method to attachment objects #2118

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 37 additions & 2 deletions discord/message.py
Expand Up @@ -112,8 +112,7 @@ async def save(self, fp, *, seek_begin=True, use_cached=False):
: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:
Expand All @@ -123,6 +122,42 @@ async def save(self, fp, *, seek_begin=True, use_cached=False):
with open(fp, 'wb') as f:
Vexs marked this conversation as resolved.
Show resolved Hide resolved
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.

Expand Down