-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
modmail.py
2018 lines (1701 loc) · 76.3 KB
/
modmail.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
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import re
from datetime import datetime
from itertools import zip_longest
from typing import Optional, Union
from types import SimpleNamespace
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from discord.role import Role
from discord.utils import escape_markdown
from dateutil import parser
from natural.date import duration
from core import checks
from core.models import DMDisabled, PermissionLevel, SimilarCategoryConverter, getLogger
from core.paginator import EmbedPaginatorSession
from core.thread import Thread
from core.time import UserFriendlyTime, human_timedelta
from core.utils import *
logger = getLogger(__name__)
class Modmail(commands.Cog):
"""Commands directly related to Modmail functionality."""
def __init__(self, bot):
self.bot = bot
@commands.command()
@trigger_typing
@checks.has_permissions(PermissionLevel.OWNER)
async def setup(self, ctx):
"""
Sets up a server for Modmail.
You only need to run this command
once after configuring Modmail.
"""
if ctx.guild != self.bot.modmail_guild:
return await ctx.send(f"You can only setup in the Modmail guild: {self.bot.modmail_guild}.")
if self.bot.main_category is not None:
logger.debug("Can't re-setup server, main_category is found.")
return await ctx.send(f"{self.bot.modmail_guild} is already set up.")
if self.bot.modmail_guild is None:
embed = discord.Embed(
title="Error",
description="Modmail functioning guild not found.",
color=self.bot.error_color,
)
return await ctx.send(embed=embed)
overwrites = {
self.bot.modmail_guild.default_role: discord.PermissionOverwrite(read_messages=False),
self.bot.modmail_guild.me: discord.PermissionOverwrite(read_messages=True),
}
for level in PermissionLevel:
if level <= PermissionLevel.REGULAR:
continue
permissions = self.bot.config["level_permissions"].get(level.name, [])
for perm in permissions:
perm = int(perm)
if perm == -1:
key = self.bot.modmail_guild.default_role
else:
key = self.bot.modmail_guild.get_member(perm)
if key is None:
key = self.bot.modmail_guild.get_role(perm)
if key is not None:
logger.info("Granting %s access to Modmail category.", key.name)
overwrites[key] = discord.PermissionOverwrite(read_messages=True)
category = await self.bot.modmail_guild.create_category(name="Modmail", overwrites=overwrites)
await category.edit(position=0)
log_channel = await self.bot.modmail_guild.create_text_channel(name="bot-logs", category=category)
embed = discord.Embed(
title="Friendly Reminder",
description=f"You may use the `{self.bot.prefix}config set log_channel_id "
"<channel-id>` command to set up a custom log channel, then you can delete this default "
f"{log_channel.mention} log channel.",
color=self.bot.main_color,
)
embed.add_field(
name="Thanks for using our bot!",
value="If you like what you see, consider giving the "
"[repo a star](https://github.com/kyb3r/modmail) :star: and if you are "
"feeling extra generous, buy us coffee on [Patreon](https://patreon.com/kyber) :heart:!",
)
embed.set_footer(text=f'Type "{self.bot.prefix}help" for a complete list of commands.')
await log_channel.send(embed=embed)
self.bot.config["main_category_id"] = category.id
self.bot.config["log_channel_id"] = log_channel.id
await self.bot.config.update()
await ctx.send(
"**Successfully set up server.**\n"
"Consider setting permission levels to give access to roles "
"or users the ability to use Modmail.\n\n"
f"Type:\n- `{self.bot.prefix}permissions` and `{self.bot.prefix}permissions add` "
"for more info on setting permissions.\n"
f"- `{self.bot.prefix}config help` for a list of available customizations."
)
if not self.bot.config["command_permissions"] and not self.bot.config["level_permissions"]:
await self.bot.update_perms(PermissionLevel.REGULAR, -1)
for owner_id in self.bot.bot_owner_ids:
await self.bot.update_perms(PermissionLevel.OWNER, owner_id)
@commands.group(aliases=["snippets"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
async def snippet(self, ctx, *, name: str.lower = None):
"""
Create pre-defined messages for use in threads.
When `{prefix}snippet` is used by itself, this will retrieve
a list of snippets that are currently set. `{prefix}snippet-name` will show what the
snippet point to.
To create a snippet:
- `{prefix}snippet add snippet-name A pre-defined text.`
You can use your snippet in a thread channel
with `{prefix}snippet-name`, the message "A pre-defined text."
will be sent to the recipient.
Currently, there is not a built-in anonymous snippet command; however, a workaround
is available using `{prefix}alias`. Here is how:
- `{prefix}alias add snippet-name anonreply A pre-defined anonymous text.`
See also `{prefix}alias`.
"""
if name is not None:
val = self.bot.snippets.get(name)
if val is None:
embed = create_not_found_embed(name, self.bot.snippets.keys(), "Snippet")
else:
embed = discord.Embed(
title=f'Snippet - "{name}":', description=val, color=self.bot.main_color
)
return await ctx.send(embed=embed)
if not self.bot.snippets:
embed = discord.Embed(
color=self.bot.error_color, description="You dont have any snippets at the moment."
)
embed.set_footer(text=f'Check "{self.bot.prefix}help snippet add" to add a snippet.')
embed.set_author(name="Snippets", icon_url=ctx.guild.icon_url)
return await ctx.send(embed=embed)
embeds = []
for i, names in enumerate(zip_longest(*(iter(sorted(self.bot.snippets)),) * 15)):
description = format_description(i, names)
embed = discord.Embed(color=self.bot.main_color, description=description)
embed.set_author(name="Snippets", icon_url=ctx.guild.icon_url)
embeds.append(embed)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@snippet.command(name="raw")
@checks.has_permissions(PermissionLevel.SUPPORTER)
async def snippet_raw(self, ctx, *, name: str.lower):
"""
View the raw content of a snippet.
"""
val = self.bot.snippets.get(name)
if val is None:
embed = create_not_found_embed(name, self.bot.snippets.keys(), "Snippet")
else:
val = truncate(escape_code_block(val), 2048 - 7)
embed = discord.Embed(
title=f'Raw snippet - "{name}":',
description=f"```\n{val}```",
color=self.bot.main_color,
)
return await ctx.send(embed=embed)
@snippet.command(name="add")
@checks.has_permissions(PermissionLevel.SUPPORTER)
async def snippet_add(self, ctx, name: str.lower, *, value: commands.clean_content):
"""
Add a snippet.
Simply to add a snippet, do: ```
{prefix}snippet add hey hello there :)
```
then when you type `{prefix}hey`, "hello there :)" will get sent to the recipient.
To add a multi-word snippet name, use quotes: ```
{prefix}snippet add "two word" this is a two word snippet.
```
"""
if self.bot.get_command(name):
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"A command with the same name already exists: `{name}`.",
)
elif name in self.bot.snippets:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"Snippet `{name}` already exists.",
)
return await ctx.send(embed=embed)
if name in self.bot.aliases:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"An alias that shares the same name exists: `{name}`.",
)
return await ctx.send(embed=embed)
if len(name) > 120:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description="Snippet names cannot be longer than 120 characters.",
)
return await ctx.send(embed=embed)
self.bot.snippets[name] = value
await self.bot.config.update()
embed = discord.Embed(
title="Added snippet",
color=self.bot.main_color,
description="Successfully created snippet.",
)
return await ctx.send(embed=embed)
@snippet.command(name="remove", aliases=["del", "delete"])
@checks.has_permissions(PermissionLevel.SUPPORTER)
async def snippet_remove(self, ctx, *, name: str.lower):
"""Remove a snippet."""
if name in self.bot.snippets:
embed = discord.Embed(
title="Removed snippet",
color=self.bot.main_color,
description=f"Snippet `{name}` is now deleted.",
)
self.bot.snippets.pop(name)
await self.bot.config.update()
else:
embed = create_not_found_embed(name, self.bot.snippets.keys(), "Snippet")
await ctx.send(embed=embed)
@snippet.command(name="edit")
@checks.has_permissions(PermissionLevel.SUPPORTER)
async def snippet_edit(self, ctx, name: str.lower, *, value):
"""
Edit a snippet.
To edit a multi-word snippet name, use quotes: ```
{prefix}snippet edit "two word" this is a new two word snippet.
```
"""
if name in self.bot.snippets:
self.bot.snippets[name] = value
await self.bot.config.update()
embed = discord.Embed(
title="Edited snippet",
color=self.bot.main_color,
description=f'`{name}` will now send "{value}".',
)
else:
embed = create_not_found_embed(name, self.bot.snippets.keys(), "Snippet")
await ctx.send(embed=embed)
@commands.command(usage="<category> [options]")
@checks.has_permissions(PermissionLevel.MODERATOR)
@checks.thread_only()
async def move(self, ctx, *, arguments):
"""
Move a thread to another category.
`category` may be a category ID, mention, or name.
`options` is a string which takes in arguments on how to perform the move. Ex: "silently"
"""
split_args = arguments.strip('"').split(" ")
category = None
# manually parse arguments, consumes as much of args as possible for category
for i in range(len(split_args)):
try:
if i == 0:
fmt = arguments
else:
fmt = " ".join(split_args[:-i])
category = await SimilarCategoryConverter().convert(ctx, fmt)
except commands.BadArgument:
if i == len(split_args) - 1:
# last one
raise
pass
else:
break
if not category:
raise commands.ChannelNotFound(arguments)
options = " ".join(arguments.split(" ")[-i:])
thread = ctx.thread
silent = False
if options:
silent_words = ["silent", "silently"]
silent = any(word in silent_words for word in options.split())
await thread.channel.move(
category=category, end=True, sync_permissions=True, reason=f"{ctx.author} moved this thread."
)
if self.bot.config["thread_move_notify"] and not silent:
embed = discord.Embed(
title=self.bot.config["thread_move_title"],
description=self.bot.config["thread_move_response"],
color=self.bot.main_color,
)
await thread.recipient.send(embed=embed)
if self.bot.config["thread_move_notify_mods"]:
mention = self.bot.config["mention"]
if mention is not None:
msg = f"{mention}, thread has been moved."
else:
msg = "Thread has been moved."
await thread.channel.send(msg)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
async def send_scheduled_close_message(self, ctx, after, silent=False):
human_delta = human_timedelta(after.dt)
silent = "*silently* " if silent else ""
embed = discord.Embed(
title="Scheduled close",
description=f"This thread will close {silent}in {human_delta}.",
color=self.bot.error_color,
)
if after.arg and not silent:
embed.add_field(name="Message", value=after.arg)
embed.set_footer(text="Closing will be cancelled if a thread message is sent.")
embed.timestamp = after.dt
await ctx.send(embed=embed)
@commands.command(usage="[after] [close message]")
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def close(self, ctx, *, after: UserFriendlyTime = None):
"""
Close the current thread.
Close after a period of time:
- `{prefix}close in 5 hours`
- `{prefix}close 2m30s`
Custom close messages:
- `{prefix}close 2 hours The issue has been resolved.`
- `{prefix}close We will contact you once we find out more.`
Silently close a thread (no message)
- `{prefix}close silently`
- `{prefix}close in 10m silently`
Stop a thread from closing:
- `{prefix}close cancel`
"""
thread = ctx.thread
now = datetime.utcnow()
close_after = (after.dt - now).total_seconds() if after else 0
message = after.arg if after else None
silent = str(message).lower() in {"silent", "silently"}
cancel = str(message).lower() == "cancel"
if cancel:
if thread.close_task is not None or thread.auto_close_task is not None:
await thread.cancel_closure(all=True)
embed = discord.Embed(
color=self.bot.error_color, description="Scheduled close has been cancelled."
)
else:
embed = discord.Embed(
color=self.bot.error_color,
description="This thread has not already been scheduled to close.",
)
return await ctx.send(embed=embed)
if after and after.dt > now:
await self.send_scheduled_close_message(ctx, after, silent)
await thread.close(closer=ctx.author, after=close_after, message=message, silent=silent)
@staticmethod
def parse_user_or_role(ctx, user_or_role):
mention = None
if user_or_role is None:
mention = ctx.author.mention
elif hasattr(user_or_role, "mention"):
mention = user_or_role.mention
elif user_or_role in {"here", "everyone", "@here", "@everyone"}:
mention = "@" + user_or_role.lstrip("@")
return mention
@commands.command(aliases=["alert"])
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def notify(self, ctx, *, user_or_role: Union[discord.Role, User, str.lower, None] = None):
"""
Notify a user or role when the next thread message received.
Once a thread message is received, `user_or_role` will be pinged once.
Leave `user_or_role` empty to notify yourself.
`@here` and `@everyone` can be substituted with `here` and `everyone`.
`user_or_role` may be a user ID, mention, name. role ID, mention, name, "everyone", or "here".
"""
mention = self.parse_user_or_role(ctx, user_or_role)
if mention is None:
raise commands.BadArgument(f"{user_or_role} is not a valid user or role.")
thread = ctx.thread
if str(thread.id) not in self.bot.config["notification_squad"]:
self.bot.config["notification_squad"][str(thread.id)] = []
mentions = self.bot.config["notification_squad"][str(thread.id)]
if mention in mentions:
embed = discord.Embed(
color=self.bot.error_color,
description=f"{mention} is already going to be mentioned.",
)
else:
mentions.append(mention)
await self.bot.config.update()
embed = discord.Embed(
color=self.bot.main_color,
description=f"{mention} will be mentioned on the next message received.",
)
return await ctx.send(embed=embed)
@commands.command(aliases=["unalert"])
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def unnotify(self, ctx, *, user_or_role: Union[discord.Role, User, str.lower, None] = None):
"""
Un-notify a user, role, or yourself from a thread.
Leave `user_or_role` empty to un-notify yourself.
`@here` and `@everyone` can be substituted with `here` and `everyone`.
`user_or_role` may be a user ID, mention, name, role ID, mention, name, "everyone", or "here".
"""
mention = self.parse_user_or_role(ctx, user_or_role)
if mention is None:
mention = f"`{user_or_role}`"
thread = ctx.thread
if str(thread.id) not in self.bot.config["notification_squad"]:
self.bot.config["notification_squad"][str(thread.id)] = []
mentions = self.bot.config["notification_squad"][str(thread.id)]
if mention not in mentions:
embed = discord.Embed(
color=self.bot.error_color,
description=f"{mention} does not have a pending notification.",
)
else:
mentions.remove(mention)
await self.bot.config.update()
embed = discord.Embed(
color=self.bot.main_color, description=f"{mention} will no longer be notified."
)
return await ctx.send(embed=embed)
@commands.command(aliases=["sub"])
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def subscribe(self, ctx, *, user_or_role: Union[discord.Role, User, str.lower, None] = None):
"""
Notify a user, role, or yourself for every thread message received.
You will be pinged for every thread message received until you unsubscribe.
Leave `user_or_role` empty to subscribe yourself.
`@here` and `@everyone` can be substituted with `here` and `everyone`.
`user_or_role` may be a user ID, mention, name, role ID, mention, name, "everyone", or "here".
"""
mention = self.parse_user_or_role(ctx, user_or_role)
if mention is None:
raise commands.BadArgument(f"{user_or_role} is not a valid user or role.")
thread = ctx.thread
if str(thread.id) not in self.bot.config["subscriptions"]:
self.bot.config["subscriptions"][str(thread.id)] = []
mentions = self.bot.config["subscriptions"][str(thread.id)]
if mention in mentions:
embed = discord.Embed(
color=self.bot.error_color,
description=f"{mention} is already subscribed to this thread.",
)
else:
mentions.append(mention)
await self.bot.config.update()
embed = discord.Embed(
color=self.bot.main_color,
description=f"{mention} will now be notified of all messages received.",
)
return await ctx.send(embed=embed)
@commands.command(aliases=["unsub"])
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def unsubscribe(self, ctx, *, user_or_role: Union[discord.Role, User, str.lower, None] = None):
"""
Unsubscribe a user, role, or yourself from a thread.
Leave `user_or_role` empty to unsubscribe yourself.
`@here` and `@everyone` can be substituted with `here` and `everyone`.
`user_or_role` may be a user ID, mention, name, role ID, mention, name, "everyone", or "here".
"""
mention = self.parse_user_or_role(ctx, user_or_role)
if mention is None:
mention = f"`{user_or_role}`"
thread = ctx.thread
if str(thread.id) not in self.bot.config["subscriptions"]:
self.bot.config["subscriptions"][str(thread.id)] = []
mentions = self.bot.config["subscriptions"][str(thread.id)]
if mention not in mentions:
embed = discord.Embed(
color=self.bot.error_color,
description=f"{mention} is not subscribed to this thread.",
)
else:
mentions.remove(mention)
await self.bot.config.update()
embed = discord.Embed(
color=self.bot.main_color,
description=f"{mention} is now unsubscribed from this thread.",
)
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def nsfw(self, ctx):
"""Flags a Modmail thread as NSFW (not safe for work)."""
await ctx.channel.edit(nsfw=True)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command()
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def sfw(self, ctx):
"""Flags a Modmail thread as SFW (safe for work)."""
await ctx.channel.edit(nsfw=False)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command()
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def msglink(self, ctx, message_id: int):
"""Retrieves the link to a message in the current thread."""
try:
message = await ctx.thread.recipient.fetch_message(message_id)
except discord.NotFound:
embed = discord.Embed(
color=self.bot.error_color, description="Message not found or no longer exists."
)
else:
embed = discord.Embed(color=self.bot.main_color, description=message.jump_url)
await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
async def loglink(self, ctx):
"""Retrieves the link to the current thread's logs."""
log_link = await self.bot.api.get_log_link(ctx.channel.id)
await ctx.send(embed=discord.Embed(color=self.bot.main_color, description=log_link))
def format_log_embeds(self, logs, avatar_url):
embeds = []
logs = tuple(logs)
title = f"Total Results Found ({len(logs)})"
for entry in logs:
created_at = parser.parse(entry["created_at"])
prefix = self.bot.config["log_url_prefix"].strip("/")
if prefix == "NONE":
prefix = ""
log_url = (
f"{self.bot.config['log_url'].strip('/')}{'/' + prefix if prefix else ''}/{entry['key']}"
)
username = entry["recipient"]["name"] + "#"
username += entry["recipient"]["discriminator"]
embed = discord.Embed(color=self.bot.main_color, timestamp=created_at)
embed.set_author(name=f"{title} - {username}", icon_url=avatar_url, url=log_url)
embed.url = log_url
embed.add_field(name="Created", value=duration(created_at, now=datetime.utcnow()))
closer = entry.get("closer")
if closer is None:
closer_msg = "Unknown"
else:
closer_msg = f"<@{closer['id']}>"
embed.add_field(name="Closed By", value=closer_msg)
if entry["recipient"]["id"] != entry["creator"]["id"]:
embed.add_field(name="Created by", value=f"<@{entry['creator']['id']}>")
embed.add_field(name="Preview", value=format_preview(entry["messages"]), inline=False)
if closer is not None:
# BUG: Currently, logviewer can't display logs without a closer.
embed.add_field(name="Link", value=log_url)
else:
logger.debug("Invalid log entry: no closer.")
embed.add_field(name="Log Key", value=f"`{entry['key']}`")
embed.set_footer(text="Recipient ID: " + str(entry["recipient"]["id"]))
embeds.append(embed)
return embeds
@commands.command(cooldown_after_parsing=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
@commands.cooldown(1, 600, BucketType.channel)
async def title(self, ctx, *, name: str):
"""Sets title for a thread"""
await ctx.thread.set_title(name)
sent_emoji, _ = await self.bot.retrieve_emoji()
await ctx.message.pin()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command(usage="<users_or_roles...> [options]", cooldown_after_parsing=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
@commands.cooldown(1, 600, BucketType.channel)
async def adduser(self, ctx, *users_arg: Union[discord.Member, discord.Role, str]):
"""Adds a user to a modmail thread
`options` can be `silent` or `silently`.
"""
silent = False
users = []
for u in users_arg:
if isinstance(u, str):
if "silent" in u or "silently" in u:
silent = True
elif isinstance(u, discord.Role):
users += u.members
elif isinstance(u, discord.Member):
users.append(u)
for u in users:
# u is a discord.Member
curr_thread = await self.bot.threads.find(recipient=u)
if curr_thread == ctx.thread:
users.remove(u)
continue
if curr_thread:
em = discord.Embed(
title="Error",
description=f"{u.mention} is already in a thread: {curr_thread.channel.mention}.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not users:
em = discord.Embed(
title="Error",
description="All users are already in the thread.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if len(users + ctx.thread.recipients) > 5:
em = discord.Embed(
title="Error",
description="Only 5 users are allowed in a group conversation",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not silent:
description = self.bot.formatter.format(
self.bot.config["private_added_to_group_response"], moderator=ctx.author
)
em = discord.Embed(
title=self.bot.config["private_added_to_group_title"],
description=description,
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
em.set_footer(text=str(ctx.author), icon_url=ctx.author.avatar_url)
for u in users:
await u.send(embed=em)
description = self.bot.formatter.format(
self.bot.config["public_added_to_group_response"],
moderator=ctx.author,
users=", ".join(u.name for u in users),
)
em = discord.Embed(
title=self.bot.config["public_added_to_group_title"],
description=description,
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
em.set_footer(text=f"{users[0]}", icon_url=users[0].avatar_url)
for i in ctx.thread.recipients:
if i not in users:
await i.send(embed=em)
await ctx.thread.add_users(users)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command(usage="<users_or_roles...> [options]", cooldown_after_parsing=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
@commands.cooldown(1, 600, BucketType.channel)
async def removeuser(self, ctx, *users_arg: Union[discord.Member, discord.Role, str]):
"""Removes a user from a modmail thread
`options` can be `silent` or `silently`.
"""
silent = False
users = []
for u in users_arg:
if isinstance(u, str):
if "silent" in u or "silently" in u:
silent = True
elif isinstance(u, discord.Role):
users += u.members
elif isinstance(u, discord.Member):
users.append(u)
for u in users:
# u is a discord.Member
curr_thread = await self.bot.threads.find(recipient=u)
if ctx.thread != curr_thread:
em = discord.Embed(
title="Error",
description=f"{u.mention} is not in this thread.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
elif ctx.thread.recipient == u:
em = discord.Embed(
title="Error",
description=f"{u.mention} is the main recipient of the thread and cannot be removed.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not silent:
description = self.bot.formatter.format(
self.bot.config["private_removed_from_group_response"], moderator=ctx.author
)
em = discord.Embed(
title=self.bot.config["private_removed_from_group_title"],
description=description,
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
em.set_footer(text=str(ctx.author), icon_url=ctx.author.avatar_url)
for u in users:
await u.send(embed=em)
description = self.bot.formatter.format(
self.bot.config["public_removed_from_group_response"],
moderator=ctx.author,
users=", ".join(u.name for u in users),
)
em = discord.Embed(
title=self.bot.config["public_removed_from_group_title"],
description=description,
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
em.set_footer(text=f"{users[0]}", icon_url=users[0].avatar_url)
for i in ctx.thread.recipients:
if i not in users:
await i.send(embed=em)
await ctx.thread.remove_users(users)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command(usage="<users_or_roles...> [options]", cooldown_after_parsing=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
@commands.cooldown(1, 600, BucketType.channel)
async def anonadduser(self, ctx, *users_arg: Union[discord.Member, discord.Role, str]):
"""Adds a user to a modmail thread anonymously
`options` can be `silent` or `silently`.
"""
silent = False
users = []
for u in users_arg:
if isinstance(u, str):
if "silent" in u or "silently" in u:
silent = True
elif isinstance(u, discord.Role):
users += u.members
elif isinstance(u, discord.Member):
users.append(u)
for u in users:
curr_thread = await self.bot.threads.find(recipient=u)
if curr_thread == ctx.thread:
users.remove(u)
continue
if curr_thread:
em = discord.Embed(
title="Error",
description=f"{u.mention} is already in a thread: {curr_thread.channel.mention}.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not users:
em = discord.Embed(
title="Error",
description="All users are already in the thread.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not silent:
em = discord.Embed(
title=self.bot.config["private_added_to_group_title"],
description=self.bot.config["private_added_to_group_description_anon"],
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
tag = self.bot.config["mod_tag"]
if tag is None:
tag = str(get_top_hoisted_role(ctx.author))
name = self.bot.config["anon_username"]
if name is None:
name = tag
avatar_url = self.bot.config["anon_avatar_url"]
if avatar_url is None:
avatar_url = self.bot.guild.icon_url
em.set_footer(text=name, icon_url=avatar_url)
for u in users:
await u.send(embed=em)
description = self.bot.formatter.format(
self.bot.config["public_added_to_group_description_anon"],
users=", ".join(u.name for u in users),
)
em = discord.Embed(
title=self.bot.config["public_added_to_group_title"],
description=description,
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
em.set_footer(text=f"{users[0]}", icon_url=users[0].avatar_url)
for i in ctx.thread.recipients:
if i not in users:
await i.send(embed=em)
await ctx.thread.add_users(users)
sent_emoji, _ = await self.bot.retrieve_emoji()
await self.bot.add_reaction(ctx.message, sent_emoji)
@commands.command(usage="<users_or_roles...> [options]", cooldown_after_parsing=True)
@checks.has_permissions(PermissionLevel.SUPPORTER)
@checks.thread_only()
@commands.cooldown(1, 600, BucketType.channel)
async def anonremoveuser(self, ctx, *users_arg: Union[discord.Member, discord.Role, str]):
"""Removes a user from a modmail thread anonymously
`options` can be `silent` or `silently`.
"""
silent = False
users = []
for u in users_arg:
if isinstance(u, str):
if "silent" in u or "silently" in u:
silent = True
elif isinstance(u, discord.Role):
users += u.members
elif isinstance(u, discord.Member):
users.append(u)
for u in users:
curr_thread = await self.bot.threads.find(recipient=u)
if ctx.thread != curr_thread:
em = discord.Embed(
title="Error",
description=f"{u.mention} is not in this thread.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
elif ctx.thread.recipient == u:
em = discord.Embed(
title="Error",
description=f"{u.mention} is the main recipient of the thread and cannot be removed.",
color=self.bot.error_color,
)
await ctx.send(embed=em)
ctx.command.reset_cooldown(ctx)
return
if not silent:
em = discord.Embed(
title=self.bot.config["private_removed_from_group_title"],
description=self.bot.config["private_removed_from_group_description_anon"],
color=self.bot.main_color,
)
if self.bot.config["show_timestamp"]:
em.timestamp = datetime.utcnow()
tag = self.bot.config["mod_tag"]
if tag is None:
tag = str(get_top_hoisted_role(ctx.author))
name = self.bot.config["anon_username"]
if name is None:
name = tag
avatar_url = self.bot.config["anon_avatar_url"]
if avatar_url is None: