-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
Copy pathutility.py
2092 lines (1771 loc) · 80 KB
/
utility.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 inspect
import os
import random
import re
import traceback
from contextlib import redirect_stdout
from datetime import datetime
from difflib import get_close_matches
from io import BytesIO, StringIO
from itertools import takewhile, zip_longest
from json import JSONDecodeError, loads
from subprocess import PIPE
from textwrap import indent
from types import SimpleNamespace
from typing import Union
import discord
from aiohttp import ClientResponseError
from discord.enums import ActivityType, Status
from discord.ext import commands, tasks
from discord.ext.commands.view import StringView
from pkg_resources import parse_version
from core import checks, utils
from core.changelog import Changelog
from core.models import (
HostingMethod,
InvalidConfigError,
PermissionLevel,
UnseenFormatter,
getLogger,
)
from core.utils import trigger_typing, truncate
from core.paginator import EmbedPaginatorSession, MessagePaginatorSession
logger = getLogger(__name__)
class ModmailHelpCommand(commands.HelpCommand):
async def command_callback(self, ctx, *, command=None):
"""Ovrwrites original command_callback to ensure `help` without any arguments
returns with checks, `help all` returns without checks"""
if command is None:
self.verify_checks = True
else:
self.verify_checks = False
if command == "all":
command = None
return await super().command_callback(ctx, command=command)
async def format_cog_help(self, cog, *, no_cog=False):
bot = self.context.bot
prefix = self.clean_prefix
formats = [""]
for cmd in await self.filter_commands(
cog.get_commands() if not no_cog else cog,
sort=True,
key=lambda c: (bot.command_perm(c.qualified_name), c.qualified_name),
):
perm_level = bot.command_perm(cmd.qualified_name)
if perm_level is PermissionLevel.INVALID:
format_ = f"`{prefix + cmd.qualified_name}` "
else:
format_ = f"`[{perm_level}] {prefix + cmd.qualified_name}` "
format_ += f"- {cmd.short_doc}\n" if cmd.short_doc else "- *No description.*\n"
if not format_.strip():
continue
if len(format_) + len(formats[-1]) >= 1024:
formats.append(format_)
else:
formats[-1] += format_
embeds = []
for format_ in formats:
description = (
cog.description or "No description."
if not no_cog
else "Miscellaneous commands without a category."
)
embed = discord.Embed(description=f"*{description}*", color=bot.main_color)
if not format_:
continue
embed.add_field(name="Commands", value=format_ or "No commands.")
continued = " (Continued)" if embeds else ""
name = cog.qualified_name + " - Help" if not no_cog else "Miscellaneous Commands"
embed.set_author(name=name + continued, icon_url=bot.user.avatar_url)
embed.set_footer(
text=f'Type "{prefix}{self.command_attrs["name"]} command" '
"for more info on a specific command."
)
embeds.append(embed)
return embeds
def process_help_msg(self, help_: str):
return help_.format(prefix=self.clean_prefix) if help_ else "No help message."
async def send_bot_help(self, mapping):
embeds = []
no_cog_commands = sorted(mapping.pop(None), key=lambda c: c.qualified_name)
cogs = sorted(mapping, key=lambda c: c.qualified_name)
bot = self.context.bot
# always come first
default_cogs = [bot.get_cog("Modmail"), bot.get_cog("Utility"), bot.get_cog("Plugins")]
default_cogs.extend(c for c in cogs if c not in default_cogs)
for cog in default_cogs:
embeds.extend(await self.format_cog_help(cog))
if no_cog_commands:
embeds.extend(await self.format_cog_help(no_cog_commands, no_cog=True))
session = EmbedPaginatorSession(self.context, *embeds, destination=self.get_destination())
return await session.run()
async def send_cog_help(self, cog):
embeds = await self.format_cog_help(cog)
session = EmbedPaginatorSession(self.context, *embeds, destination=self.get_destination())
return await session.run()
async def _get_help_embed(self, topic):
if not await self.filter_commands([topic]):
return
perm_level = self.context.bot.command_perm(topic.qualified_name)
if perm_level is not PermissionLevel.INVALID:
perm_level = f"{perm_level.name} [{perm_level}]"
else:
perm_level = "NONE"
embed = discord.Embed(
title=f"`{self.get_command_signature(topic)}`",
color=self.context.bot.main_color,
description=self.process_help_msg(topic.help),
)
return embed, perm_level
async def send_command_help(self, command):
topic = await self._get_help_embed(command)
if topic is not None:
topic[0].set_footer(text=f"Permission level: {topic[1]}")
await self.get_destination().send(embed=topic[0])
async def send_group_help(self, group):
topic = await self._get_help_embed(group)
if topic is None:
return
embed = topic[0]
embed.add_field(name="Permission Level", value=topic[1], inline=False)
format_ = ""
length = len(group.commands)
for i, command in enumerate(
await self.filter_commands(group.commands, sort=True, key=lambda c: c.name)
):
# BUG: fmt may run over the embed limit
# TODO: paginate this
if length == i + 1: # last
branch = "└─"
else:
branch = "├─"
format_ += f"`{branch} {command.name}` - {command.short_doc}\n"
embed.add_field(name="Sub Command(s)", value=format_[:1024], inline=False)
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]} command" '
"for more info on a command."
)
await self.get_destination().send(embed=embed)
async def send_error_message(self, error):
command = self.context.kwargs.get("command")
val = self.context.bot.snippets.get(command)
if val is not None:
embed = discord.Embed(title=f"{command} is a snippet.", color=self.context.bot.main_color)
embed.add_field(name=f"`{command}` will send:", value=val)
return await self.get_destination().send(embed=embed)
val = self.context.bot.aliases.get(command)
if val is not None:
values = utils.parse_alias(val)
if not values:
embed = discord.Embed(
title="Error",
color=self.context.bot.error_color,
description=f"Alias `{command}` is invalid, this alias will now be deleted."
"This alias will now be deleted.",
)
embed.add_field(name=f"{command}` used to be:", value=val)
self.context.bot.aliases.pop(command)
await self.context.bot.config.update()
else:
if len(values) == 1:
embed = discord.Embed(title=f"{command} is an alias.", color=self.context.bot.main_color)
embed.add_field(name=f"`{command}` points to:", value=values[0])
else:
embed = discord.Embed(
title=f"{command} is an alias.",
color=self.context.bot.main_color,
description=f"**`{command}` points to the following steps:**",
)
for i, val in enumerate(values, start=1):
embed.add_field(name=f"Step {i}:", value=val)
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]} alias" '
"for more details on aliases."
)
return await self.get_destination().send(embed=embed)
logger.warning("CommandNotFound: %s", error)
embed = discord.Embed(color=self.context.bot.error_color)
embed.set_footer(text=f'Command/Category "{command}" not found.')
choices = set()
for cmd in self.context.bot.walk_commands():
if not cmd.hidden:
choices.add(cmd.qualified_name)
closest = get_close_matches(command, choices)
if closest:
embed.add_field(name="Perhaps you meant:", value="\n".join(f"`{x}`" for x in closest))
else:
embed.title = "Cannot find command or category"
embed.set_footer(
text=f'Type "{self.clean_prefix}{self.command_attrs["name"]}" '
"for a list of all available commands."
)
await self.get_destination().send(embed=embed)
class Utility(commands.Cog):
"""General commands that provide utility."""
def __init__(self, bot):
self.bot = bot
self._original_help_command = bot.help_command
self.bot.help_command = ModmailHelpCommand(
command_attrs={
"help": "Shows this help message.",
"checks": [checks.has_permissions_predicate(PermissionLevel.REGULAR)],
},
)
self.bot.help_command.cog = self
self.loop_presence.start() # pylint: disable=no-member
if not self.bot.config.get("enable_eval"):
self.eval_.enabled = False
logger.info("Eval disabled. enable_eval=False")
def cog_unload(self):
self.bot.help_command = self._original_help_command
@commands.command()
@checks.has_permissions(PermissionLevel.REGULAR)
@utils.trigger_typing
async def changelog(self, ctx, version: str.lower = ""):
"""Shows the changelog of the Modmail."""
changelog = await Changelog.from_url(self.bot)
version = version.lstrip("v") if version else changelog.latest_version.version
try:
index = [v.version for v in changelog.versions].index(version)
except ValueError:
return await ctx.send(
embed=discord.Embed(
color=self.bot.error_color,
description=f"The specified version `{version}` could not be found.",
)
)
paginator = EmbedPaginatorSession(ctx, *changelog.embeds)
try:
paginator.current = index
await paginator.run()
except asyncio.CancelledError:
pass
except Exception:
try:
await paginator.close()
finally:
logger.warning("Failed to display changelog.", exc_info=True)
await ctx.send(
f"View the changelog here: {changelog.latest_version.changelog_url}#v{version[::2]}"
)
@commands.command(aliases=["info"])
@checks.has_permissions(PermissionLevel.REGULAR)
@utils.trigger_typing
async def about(self, ctx):
"""Shows information about this bot."""
embed = discord.Embed(color=self.bot.main_color, timestamp=datetime.utcnow())
embed.set_author(
name="Modmail - About",
icon_url=self.bot.user.avatar_url,
url="https://discord.gg/F34cRU8",
)
embed.set_thumbnail(url=self.bot.user.avatar_url)
desc = "This is an open source Discord bot that serves as a means for "
desc += "members to easily communicate with server administrators in "
desc += "an organised manner."
embed.description = desc
embed.add_field(name="Uptime", value=self.bot.uptime)
embed.add_field(name="Latency", value=f"{self.bot.latency * 1000:.2f} ms")
embed.add_field(name="Version", value=f"`{self.bot.version}`")
embed.add_field(name="Authors", value="`kyb3r`, `Taki`, `fourjr`")
embed.add_field(name="Hosting Method", value=self.bot.hosting_method.name)
changelog = await Changelog.from_url(self.bot)
latest = changelog.latest_version
if self.bot.version.is_prerelease:
stable = next(filter(lambda v: not parse_version(v.version).is_prerelease, changelog.versions))
footer = f"You are on the prerelease version • the latest version is v{stable.version}."
elif self.bot.version < parse_version(latest.version):
footer = f"A newer version is available v{latest.version}."
else:
footer = "You are up to date with the latest version."
embed.add_field(
name="Want Modmail in Your Server?",
value="Follow the installation guide on [GitHub](https://github.com/kyb3r/modmail/) "
"and join our [Discord server](https://discord.gg/F34cRU8)!",
inline=False,
)
embed.add_field(
name="Support the Developers",
value="This bot is completely free for everyone. We rely on kind individuals "
"like you to support us on [`Patreon`](https://patreon.com/kyber) (perks included) "
"to keep this bot free forever!",
inline=False,
)
embed.add_field(
name="Project Sponsors",
value=f"Checkout the people who supported Modmail with command `{self.bot.prefix}sponsors`!",
inline=False,
)
embed.set_footer(text=footer)
await ctx.send(embed=embed)
@commands.command(aliases=["sponsor"])
@checks.has_permissions(PermissionLevel.REGULAR)
@utils.trigger_typing
async def sponsors(self, ctx):
"""Shows the sponsors of this project."""
async with self.bot.session.get(
"https://raw.githubusercontent.com/kyb3r/modmail/master/SPONSORS.json"
) as resp:
data = loads(await resp.text())
embeds = []
for elem in data:
embed = discord.Embed.from_dict(elem["embed"])
embeds.append(embed)
random.shuffle(embeds)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@commands.group(invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
@utils.trigger_typing
async def debug(self, ctx):
"""Shows the recent application logs of the bot."""
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"r+",
) as f:
logs = f.read().strip()
if not logs:
embed = discord.Embed(
color=self.bot.main_color,
title="Debug Logs:",
description="You don't have any logs at the moment.",
)
embed.set_footer(text="Go to Heroku to see your logs.")
return await ctx.send(embed=embed)
messages = []
# Using Haskell formatting because it's similar to Python for exceptions
# and it does a fine job formatting the logs.
msg = "```Haskell\n"
for line in logs.splitlines(keepends=True):
if msg != "```Haskell\n":
if len(line) + len(msg) + 3 > 2000:
msg += "```"
messages.append(msg)
msg = "```Haskell\n"
msg += line
if len(msg) + 3 > 2000:
msg = msg[:1993] + "[...]```"
messages.append(msg)
msg = "```Haskell\n"
if msg != "```Haskell\n":
msg += "```"
messages.append(msg)
embed = discord.Embed(color=self.bot.main_color)
embed.set_footer(text="Debug logs - Navigate using the reactions below.")
session = MessagePaginatorSession(ctx, *messages, embed=embed)
session.current = len(messages) - 1
return await session.run()
@debug.command(name="hastebin", aliases=["haste"])
@checks.has_permissions(PermissionLevel.OWNER)
@utils.trigger_typing
async def debug_hastebin(self, ctx):
"""Posts application-logs to Hastebin."""
haste_url = os.environ.get("HASTE_URL", "https://hastebin.cc")
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"rb+",
) as f:
logs = BytesIO(f.read().strip())
try:
async with self.bot.session.post(haste_url + "/documents", data=logs) as resp:
data = await resp.json()
try:
key = data["key"]
except KeyError:
logger.error(data["message"])
raise
embed = discord.Embed(
title="Debug Logs",
color=self.bot.main_color,
description=f"{haste_url}/" + key,
)
except (JSONDecodeError, ClientResponseError, IndexError, KeyError):
embed = discord.Embed(
title="Debug Logs",
color=self.bot.main_color,
description="Something's wrong. We're unable to upload your logs to hastebin.",
)
embed.set_footer(text="Go to Heroku to see your logs.")
await ctx.send(embed=embed)
@debug.command(name="clear", aliases=["wipe"])
@checks.has_permissions(PermissionLevel.OWNER)
@utils.trigger_typing
async def debug_clear(self, ctx):
"""Clears the locally cached logs."""
log_file_name = self.bot.token.split(".")[0]
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"w",
):
pass
await ctx.send(
embed=discord.Embed(color=self.bot.main_color, description="Cached logs are now cleared.")
)
@commands.command(aliases=["presence"])
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def activity(self, ctx, activity_type: str.lower, *, message: str = ""):
"""
Set an activity status for the bot.
Possible activity types:
- `playing`
- `streaming`
- `listening`
- `watching`
- `competing`
When activity type is set to `listening`,
it must be followed by a "to": "listening to..."
When activity type is set to `competing`,
it must be followed by a "in": "competing in..."
When activity type is set to `streaming`, you can set
the linked twitch page:
- `{prefix}config set twitch_url https://www.twitch.tv/somechannel/`
To remove the current activity status:
- `{prefix}activity clear`
"""
if activity_type == "clear":
self.bot.config.remove("activity_type")
self.bot.config.remove("activity_message")
await self.bot.config.update()
await self.set_presence()
embed = discord.Embed(title="Activity Removed", color=self.bot.main_color)
return await ctx.send(embed=embed)
if not message:
raise commands.MissingRequiredArgument(SimpleNamespace(name="message"))
try:
activity_type = ActivityType[activity_type]
except KeyError:
raise commands.MissingRequiredArgument(SimpleNamespace(name="activity"))
activity, _ = await self.set_presence(activity_type=activity_type, activity_message=message)
self.bot.config["activity_type"] = activity.type.value
self.bot.config["activity_message"] = activity.name
await self.bot.config.update()
msg = f"Activity set to: {activity.type.name.capitalize()} "
if activity.type == ActivityType.listening:
msg += f"to {activity.name}."
elif activity.type == ActivityType.competing:
msg += f"in {activity.name}."
else:
msg += f"{activity.name}."
embed = discord.Embed(title="Activity Changed", description=msg, color=self.bot.main_color)
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def status(self, ctx, *, status_type: str.lower):
"""
Set a status for the bot.
Possible status types:
- `online`
- `idle`
- `dnd` or `do not disturb`
- `invisible` or `offline`
To remove the current status:
- `{prefix}status clear`
"""
if status_type == "clear":
self.bot.config.remove("status")
await self.bot.config.update()
await self.set_presence()
embed = discord.Embed(title="Status Removed", color=self.bot.main_color)
return await ctx.send(embed=embed)
status_type = status_type.replace(" ", "_")
try:
status = Status[status_type]
except KeyError:
raise commands.MissingRequiredArgument(SimpleNamespace(name="status"))
_, status = await self.set_presence(status=status)
self.bot.config["status"] = status.value
await self.bot.config.update()
msg = f"Status set to: {status.value}."
embed = discord.Embed(title="Status Changed", description=msg, color=self.bot.main_color)
return await ctx.send(embed=embed)
async def set_presence(self, *, status=None, activity_type=None, activity_message=None):
if status is None:
status = self.bot.config.get("status")
if activity_type is None:
activity_type = self.bot.config.get("activity_type")
url = None
activity_message = (activity_message or self.bot.config["activity_message"]).strip()
if activity_type is not None and not activity_message:
logger.warning('No activity message found whilst activity is provided, defaults to "Modmail".')
activity_message = "Modmail"
if activity_type == ActivityType.listening:
if activity_message.lower().startswith("to "):
# The actual message is after listening to [...]
# discord automatically add the "to"
activity_message = activity_message[3:].strip()
elif activity_type == ActivityType.competing:
if activity_message.lower().startswith("in "):
# The actual message is after listening to [...]
# discord automatically add the "in"
activity_message = activity_message[3:].strip()
elif activity_type == ActivityType.streaming:
url = self.bot.config["twitch_url"]
if activity_type is not None:
activity = discord.Activity(type=activity_type, name=activity_message, url=url)
else:
activity = None
await self.bot.change_presence(activity=activity, status=status)
return activity, status
@tasks.loop(minutes=30)
async def loop_presence(self):
"""Set presence to the configured value every 30 minutes."""
logger.debug("Resetting presence.")
await self.set_presence()
@loop_presence.before_loop
async def before_loop_presence(self):
await self.bot.wait_for_connected()
logger.line()
activity, status = await self.set_presence()
if activity is not None:
msg = f"Activity set to: {activity.type.name.capitalize()} "
if activity.type == ActivityType.listening:
msg += f"to {activity.name}."
else:
msg += f"{activity.name}."
logger.info(msg)
else:
logger.info("No activity has been set.")
if status is not None:
msg = f"Status set to: {status.value}."
logger.info(msg)
else:
logger.info("No status has been set.")
await asyncio.sleep(1800)
logger.info("Starting presence loop.")
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
@utils.trigger_typing
async def ping(self, ctx):
"""Pong! Returns your websocket latency."""
embed = discord.Embed(
title="Pong! Websocket Latency:",
description=f"{self.bot.ws.latency * 1000:.4f} ms",
color=self.bot.main_color,
)
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def mention(self, ctx, *user_or_role: Union[discord.Role, discord.Member, str]):
"""
Change what the bot mentions at the start of each thread.
`user_or_role` may be a user ID, mention, name, role ID, mention, or name.
You can also set it to mention multiple users or roles, just separate the arguments with space.
Examples:
- `{prefix}mention @user`
- `{prefix}mention @user @role`
- `{prefix}mention 984301093849028 388218663326449`
- `{prefix}mention everyone`
Do not ping `@everyone` to set mention to everyone, use "everyone" or "all" instead.
Notes:
- Type only `{prefix}mention` to retrieve your current "mention" message.
- `{prefix}mention disable` to disable mention.
- `{prefix}mention reset` to reset it to default value, which is "@here".
"""
current = self.bot.config["mention"]
if not user_or_role:
embed = discord.Embed(
title="Current mention:", color=self.bot.main_color, description=str(current)
)
elif (
len(user_or_role) == 1
and isinstance(user_or_role[0], str)
and user_or_role[0].lower() in ("disable", "reset")
):
option = user_or_role[0].lower()
if option == "disable":
embed = discord.Embed(
description=f"Disabled mention on thread creation.",
color=self.bot.main_color,
)
self.bot.config["mention"] = None
else:
embed = discord.Embed(
description="`mention` is reset to default.",
color=self.bot.main_color,
)
self.bot.config.remove("mention")
await self.bot.config.update()
else:
mention = []
everyone = ("all", "everyone")
for m in user_or_role:
if not isinstance(m, (discord.Role, discord.Member)) and m not in everyone:
raise commands.BadArgument(f'Role or Member "{m}" not found.')
elif m == ctx.guild.default_role or m in everyone:
mention.append("@everyone")
continue
mention.append(m.mention)
mention = " ".join(mention)
embed = discord.Embed(
title="Changed mention!",
description=f'On thread creation the bot now says "{mention}".',
color=self.bot.main_color,
)
self.bot.config["mention"] = mention
await self.bot.config.update()
return await ctx.send(embed=embed)
@commands.command()
@checks.has_permissions(PermissionLevel.ADMINISTRATOR)
async def prefix(self, ctx, *, prefix=None):
"""
Change the prefix of the bot.
Type only `{prefix}prefix` to retrieve your current bot prefix.
"""
current = self.bot.prefix
embed = discord.Embed(title="Current prefix", color=self.bot.main_color, description=f"{current}")
if prefix is None:
await ctx.send(embed=embed)
else:
embed.title = "Changed prefix!"
embed.description = f"Set prefix to `{prefix}`"
self.bot.config["prefix"] = prefix
await self.bot.config.update()
await ctx.send(embed=embed)
@commands.group(aliases=["configuration"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.OWNER)
async def config(self, ctx):
"""
Modify changeable configuration variables for this bot.
Type `{prefix}config options` to view a list
of valid configuration variables.
Type `{prefix}config help config-name` for info
on a config.
To set a configuration variable:
- `{prefix}config set config-name value here`
To remove a configuration variable:
- `{prefix}config remove config-name`
"""
await ctx.send_help(ctx.command)
@config.command(name="options", aliases=["list"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_options(self, ctx):
"""Return a list of valid configuration names you can change."""
embeds = []
for names in zip_longest(*(iter(sorted(self.bot.config.public_keys)),) * 15):
description = "\n".join(f"`{name}`" for name in takewhile(lambda x: x is not None, names))
embed = discord.Embed(
title="Available configuration keys:",
color=self.bot.main_color,
description=description,
)
embeds.append(embed)
session = EmbedPaginatorSession(ctx, *embeds)
await session.run()
@config.command(name="set", aliases=["add"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_set(self, ctx, key: str.lower, *, value: str):
"""Set a configuration variable and its value."""
keys = self.bot.config.public_keys
if key in keys:
try:
self.bot.config.set(key, value)
await self.bot.config.update()
embed = discord.Embed(
title="Success",
color=self.bot.main_color,
description=f"Set `{key}` to `{self.bot.config[key]}`.",
)
except InvalidConfigError as exc:
embed = exc.embed
else:
embed = discord.Embed(
title="Error", color=self.bot.error_color, description=f"{key} is an invalid key."
)
valid_keys = [f"`{k}`" for k in sorted(keys)]
embed.add_field(name="Valid keys", value=truncate(", ".join(valid_keys), 1024))
return await ctx.send(embed=embed)
@config.command(name="remove", aliases=["del", "delete"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_remove(self, ctx, *, key: str.lower):
"""Delete a set configuration variable."""
keys = self.bot.config.public_keys
if key in keys:
self.bot.config.remove(key)
await self.bot.config.update()
embed = discord.Embed(
title="Success",
color=self.bot.main_color,
description=f"`{key}` had been reset to default.",
)
else:
embed = discord.Embed(
title="Error", color=self.bot.error_color, description=f"{key} is an invalid key."
)
valid_keys = [f"`{k}`" for k in sorted(keys)]
embed.add_field(name="Valid keys", value=", ".join(valid_keys))
return await ctx.send(embed=embed)
@config.command(name="get")
@checks.has_permissions(PermissionLevel.OWNER)
async def config_get(self, ctx, *, key: str.lower = None):
"""
Show the configuration variables that are currently set.
Leave `key` empty to show all currently set configuration variables.
"""
keys = self.bot.config.public_keys
if key:
if key in keys:
desc = f"`{key}` is set to `{self.bot.config[key]}`"
embed = discord.Embed(color=self.bot.main_color, description=desc)
embed.set_author(name="Config variable", icon_url=self.bot.user.avatar_url)
else:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"`{key}` is an invalid key.",
)
embed.set_footer(
text=f'Type "{self.bot.prefix}config options" for a list of config variables.'
)
else:
embed = discord.Embed(
color=self.bot.main_color,
description="Here is a list of currently set configuration variable(s).",
)
embed.set_author(name="Current config(s):", icon_url=self.bot.user.avatar_url)
config = self.bot.config.filter_default(self.bot.config)
for name, value in config.items():
if name in self.bot.config.public_keys:
embed.add_field(name=name, value=f"`{value}`", inline=False)
return await ctx.send(embed=embed)
@config.command(name="help", aliases=["info"])
@checks.has_permissions(PermissionLevel.OWNER)
async def config_help(self, ctx, key: str.lower = None):
"""
Show information on a specified configuration.
"""
if key is not None and not (
key in self.bot.config.public_keys or key in self.bot.config.protected_keys
):
closest = get_close_matches(
key, {**self.bot.config.public_keys, **self.bot.config.protected_keys}
)
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"`{key}` is an invalid key.",
)
if closest:
embed.add_field(name=f"Perhaps you meant:", value="\n".join(f"`{x}`" for x in closest))
return await ctx.send(embed=embed)
config_help = self.bot.config.config_help
if key is not None and key not in config_help:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"No help details found for `{key}`.",
)
return await ctx.send(embed=embed)
def fmt(val):
return UnseenFormatter().format(val, prefix=self.bot.prefix, bot=self.bot)
index = 0
embeds = []
for i, (current_key, info) in enumerate(config_help.items()):
if current_key == key:
index = i
embed = discord.Embed(
title=f"Configuration description on {current_key}:", color=self.bot.main_color
)
embed.add_field(name="Default:", value=fmt(info["default"]), inline=False)
embed.add_field(name="Information:", value=fmt(info["description"]), inline=False)
if info["examples"]:
example_text = ""
for example in info["examples"]:
example_text += f"- {fmt(example)}\n"
embed.add_field(name="Example(s):", value=example_text, inline=False)
note_text = ""
for note in info.get("notes", []):
note_text += f"- {fmt(note)}\n"
if note_text:
embed.add_field(name="Note(s):", value=note_text, inline=False)
if info.get("image") is not None:
embed.set_image(url=fmt(info["image"]))
if info.get("thumbnail") is not None:
embed.set_thumbnail(url=fmt(info["thumbnail"]))
embeds += [embed]
paginator = EmbedPaginatorSession(ctx, *embeds)
paginator.current = index
await paginator.run()
@commands.group(aliases=["aliases"], invoke_without_command=True)
@checks.has_permissions(PermissionLevel.MODERATOR)
async def alias(self, ctx, *, name: str.lower = None):
"""
Create shortcuts to bot commands.
When `{prefix}alias` is used by itself, this will retrieve
a list of alias that are currently set. `{prefix}alias-name` will show what the
alias point to.
To use alias:
First create an alias using:
- `{prefix}alias add alias-name other-command`
For example:
- `{prefix}alias add r reply`
- Now you can use `{prefix}r` as an replacement for `{prefix}reply`.
See also `{prefix}snippet`.
"""
if name is not None:
val = self.bot.aliases.get(name)
if val is None:
embed = utils.create_not_found_embed(name, self.bot.aliases.keys(), "Alias")
return await ctx.send(embed=embed)
values = utils.parse_alias(val)
if not values:
embed = discord.Embed(
title="Error",
color=self.bot.error_color,
description=f"Alias `{name}` is invalid, this alias will now be deleted."
"This alias will now be deleted.",
)
embed.add_field(name=f"{name}` used to be:", value=utils.truncate(val, 1024))
self.bot.aliases.pop(name)
await self.bot.config.update()
return await ctx.send(embed=embed)
if len(values) == 1:
embed = discord.Embed(
title=f'Alias - "{name}":', description=values[0], color=self.bot.main_color
)
return await ctx.send(embed=embed)
else:
embeds = []
for i, val in enumerate(values, start=1):
embed = discord.Embed(
color=self.bot.main_color,
title=f'Alias - "{name}" - Step {i}:',
description=val,
)
embeds += [embed]
session = EmbedPaginatorSession(ctx, *embeds)