Browse Source

Add Attachment.to_file to easily send an attachment.

The first thing someone will ask when someone sees this method is
"Why doesn't `send` just accept `Attachment`?". This question is fair
but it has an issue: exception propagation becomes confusing.

When we save a file and write it to memory an HTTP request is sent
similar to other API calls. Like all HTTP requests, these can fail.
Since these requests denote failure using HTTPException, if it were to
originate within `send` then it becomes confusing to know whether the
attachment saving itself failed or whether the sending failed.

For that reason, and to keep in-line with only 1 type of HTTP call per
method, it doesn't make sense for `send` to support `Attachment`.
pull/2498/head
Rapptz 5 years ago
parent
commit
195b5188e8
  1. 27
      discord/message.py

27
discord/message.py

@ -39,6 +39,7 @@ from .errors import InvalidArgument, ClientException, HTTPException
from .embeds import Embed
from .member import Member
from .flags import MessageFlags
from .file import File
from .utils import escape_mentions
@ -164,6 +165,32 @@ class Attachment:
data = await self._http.get_from_cdn(url)
return data
async def to_file(self):
"""|coro|
Converts the attachment into a :class:`File` suitable for sending via
:meth:`abc.Messageable.send`.
.. versionadded:: 1.3.0
Raises
------
HTTPException
Downloading the attachment failed.
Forbidden
You do not have permissions to access this attachment
NotFound
The attachment was deleted.
Returns
-------
:class:`File`
The attachment as a file suitable for sending.
"""
data = await self.read()
return File(io.BytesIO(data), filename=self.filename)
def flatten_handlers(cls):
prefix = len('_handle_')
cls._HANDLERS = {

Loading…
Cancel
Save