-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathutils.py
More file actions
790 lines (642 loc) · 23.3 KB
/
utils.py
File metadata and controls
790 lines (642 loc) · 23.3 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
import base64
import functools
import contextlib
import re
import typing
from datetime import datetime, timezone
from difflib import get_close_matches
from itertools import takewhile, zip_longest
from urllib import parse
import discord
from discord.ext import commands
from core.models import getLogger
__all__ = [
"strtobool",
"User",
"truncate",
"format_preview",
"is_image_url",
"parse_image_url",
"human_join",
"days",
"cleanup_code",
"parse_channel_topic",
"match_title",
"match_user_id",
"match_other_recipients",
"create_thread_channel",
"create_not_found_embed",
"parse_alias",
"normalize_alias",
"format_description",
"trigger_typing",
"safe_typing",
"escape_code_block",
"tryint",
"get_top_role",
"get_joint_id",
"extract_block_timestamp",
"return_or_truncate",
"AcceptButton",
"DenyButton",
"ConfirmThreadCreationView",
"DummyParam",
"extract_forwarded_content",
"extract_forwarded_attachments",
]
logger = getLogger(__name__)
def strtobool(val):
if isinstance(val, bool):
return val
val = str(val).lower()
if val in ("y", "yes", "on", "1", "true", "t", "enable"):
return 1
if val in ("n", "no", "off", "0", "false", "f", "disable"):
return 0
raise ValueError(f"invalid truth value {val}")
class User(commands.MemberConverter):
"""
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(ctx, argument)
except commands.BadArgument:
pass
try:
return await commands.UserConverter().convert(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.
"""
text = text.strip()
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"]
discriminator = str(author["discriminator"])
if discriminator != "0":
name += "#" + 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, **kwargs) -> str:
"""
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.
"""
try:
result = parse.urlparse(url)
if result.netloc == "gyazo.com" and result.scheme in ["http", "https"]:
# gyazo support
url = re.sub(
r"(https?://)((?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|%[0-9a-fA-F][0-9a-fA-F])+)",
r"\1i.\2.png",
url,
)
except ValueError:
pass
return parse_image_url(url, **kwargs)
def parse_image_url(url: str, *, convert_size=True) -> 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):
if convert_size:
return parse.urlunsplit((*url[:3], "size=128", url[-1]))
else:
return parse.urlunsplit(url)
return ""
def human_join(seq: typing.Sequence[str], delim: str = ", ", final: str = "or") -> str:
"""https://github.com/Rapptz/RoboDanny/blob/bf7d4226350dff26df4981dd53134eeb2aceeb87/cogs/utils/formats.py#L21-L32"""
size = len(seq)
if size == 0:
return ""
if size == 1:
return seq[0]
if size == 2:
return f"{seq[0]} {final} {seq[1]}"
return delim.join(seq[:-1]) + f" {final} {seq[-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")
TOPIC_REGEX = re.compile(
r"(?:\bTitle:\s*(?P<title>.*)\n)?"
r"\bUser ID:\s*(?P<user_id>\d{17,21})\b"
r"(?:\nOther Recipients:\s*(?P<other_ids>\d{17,21}(?:(?:\s*,\s*)\d{17,21})*)\b)?",
flags=re.IGNORECASE | re.DOTALL,
)
UID_REGEX = re.compile(r"\bUser ID:\s*(\d{17,21})\b", flags=re.IGNORECASE)
def parse_channel_topic(
text: str,
) -> typing.Tuple[typing.Optional[str], int, typing.List[int]]:
"""
A helper to parse channel topics and respectivefully returns all the required values
at once.
Parameters
----------
text : str
The text of channel topic.
Returns
-------
Tuple[Optional[str], int, List[int]]
A tuple of title, user ID, and other recipients IDs.
"""
title, user_id, other_ids = None, -1, []
if isinstance(text, str):
match = TOPIC_REGEX.search(text)
else:
match = None
if match is not None:
groupdict = match.groupdict()
title = groupdict["title"]
# user ID string is the required one in regex, so if match is found
# the value of this won't be None
user_id = int(groupdict["user_id"])
oth_ids = groupdict["other_ids"]
if oth_ids:
other_ids = list(map(int, oth_ids.split(",")))
return title, user_id, other_ids
def match_title(text: str) -> str:
"""
Matches a title in the format of "Title: XXXX"
Parameters
----------
text : str
The text of the user ID.
Returns
-------
Optional[str]
The title if found.
"""
return parse_channel_topic(text)[0]
def match_user_id(text: str, any_string: bool = False) -> int:
"""
Matches a user ID in the format of "User ID: 12345".
Parameters
----------
text : str
The text of the user ID.
any_string: bool
Whether to search any string that matches the UID_REGEX, e.g. not from channel topic.
Defaults to False.
Returns
-------
int
The user ID if found. Otherwise, -1.
"""
user_id = -1
if any_string:
match = UID_REGEX.search(text)
if match is not None:
user_id = int(match.group(1))
else:
user_id = parse_channel_topic(text)[1]
return user_id
def match_other_recipients(text: str) -> typing.List[int]:
"""
Matches a title in the format of "Other Recipients: XXXX,XXXX"
Parameters
----------
text : str
The text of the user ID.
Returns
-------
List[int]
The list of other recipients IDs.
"""
return parse_channel_topic(text)[2]
def create_not_found_embed(word, possibilities, name, n=2, cutoff=0.6) -> discord.Embed:
# Single reference of Color.red()
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, *, split=True):
def encode_alias(m):
return "\x1aU" + base64.b64encode(m.group(1).encode()).decode() + "\x1aU"
def decode_alias(m):
return base64.b64decode(m.group(1).encode()).decode()
alias = re.sub(
r"(?:(?<=^)(?:\s*(?<!\\)(?:\")\s*)|(?<=&&)(?:\s*(?<!\\)(?:\")\s*))(.+?)"
r"(?:(?:\s*(?<!\\)(?:\")\s*)(?=&&)|(?:\s*(?<!\\)(?:\")\s*)(?=$))",
encode_alias,
alias,
).strip()
aliases = []
if not alias:
return aliases
if split:
iterate = re.split(r"\s*&&\s*", alias)
else:
iterate = [alias]
for a in iterate:
a = re.sub(r"\x1AU(.+?)\x1AU", decode_alias, a)
if a[0] == a[-1] == '"':
a = a[1:-1]
aliases.append(a)
return aliases
def normalize_alias(alias, message=""):
aliases = parse_alias(alias)
contents = parse_alias(message, split=False)
final_aliases = []
for a, content in zip_longest(aliases, contents):
if a is None:
break
if content:
final_aliases.append(f"{a} {content}")
else:
final_aliases.append(a)
return final_aliases
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)
)
class _SafeTyping:
"""Best-effort typing context manager.
Suppresses errors from Discord's typing endpoint so core flows continue
when typing is disabled or experiencing outages.
"""
def __init__(self, target):
# target can be a Context or any Messageable (channel/DM/user)
self._target = target
self._cm = None
async def __aenter__(self):
try:
self._cm = self._target.typing()
return await self._cm.__aenter__()
except Exception:
# typing is best-effort; ignore any failure
self._cm = None
async def __aexit__(self, exc_type, exc, tb):
if self._cm is not None:
with contextlib.suppress(Exception):
return await self._cm.__aexit__(exc_type, exc, tb)
def safe_typing(target):
return _SafeTyping(target)
def trigger_typing(func):
@functools.wraps(func)
async def wrapper(self, ctx: commands.Context, *args, **kwargs):
# Keep typing active for the duration of the command; suppress failures
async with safe_typing(ctx):
return await func(self, ctx, *args, **kwargs)
return wrapper
def escape_code_block(text):
return re.sub(r"```", "`\u200b``", text)
def tryint(x):
try:
return int(x)
except (ValueError, TypeError):
return x
def get_top_role(member: discord.Member, hoisted=True):
roles = sorted(member.roles, key=lambda r: r.position, reverse=True)
for role in roles:
if not hoisted:
return role
if role.hoist:
return role
async def create_thread_channel(bot, recipient, category, overwrites, *, name=None, errors_raised=None):
name = name or bot.format_channel_name(recipient)
errors_raised = errors_raised or []
try:
channel = await bot.modmail_guild.create_text_channel(
name=name,
category=category,
overwrites=overwrites,
topic=f"User ID: {recipient.id}",
reason="Creating a thread channel.",
)
except discord.HTTPException as e:
if (e.text, (category, name)) in errors_raised:
# Just raise the error to prevent infinite recursion after retrying
raise
errors_raised.append((e.text, (category, name)))
if "Maximum number of channels in category reached" in e.text:
fallback = None
fallback_id = bot.config["fallback_category_id"]
if fallback_id:
fallback = discord.utils.get(category.guild.categories, id=int(fallback_id))
if fallback and len(fallback.channels) >= 49:
fallback = None
if not fallback:
fallback = await category.clone(name="Fallback Modmail")
await bot.config.set("fallback_category_id", str(fallback.id))
await bot.config.update()
return await create_thread_channel(
bot, recipient, fallback, overwrites, errors_raised=errors_raised
)
if "Contains words not allowed" in e.text:
# try again but null-discrim (name could be banned)
return await create_thread_channel(
bot,
recipient,
category,
overwrites,
name=bot.format_channel_name(recipient, force_null=True),
errors_raised=errors_raised,
)
raise
return channel
def get_joint_id(message: discord.Message) -> typing.Optional[int]:
"""
Get the joint ID from `discord.Embed().author.url`.
Parameters
-----------
message : discord.Message
The discord.Message object.
Returns
-------
int
The joint ID if found. Otherwise, None.
"""
if message.embeds:
try:
url = getattr(message.embeds[0].author, "url", "")
if url:
return int(url.split("#")[-1])
except ValueError:
pass
return None
def extract_block_timestamp(reason, id_):
# etc "blah blah blah... until <t:XX:f>."
now = discord.utils.utcnow()
end_time = re.search(r"until <t:(\d+):(?:R|f)>.$", reason)
attempts = [
# backwards compat
re.search(r"until ([^`]+?)\.$", reason),
re.search(r"%([^%]+?)%", reason),
]
after = None
if end_time is None:
for i in attempts:
if i is not None:
end_time = i
break
if end_time is not None:
# found a deprecated version
try:
after = (
datetime.fromisoformat(end_time.group(1)).replace(tzinfo=timezone.utc) - now
).total_seconds()
except ValueError:
logger.warning(
r"Broken block message for user %s, block and unblock again with a different message to prevent further issues",
id_,
)
raise
logger.warning(
r"Deprecated time message for user %s, block and unblock again to update.",
id_,
)
else:
try:
after = (
datetime.utcfromtimestamp(int(end_time.group(1))).replace(tzinfo=timezone.utc) - now
).total_seconds()
except ValueError:
logger.warning(
r"Broken block message for user %s, block and unblock again with a different message to prevent further issues",
id_,
)
raise
return end_time, after
def return_or_truncate(text, max_length):
if len(text) <= max_length:
return text
return text[: max_length - 3] + "..."
class AcceptButton(discord.ui.Button):
def __init__(self, custom_id: str, emoji: str):
super().__init__(style=discord.ButtonStyle.gray, emoji=emoji, custom_id=custom_id)
async def callback(self, interaction: discord.Interaction):
self.view.value = True
await interaction.response.edit_message(view=None)
self.view.stop()
class DenyButton(discord.ui.Button):
def __init__(self, custom_id: str, emoji: str):
super().__init__(style=discord.ButtonStyle.gray, emoji=emoji, custom_id=custom_id)
async def callback(self, interaction: discord.Interaction):
self.view.value = False
await interaction.response.edit_message(view=None)
self.view.stop()
class ConfirmThreadCreationView(discord.ui.View):
def __init__(self):
# Match thread_creation_menu_timeout default (30s) for consistency in UX
super().__init__(timeout=30)
self.value = None
def extract_forwarded_attachments(message) -> typing.List[typing.Tuple[str, str]]:
"""
Extract attachment URLs from forwarded messages.
Parameters
----------
message : discord.Message
The message to extract attachments from.
Returns
-------
List[Tuple[str, str]]
List of (url, filename) tuples for attachments.
"""
attachments = []
try:
if hasattr(message, "message_snapshots") and message.message_snapshots:
for snap in message.message_snapshots:
if hasattr(snap, "attachments") and snap.attachments:
for a in snap.attachments:
url = getattr(a, "url", None)
filename = getattr(a, "filename", "Unknown")
if url:
attachments.append((url.split("?")[0], filename))
except Exception:
pass
return attachments
def extract_forwarded_content(message) -> typing.Optional[str]:
"""
Extract forwarded message content from Discord forwarded messages.
Parameters
----------
message : discord.Message
The message to extract forwarded content from.
Returns
-------
Optional[str]
The extracted forwarded content, or None if not a forwarded message.
"""
try:
# Handle multi-forward (message_snapshots)
# Check directly for snapshots as flags.has_snapshot can be unreliable in some versions
if hasattr(message, "message_snapshots") and message.message_snapshots:
forwarded_parts = []
for snap in message.message_snapshots:
# If author is missing, we can try to rely on the container message context or just omit.
# Since we can't reliably get the original author from snapshot in this state, we focus on content.
snap_content = getattr(snap, "content", "")
formatted_part = "📨 **Forwarded Message**\n"
if snap_content:
if len(snap_content) > 500:
snap_content = snap_content[:497] + "..."
formatted_part += "\n".join([f"{line}" for line in snap_content.splitlines()]) + "\n"
if hasattr(snap, "embeds") and snap.embeds:
for embed in snap.embeds:
if hasattr(embed, "description") and embed.description:
embed_desc = embed.description
if len(embed_desc) > 300:
embed_desc = embed_desc[:297] + "..."
formatted_part += (
"\n".join([f"> {line}" for line in embed_desc.splitlines()]) + "\n"
)
break # One embed preview is usually enough
if hasattr(snap, "attachments") and snap.attachments:
attachment_urls = []
for a in snap.attachments[:3]:
url = getattr(a, "url", None)
if url:
# Use direct URL for proper embedding in logviewer
attachment_urls.append(url.split("?")[0])
if len(snap.attachments) > 3:
formatted_part += f"📎 (+{len(snap.attachments) - 3} more attachments)\n"
# Add URLs on separate lines for proper embedding
for url in attachment_urls:
formatted_part += f"{url}\n"
forwarded_parts.append(formatted_part)
if forwarded_parts:
return "\n".join(forwarded_parts)
# Handle single-message forward
elif hasattr(message, "type") and message.type == getattr(discord.MessageType, "forward", None):
ref = getattr(message, "reference", None)
if (
ref
and hasattr(discord, "MessageReferenceType")
and getattr(ref, "type", None) == getattr(discord.MessageReferenceType, "forward", None)
):
try:
ref_msg = getattr(ref, "resolved", None)
if ref_msg:
ref_author = getattr(ref_msg, "author", None)
ref_author_name = getattr(ref_author, "name", "Unknown") if ref_author else "Unknown"
ref_content = getattr(ref_msg, "content", "")
if ref_content:
if len(ref_content) > 500:
ref_content = ref_content[:497] + "..."
return f"**{ref_author_name}:** {ref_content}"
elif hasattr(ref_msg, "embeds") and ref_msg.embeds:
for embed in ref_msg.embeds:
if hasattr(embed, "description") and embed.description:
embed_desc = embed.description
if len(embed_desc) > 300:
embed_desc = embed_desc[:297] + "..."
return f"**{ref_author_name}:** {embed_desc}"
elif hasattr(ref_msg, "attachments") and ref_msg.attachments:
attachment_urls = []
for a in ref_msg.attachments[:3]:
url = getattr(a, "url", None)
if url:
# Use direct URL for proper embedding in logviewer
attachment_urls.append(url.split("?")[0])
result = f"**{ref_author_name}:** 📎\n"
if len(ref_msg.attachments) > 3:
result += f"(+{len(ref_msg.attachments) - 3} more attachments)\n"
# Add URLs on separate lines for proper embedding
for url in attachment_urls:
result += f"{url}\n"
return result
except Exception as e:
# Log and continue; failing to extract a reference preview shouldn't break flow
logger.debug("Failed to extract reference preview: %s", e)
except Exception:
# Silently handle any unexpected errors
pass
return None
class DummyParam:
"""
A dummy parameter that can be used for MissingRequiredArgument.
"""
def __init__(self, name):
self.name = name
self.displayed_name = name