From 195b5188e8707d14d8b43aa31c3fc4628e0c370b Mon Sep 17 00:00:00 2001 From: Rapptz Date: Fri, 3 Jan 2020 20:42:45 -0500 Subject: [PATCH] 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`. --- discord/message.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/discord/message.py b/discord/message.py index 738b06e97..e2ae71930 100644 --- a/discord/message.py +++ b/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 = {