1
|
|
|
# Copyright Pincer 2021-Present |
|
|
|
|
2
|
|
|
# Full MIT License can be found in `LICENSE` at the project root. |
3
|
|
|
|
4
|
|
|
from __future__ import annotations |
5
|
|
|
|
6
|
|
|
from dataclasses import dataclass |
7
|
|
|
from json import dumps |
8
|
|
|
from typing import Dict, Tuple, Union, List, Optional, TYPE_CHECKING |
9
|
|
|
|
10
|
|
|
from aiohttp import FormData, Payload |
11
|
|
|
|
12
|
|
|
from ...exceptions import CommandReturnIsEmpty |
13
|
|
|
from ...utils.api_object import APIObject |
|
|
|
|
14
|
|
|
|
15
|
|
|
PILLOW_IMPORT = True |
16
|
|
|
|
17
|
|
|
try: |
18
|
|
|
from PIL.Image import Image |
19
|
|
|
except (ModuleNotFoundError, ImportError): |
20
|
|
|
PILLOW_IMPORT = False |
21
|
|
|
|
22
|
|
|
if TYPE_CHECKING: |
23
|
|
|
from ..guild.role import Role |
24
|
|
|
from ..message.embed import Embed |
25
|
|
|
from ..message.file import File |
26
|
|
|
from ..message.user_message import AllowedMentionTypes |
27
|
|
|
from ..user import User |
28
|
|
|
from ...utils.snowflake import Snowflake |
29
|
|
|
from ..app import InteractionFlags |
30
|
|
|
from .component import MessageComponent |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
@dataclass |
|
|
|
|
34
|
|
|
class AllowedMentions(APIObject): |
35
|
|
|
parse: List[AllowedMentionTypes] |
36
|
|
|
roles: List[Union[Role, Snowflake]] |
37
|
|
|
users: List[Union[User, Snowflake]] |
38
|
|
|
reply: bool = True |
39
|
|
|
|
40
|
|
|
def to_dict(self): |
|
|
|
|
41
|
|
|
def get_str_id(obj: Union[Snowflake, User, Role]) -> str: |
42
|
|
|
if hasattr(obj, "id"): |
43
|
|
|
obj = obj.id |
44
|
|
|
|
45
|
|
|
return str(obj) |
46
|
|
|
|
47
|
|
|
return { |
48
|
|
|
"parse": self.parse, |
49
|
|
|
"roles": list(map(get_str_id, self.roles)), |
50
|
|
|
"users": list(map(get_str_id, self.users)), |
51
|
|
|
"replied_user": self.reply |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
|
55
|
|
|
@dataclass |
|
|
|
|
56
|
|
|
class Message: |
57
|
|
|
# TODO: Docs for tts, allowed_mentions, components, flags, and type. |
|
|
|
|
58
|
|
|
|
59
|
|
|
""" |
60
|
|
|
A discord message that will be send to discord |
61
|
|
|
|
62
|
|
|
:param content: |
63
|
|
|
The text in the message. |
64
|
|
|
|
65
|
|
|
:param attachments: |
66
|
|
|
Attachments on the message. This is a File object. You can also attach |
67
|
|
|
a Pillow Image or string. Pillow images will be converted to PNGs. They |
68
|
|
|
will use the naming sceme ``image%`` where % is the images index in the |
69
|
|
|
attachments array. Strings will be read as a filepath. The name of the |
70
|
|
|
file that the string points to will be used as the name. |
71
|
|
|
|
72
|
|
|
:param embeds: |
73
|
|
|
Embed attached to the message. This is an Embed object. |
74
|
|
|
""" |
75
|
|
|
content: str = '' |
76
|
|
|
attachments: Optional[List[File]] = None |
77
|
|
|
tts: Optional[bool] = False |
78
|
|
|
embeds: Optional[List[Embed]] = None |
79
|
|
|
allowed_mentions: Optional[AllowedMentions] = None |
80
|
|
|
components: Optional[List[MessageComponent]] = None |
81
|
|
|
flags: Optional[InteractionFlags] = None |
82
|
|
|
delete_after: Optional[float] = None |
83
|
|
|
|
84
|
|
|
def __post_init__(self): |
85
|
|
|
if self.delete_after and self.delete_after < 0: |
86
|
|
|
raise ValueError( |
87
|
|
|
"Message can not be deleted after a negative amount of " |
88
|
|
|
"seconds!" |
89
|
|
|
) |
90
|
|
|
|
91
|
|
|
if not self.attachments: |
92
|
|
|
return |
93
|
|
|
|
94
|
|
|
attch = [] |
95
|
|
|
|
96
|
|
|
for count, value in enumerate(self.attachments): |
97
|
|
|
if isinstance(value, File): |
98
|
|
|
attch.append(value) |
99
|
|
|
elif PILLOW_IMPORT and isinstance(value, Image): |
100
|
|
|
attch.append(File.from_pillow_image( |
101
|
|
|
value, |
102
|
|
|
f"image{count}.png", |
103
|
|
|
)) |
104
|
|
|
elif isinstance(value, str): |
105
|
|
|
attch.append(File.from_file(value)) |
106
|
|
|
else: |
107
|
|
|
raise ValueError(f"Attachment {count} is invalid type.") |
108
|
|
|
|
109
|
|
|
self.attachments = attch |
110
|
|
|
|
111
|
|
|
@property |
112
|
|
|
def isempty(self) -> bool: |
113
|
|
|
""" |
114
|
|
|
:return: |
115
|
|
|
Returns true if a message is empty. |
116
|
|
|
""" |
117
|
|
|
|
118
|
|
|
return ( |
119
|
|
|
len(self.content) < 1 |
|
|
|
|
120
|
|
|
and not self.embeds |
|
|
|
|
121
|
|
|
and not self.attachments |
|
|
|
|
122
|
|
|
) |
123
|
|
|
|
124
|
|
|
def to_dict(self): |
|
|
|
|
125
|
|
|
|
126
|
|
|
allowed_mentions = ( |
127
|
|
|
self.allowed_mentions.to_dict() |
128
|
|
|
if self.allowed_mentions else {} |
129
|
|
|
) |
130
|
|
|
|
131
|
|
|
# Attachments aren't serialized |
132
|
|
|
# because they are not sent as part of the json |
133
|
|
|
resp = { |
134
|
|
|
"content": self.content, |
135
|
|
|
"tts": self.tts, |
136
|
|
|
"flags": self.flags, |
137
|
|
|
"embeds": [embed.to_dict() for embed in (self.embeds or [])], |
138
|
|
|
"allowed_mentions": allowed_mentions, |
139
|
|
|
"components": [ |
140
|
|
|
components.to_dict() for components in (self.components or []) |
141
|
|
|
] |
142
|
|
|
} |
143
|
|
|
|
144
|
|
|
# IDE does not recognise return type of filter properly. |
145
|
|
|
# noinspection PyTypeChecker |
146
|
|
|
return dict(filter( |
147
|
|
|
lambda kv: kv[1], |
148
|
|
|
resp.items() |
149
|
|
|
)) |
150
|
|
|
|
151
|
|
|
def serialize(self) -> Tuple[str, Union[Payload, Dict]]: |
152
|
|
|
""" |
153
|
|
|
Creates the data that the discord API wants for the message object |
154
|
|
|
|
155
|
|
|
:return: (content_type, data) |
156
|
|
|
|
157
|
|
|
:raises CommandReturnIsEmpty: |
158
|
|
|
Command does not have content, an embed, or attachment. |
159
|
|
|
""" |
160
|
|
|
|
161
|
|
|
if self.isempty: |
162
|
|
|
raise CommandReturnIsEmpty("Cannot return empty message.") |
163
|
|
|
|
164
|
|
|
if not self.attachments: |
165
|
|
|
return "application/json", self.to_dict() |
166
|
|
|
|
167
|
|
|
form = FormData() |
168
|
|
|
form.add_field("payload_json", dumps(self.to_dict())) |
169
|
|
|
|
170
|
|
|
for file in self.attachments: |
171
|
|
|
form.add_field("file", file.content, filename=file.filename) |
172
|
|
|
|
173
|
|
|
payload = form() |
174
|
|
|
return payload.headers["Content-Type"], payload |
175
|
|
|
|