-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
Copy pathutils.py
263 lines (209 loc) · 6.15 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import re
import shlex
import typing
from difflib import get_close_matches
from distutils.util import strtobool as _stb
from itertools import takewhile
from urllib import parse
import discord
from discord.ext import commands
def strtobool(val):
if isinstance(val, bool):
return val
return _stb(str(val))
class User(commands.IDConverter):
"""
A custom discord.py `Converter` that
supports `Member`, `User`, and string ID's.
"""
# noinspection PyCallByClass,PyTypeChecker
async def convert(self, ctx, argument):
try:
return await commands.MemberConverter.convert(self, ctx, argument)
except commands.BadArgument:
pass
try:
return await commands.UserConverter.convert(self, ctx, argument)
except commands.BadArgument:
pass
match = self._get_id_match(argument)
if match is None:
raise commands.BadArgument('User "{}" not found'.format(argument))
return discord.Object(int(match.group(1)))
def truncate(text: str, max: int = 50) -> str: # pylint: disable=redefined-builtin
"""
Reduces the string to `max` length, by trimming the message into "...".
Parameters
----------
text : str
The text to trim.
max : int, optional
The max length of the text.
Defaults to 50.
Returns
-------
str
The truncated text.
"""
return text[: max - 3].strip() + "..." if len(text) > max else text
def format_preview(messages: typing.List[typing.Dict[str, typing.Any]]):
"""
Used to format previews.
Parameters
----------
messages : List[Dict[str, Any]]
A list of messages.
Returns
-------
str
A formatted string preview.
"""
messages = messages[:3]
out = ""
for message in messages:
if message.get("type") in ("note", "internal"):
continue
author = message["author"]
content = str(message["content"]).replace("\n", " ")
name = author["name"] + "#" + str(author["discriminator"])
prefix = "[M]" if author["mod"] else "[R]"
out += truncate(f"`{prefix} {name}:` {content}", max=75) + "\n"
return out or "No Messages"
def is_image_url(url: str) -> bool:
"""
Check if the URL is pointing to an image.
Parameters
----------
url : str
The URL to check.
Returns
-------
bool
Whether the URL is a valid image URL.
"""
return bool(parse_image_url(url))
def parse_image_url(url: str) -> str:
"""
Convert the image URL into a sized Discord avatar.
Parameters
----------
url : str
The URL to convert.
Returns
-------
str
The converted URL, or '' if the URL isn't in the proper format.
"""
types = [".png", ".jpg", ".gif", ".jpeg", ".webp"]
url = parse.urlsplit(url)
if any(url.path.lower().endswith(i) for i in types):
return parse.urlunsplit((*url[:3], "size=128", url[-1]))
return ""
def human_join(strings):
if len(strings) <= 2:
return " or ".join(strings)
return ", ".join(strings[: len(strings) - 1]) + " or " + strings[-1]
def days(day: typing.Union[str, int]) -> str:
"""
Humanize the number of days.
Parameters
----------
day: Union[int, str]
The number of days passed.
Returns
-------
str
A formatted string of the number of days passed.
"""
day = int(day)
if day == 0:
return "**today**"
return f"{day} day ago" if day == 1 else f"{day} days ago"
def cleanup_code(content: str) -> str:
"""
Automatically removes code blocks from the code.
Parameters
----------
content : str
The content to be cleaned.
Returns
-------
str
The cleaned content.
"""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:-1])
# remove `foo`
return content.strip("` \n")
def match_user_id(text: str) -> int:
"""
Matches a user ID in the format of "User ID: 12345".
Parameters
----------
text : str
The text of the user ID.
Returns
-------
int
The user ID if found. Otherwise, -1.
"""
match = re.search(r"\bUser ID: (\d{17,21})\b", text)
if match is not None:
return int(match.group(1))
return -1
def get_perm_level(cmd):
from core.models import PermissionLevel
for check in cmd.checks:
perm = getattr(check, "permission_level", None)
if perm is not None:
return perm
for check in cmd.checks:
if "is_owner" in str(check):
return PermissionLevel.OWNER
return PermissionLevel.INVALID
async def ignore(coro):
try:
await coro
except Exception:
pass
def create_not_found_embed(word, possibilities, name, n=2, cutoff=0.6) -> discord.Embed:
embed = discord.Embed(
color=discord.Color.red(),
description=f"**{name.capitalize()} `{word}` cannot be found.**",
)
val = get_close_matches(word, possibilities, n=n, cutoff=cutoff)
if val:
embed.description += "\nHowever, perhaps you meant...\n" + "\n".join(val)
return embed
def parse_alias(alias):
if "&&" not in alias:
if alias.startswith('"') and alias.endswith('"'):
return [alias[1:-1]]
return [alias]
buffer = ""
cmd = []
try:
for token in shlex.shlex(alias, punctuation_chars="&"):
if token != "&&":
buffer += " " + token
continue
buffer = buffer.strip()
if buffer.startswith('"') and buffer.endswith('"'):
buffer = buffer[1:-1]
cmd += [buffer]
buffer = ""
except ValueError:
return []
buffer = buffer.strip()
if buffer.startswith('"') and buffer.endswith('"'):
buffer = buffer[1:-1]
cmd += [buffer]
if not all(cmd):
return []
return cmd
def format_description(i, names):
return "\n".join(
": ".join((str(a + i * 15), b))
for a, b in enumerate(takewhile(lambda x: x is not None, names), start=1)
)