aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRapptz <[email protected]>2020-01-03 20:42:45 -0500
committerRapptz <[email protected]>2020-01-03 20:42:45 -0500
commit195b5188e8707d14d8b43aa31c3fc4628e0c370b (patch)
tree5777933510c1e9ed089fbddf4fb1c0e51e5335f4
parentDocument that widget members may be incomplete. (diff)
downloaddiscord.py-195b5188e8707d14d8b43aa31c3fc4628e0c370b.tar.xz
discord.py-195b5188e8707d14d8b43aa31c3fc4628e0c370b.zip
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`.
-rw-r--r--discord/message.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/discord/message.py b/discord/message.py
index 738b06e9..e2ae7193 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 = {