forked from Cog-Creators/Red-DiscordBot
/
core_commands.py
2491 lines (2142 loc) · 92 KB
/
core_commands.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 contextlib
import datetime
import importlib
import itertools
import logging
import os
import re
import sys
import platform
import getpass
import pip
import traceback
from collections import namedtuple
from pathlib import Path
from random import SystemRandom
from string import ascii_letters, digits
from typing import TYPE_CHECKING, Union, Tuple, List, Optional, Iterable, Sequence, Dict, Set
import aiohttp
import discord
import pkg_resources
from . import (
__version__,
version_info as red_version_info,
VersionInfo,
checks,
commands,
drivers,
errors,
i18n,
config,
)
from .utils.predicates import MessagePredicate
from .utils.chat_formatting import (
box,
escape,
humanize_list,
humanize_number,
humanize_timedelta,
inline,
pagify,
)
from .commands.requires import PrivilegeLevel
if TYPE_CHECKING:
from redbot.core.bot import Red
__all__ = ["Core"]
log = logging.getLogger("red")
_ = i18n.Translator("Core", __file__)
TokenConverter = commands.get_dict_converter(delims=[" ", ",", ";"])
class CoreLogic:
def __init__(self, bot: "Red"):
self.bot = bot
self.bot.register_rpc_handler(self._load)
self.bot.register_rpc_handler(self._unload)
self.bot.register_rpc_handler(self._reload)
self.bot.register_rpc_handler(self._name)
self.bot.register_rpc_handler(self._prefixes)
self.bot.register_rpc_handler(self._version_info)
self.bot.register_rpc_handler(self._invite_url)
async def _load(
self, cog_names: Iterable[str]
) -> Tuple[List[str], List[str], List[str], List[str], List[Tuple[str, str]], Set[str]]:
"""
Loads cogs by name.
Parameters
----------
cog_names : list of str
Returns
-------
tuple
4-tuple of loaded, failed, not found and already loaded cogs.
"""
failed_packages = []
loaded_packages = []
notfound_packages = []
alreadyloaded_packages = []
failed_with_reason_packages = []
repos_with_shared_libs = set()
bot = self.bot
cogspecs = []
for name in cog_names:
try:
spec = await bot._cog_mgr.find_cog(name)
if spec:
cogspecs.append((spec, name))
else:
notfound_packages.append(name)
except Exception as e:
log.exception("Package import failed", exc_info=e)
exception_log = "Exception during import of cog\n"
exception_log += "".join(traceback.format_exception(type(e), e, e.__traceback__))
bot._last_exception = exception_log
failed_packages.append(name)
for spec, name in cogspecs:
try:
self._cleanup_and_refresh_modules(spec.name)
await bot.load_extension(spec)
except errors.PackageAlreadyLoaded:
alreadyloaded_packages.append(name)
except errors.CogLoadError as e:
failed_with_reason_packages.append((name, str(e)))
except Exception as e:
log.exception("Package loading failed", exc_info=e)
exception_log = "Exception during loading of cog\n"
exception_log += "".join(traceback.format_exception(type(e), e, e.__traceback__))
bot._last_exception = exception_log
failed_packages.append(name)
else:
await bot.add_loaded_package(name)
loaded_packages.append(name)
# remove in Red 3.4
downloader = bot.get_cog("Downloader")
if downloader is None:
continue
try:
maybe_repo = await downloader._shared_lib_load_check(name)
except Exception:
log.exception(
"Shared library check failed,"
" if you're not using modified Downloader, report this issue."
)
maybe_repo = None
if maybe_repo is not None:
repos_with_shared_libs.add(maybe_repo.name)
return (
loaded_packages,
failed_packages,
notfound_packages,
alreadyloaded_packages,
failed_with_reason_packages,
repos_with_shared_libs,
)
@staticmethod
def _cleanup_and_refresh_modules(module_name: str) -> None:
"""Interally reloads modules so that changes are detected"""
splitted = module_name.split(".")
def maybe_reload(new_name):
try:
lib = sys.modules[new_name]
except KeyError:
pass
else:
importlib._bootstrap._exec(lib.__spec__, lib)
# noinspection PyTypeChecker
modules = itertools.accumulate(splitted, "{}.{}".format)
for m in modules:
maybe_reload(m)
children = {name: lib for name, lib in sys.modules.items() if name.startswith(module_name)}
for child_name, lib in children.items():
importlib._bootstrap._exec(lib.__spec__, lib)
async def _unload(self, cog_names: Iterable[str]) -> Tuple[List[str], List[str]]:
"""
Unloads cogs with the given names.
Parameters
----------
cog_names : list of str
Returns
-------
tuple
2 element tuple of successful unloads and failed unloads.
"""
failed_packages = []
unloaded_packages = []
bot = self.bot
for name in cog_names:
if name in bot.extensions:
bot.unload_extension(name)
await bot.remove_loaded_package(name)
unloaded_packages.append(name)
else:
failed_packages.append(name)
return unloaded_packages, failed_packages
async def _reload(
self, cog_names: Sequence[str]
) -> Tuple[List[str], List[str], List[str], List[str], List[Tuple[str, str]], Set[str]]:
await self._unload(cog_names)
(
loaded,
load_failed,
not_found,
already_loaded,
load_failed_with_reason,
repos_with_shared_libs,
) = await self._load(cog_names)
return (
loaded,
load_failed,
not_found,
already_loaded,
load_failed_with_reason,
repos_with_shared_libs,
)
async def _name(self, name: Optional[str] = None) -> str:
"""
Gets or sets the bot's username.
Parameters
----------
name : str
If passed, the bot will change it's username.
Returns
-------
str
The current (or new) username of the bot.
"""
if name is not None:
await self.bot.user.edit(username=name)
return self.bot.user.name
async def _prefixes(self, prefixes: Optional[Sequence[str]] = None) -> List[str]:
"""
Gets or sets the bot's global prefixes.
Parameters
----------
prefixes : list of str
If passed, the bot will set it's global prefixes.
Returns
-------
list of str
The current (or new) list of prefixes.
"""
if prefixes:
await self.bot._prefix_cache.set_prefixes(guild=None, prefixes=prefixes)
return prefixes
return await self.bot._prefix_cache.get_prefixes(guild=None)
@classmethod
async def _version_info(cls) -> Dict[str, str]:
"""
Version information for Red and discord.py
Returns
-------
dict
`redbot` and `discordpy` keys containing version information for both.
"""
return {"redbot": __version__, "discordpy": discord.__version__}
async def _invite_url(self) -> str:
"""
Generates the invite URL for the bot.
Returns
-------
str
Invite URL.
"""
app_info = await self.bot.application_info()
perms_int = await self.bot._config.invite_perm()
permissions = discord.Permissions(perms_int)
return discord.utils.oauth_url(app_info.id, permissions)
@staticmethod
async def _can_get_invite_url(ctx):
is_owner = await ctx.bot.is_owner(ctx.author)
is_invite_public = await ctx.bot._config.invite_public()
return is_owner or is_invite_public
@i18n.cog_i18n(_)
class Core(commands.Cog, CoreLogic):
"""Commands related to core functions"""
@commands.command(hidden=True)
async def ping(self, ctx: commands.Context):
"""Pong."""
await ctx.send("Pong.")
@commands.command()
async def info(self, ctx: commands.Context):
"""Shows info about Red"""
author_repo = "https://github.com/Twentysix26"
org_repo = "https://github.com/Cog-Creators"
red_repo = org_repo + "/Red-DiscordBot"
red_pypi = "https://pypi.org/pypi/Red-DiscordBot"
support_server_url = "https://discord.gg/red"
dpy_repo = "https://github.com/Rapptz/discord.py"
python_url = "https://www.python.org/"
since = datetime.datetime(2016, 1, 2, 0, 0)
days_since = (datetime.datetime.utcnow() - since).days
dpy_version = "[{}]({})".format(discord.__version__, dpy_repo)
python_version = "[{}.{}.{}]({})".format(*sys.version_info[:3], python_url)
red_version = "[{}]({})".format(__version__, red_pypi)
app_info = await self.bot.application_info()
if app_info.team:
owner = app_info.team.name
else:
owner = app_info.owner
custom_info = await self.bot._config.custom_info()
async with aiohttp.ClientSession() as session:
async with session.get("{}/json".format(red_pypi)) as r:
data = await r.json()
outdated = VersionInfo.from_str(data["info"]["version"]) > red_version_info
about = _(
"This bot is an instance of [Red, an open source Discord bot]({}) "
"created by [Twentysix]({}) and [improved by many]({}).\n\n"
"Red is backed by a passionate community who contributes and "
"creates content for everyone to enjoy. [Join us today]({}) "
"and help us improve!\n\n"
"(c) Cog Creators"
).format(red_repo, author_repo, org_repo, support_server_url)
embed = discord.Embed(color=(await ctx.embed_colour()))
embed.add_field(name=_("Instance owned by"), value=str(owner))
embed.add_field(name="Python", value=python_version)
embed.add_field(name="discord.py", value=dpy_version)
embed.add_field(name=_("Red version"), value=red_version)
if outdated:
embed.add_field(
name=_("Outdated"), value=_("Yes, {} is available").format(data["info"]["version"])
)
if custom_info:
embed.add_field(name=_("About this instance"), value=custom_info, inline=False)
embed.add_field(name=_("About Red"), value=about, inline=False)
embed.set_footer(
text=_("Bringing joy since 02 Jan 2016 (over {} days ago!)").format(days_since)
)
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send(_("I need the `Embed links` permission to send this"))
@commands.command()
async def uptime(self, ctx: commands.Context):
"""Shows [botname]'s uptime"""
since = ctx.bot.uptime.strftime("%Y-%m-%d %H:%M:%S")
delta = datetime.datetime.utcnow() - self.bot.uptime
uptime_str = humanize_timedelta(timedelta=delta) or _("Less than one second")
await ctx.send(
_("Been up for: **{time_quantity}** (since {timestamp} UTC)").format(
time_quantity=uptime_str, timestamp=since
)
)
@commands.group()
async def embedset(self, ctx: commands.Context):
"""
Commands for toggling embeds on or off.
This setting determines whether or not to
use embeds as a response to a command (for
commands that support it). The default is to
use embeds.
"""
if ctx.invoked_subcommand is None:
text = _("Embed settings:\n\n")
global_default = await self.bot._config.embeds()
text += _("Global default: {}\n").format(global_default)
if ctx.guild:
guild_setting = await self.bot._config.guild(ctx.guild).embeds()
text += _("Guild setting: {}\n").format(guild_setting)
if ctx.channel:
channel_setting = await self.bot._config.channel(ctx.channel).embeds()
text += _("Channel setting: {}\n").format(channel_setting)
user_setting = await self.bot._config.user(ctx.author).embeds()
text += _("User setting: {}").format(user_setting)
await ctx.send(box(text))
@embedset.command(name="global")
@checks.is_owner()
async def embedset_global(self, ctx: commands.Context):
"""
Toggle the global embed setting.
This is used as a fallback if the user
or guild hasn't set a preference. The
default is to use embeds.
"""
current = await self.bot._config.embeds()
await self.bot._config.embeds.set(not current)
await ctx.send(
_("Embeds are now {} by default.").format(_("disabled") if current else _("enabled"))
)
@embedset.command(name="guild")
@checks.guildowner_or_permissions(administrator=True)
@commands.guild_only()
async def embedset_guild(self, ctx: commands.Context, enabled: bool = None):
"""
Toggle the guild's embed setting.
If enabled is None, the setting will be unset and
the global default will be used instead.
If set, this is used instead of the global default
to determine whether or not to use embeds. This is
used for all commands done in a guild channel except
for help commands.
"""
await self.bot._config.guild(ctx.guild).embeds.set(enabled)
if enabled is None:
await ctx.send(_("Embeds will now fall back to the global setting."))
else:
await ctx.send(
_("Embeds are now {} for this guild.").format(
_("enabled") if enabled else _("disabled")
)
)
@embedset.command(name="channel")
@checks.guildowner_or_permissions(administrator=True)
@commands.guild_only()
async def embedset_channel(self, ctx: commands.Context, enabled: bool = None):
"""
Toggle the channel's embed setting.
If enabled is None, the setting will be unset and
the guild default will be used instead.
If set, this is used instead of the guild default
to determine whether or not to use embeds. This is
used for all commands done in a channel except
for help commands.
"""
await self.bot._config.channel(ctx.channel).embeds.set(enabled)
if enabled is None:
await ctx.send(_("Embeds will now fall back to the global setting."))
else:
await ctx.send(
_("Embeds are now {} for this channel.").format(
_("enabled") if enabled else _("disabled")
)
)
@embedset.command(name="user")
async def embedset_user(self, ctx: commands.Context, enabled: bool = None):
"""
Toggle the user's embed setting.
If enabled is None, the setting will be unset and
the global default will be used instead.
If set, this is used instead of the global default
to determine whether or not to use embeds. This is
used for all commands done in a DM with the bot, as
well as all help commands everywhere.
"""
await self.bot._config.user(ctx.author).embeds.set(enabled)
if enabled is None:
await ctx.send(_("Embeds will now fall back to the global setting."))
else:
await ctx.send(
_("Embeds are now {} for you.").format(_("enabled") if enabled else _("disabled"))
)
@commands.command()
@checks.is_owner()
async def traceback(self, ctx: commands.Context, public: bool = False):
"""Sends to the owner the last command exception that has occurred
If public (yes is specified), it will be sent to the chat instead"""
if not public:
destination = ctx.author
else:
destination = ctx.channel
if self.bot._last_exception:
for page in pagify(self.bot._last_exception, shorten_by=10):
await destination.send(box(page, lang="py"))
else:
await ctx.send(_("No exception has occurred yet"))
@commands.command()
@commands.check(CoreLogic._can_get_invite_url)
async def invite(self, ctx):
"""Show's [botname]'s invite url"""
try:
await ctx.author.send(await self._invite_url())
except discord.errors.Forbidden:
await ctx.send(
"I couldn't send the invite message to you in DM. "
"Either you blocked me or you disabled DMs in this server."
)
@commands.group()
@checks.is_owner()
async def inviteset(self, ctx):
"""Setup the bot's invite"""
pass
@inviteset.command()
async def public(self, ctx, confirm: bool = False):
"""
Define if the command should be accessible for the average user.
"""
if await self.bot._config.invite_public():
await self.bot._config.invite_public.set(False)
await ctx.send("The invite is now private.")
return
app_info = await self.bot.application_info()
if not app_info.bot_public:
await ctx.send(
"I am not a public bot. That means that nobody except "
"you can invite me on new servers.\n\n"
"You can change this by ticking `Public bot` in "
"your token settings: "
"https://discordapp.com/developers/applications/me/{0}".format(self.bot.user.id)
)
return
if not confirm:
await ctx.send(
"You're about to make the `{0}invite` command public. "
"All users will be able to invite me on their server.\n\n"
"If you agree, you can type `{0}inviteset public yes`.".format(ctx.clean_prefix)
)
else:
await self.bot._config.invite_public.set(True)
await ctx.send("The invite command is now public.")
@inviteset.command()
async def perms(self, ctx, level: int):
"""
Make the bot create its own role with permissions on join.
The bot will create its own role with the desired permissions\
when it joins a new server. This is a special role that can't be\
deleted or removed from the bot.
For that, you need to provide a valid permissions level.
You can generate one here: https://discordapi.com/permissions.html
Please note that you might need two factor authentification for\
some permissions.
"""
await self.bot._config.invite_perm.set(level)
await ctx.send("The new permissions level has been set.")
@commands.command()
@commands.guild_only()
@checks.is_owner()
async def leave(self, ctx: commands.Context):
"""Leaves server"""
await ctx.send(_("Are you sure you want me to leave this server? (y/n)"))
pred = MessagePredicate.yes_or_no(ctx)
try:
await self.bot.wait_for("message", check=pred)
except asyncio.TimeoutError:
await ctx.send(_("Response timed out."))
return
else:
if pred.result is True:
await ctx.send(_("Alright. Bye :wave:"))
log.debug(_("Leaving guild '{}'").format(ctx.guild.name))
await ctx.guild.leave()
else:
await ctx.send(_("Alright, I'll stay then :)"))
@commands.command()
@checks.is_owner()
async def servers(self, ctx: commands.Context):
"""Lists and allows to leave servers"""
guilds = sorted(list(self.bot.guilds), key=lambda s: s.name.lower())
msg = ""
responses = []
for i, server in enumerate(guilds, 1):
msg += "{}: {} (`{}`)\n".format(i, server.name, server.id)
responses.append(str(i))
for page in pagify(msg, ["\n"]):
await ctx.send(page)
query = await ctx.send(_("To leave a server, just type its number."))
pred = MessagePredicate.contained_in(responses, ctx)
try:
await self.bot.wait_for("message", check=pred, timeout=15)
except asyncio.TimeoutError:
try:
await query.delete()
except discord.errors.NotFound:
pass
else:
await self.leave_confirmation(guilds[pred.result], ctx)
async def leave_confirmation(self, guild, ctx):
if guild.owner.id == ctx.bot.user.id:
await ctx.send(_("I cannot leave a guild I am the owner of."))
return
await ctx.send(_("Are you sure you want me to leave {}? (yes/no)").format(guild.name))
pred = MessagePredicate.yes_or_no(ctx)
try:
await self.bot.wait_for("message", check=pred, timeout=15)
if pred.result is True:
await guild.leave()
if guild != ctx.guild:
await ctx.send(_("Done."))
else:
await ctx.send(_("Alright then."))
except asyncio.TimeoutError:
await ctx.send(_("Response timed out."))
@commands.command()
@checks.is_owner()
async def load(self, ctx: commands.Context, *cogs: str):
"""Loads packages"""
if not cogs:
return await ctx.send_help()
cogs = tuple(map(lambda cog: cog.rstrip(","), cogs))
async with ctx.typing():
(
loaded,
failed,
not_found,
already_loaded,
failed_with_reason,
repos_with_shared_libs,
) = await self._load(cogs)
output = []
if loaded:
loaded_packages = humanize_list([inline(package) for package in loaded])
formed = _("Loaded {packs}.").format(packs=loaded_packages)
output.append(formed)
if already_loaded:
if len(already_loaded) == 1:
formed = _("The following package is already loaded: {pack}").format(
pack=inline(already_loaded[0])
)
else:
formed = _("The following packages are already loaded: {packs}").format(
packs=humanize_list([inline(package) for package in already_loaded])
)
output.append(formed)
if failed:
if len(failed) == 1:
formed = _(
"Failed to load the following package: {pack}."
"\nCheck your console or logs for details."
).format(pack=inline(failed[0]))
else:
formed = _(
"Failed to load the following packages: {packs}"
"\nCheck your console or logs for details."
).format(packs=humanize_list([inline(package) for package in failed]))
output.append(formed)
if not_found:
if len(not_found) == 1:
formed = _("The following package was not found in any cog path: {pack}.").format(
pack=inline(not_found[0])
)
else:
formed = _(
"The following packages were not found in any cog path: {packs}"
).format(packs=humanize_list([inline(package) for package in not_found]))
output.append(formed)
if failed_with_reason:
reasons = "\n".join([f"`{x}`: {y}" for x, y in failed_with_reason])
if len(failed_with_reason) == 1:
formed = _(
"This package could not be loaded for the following reason:\n\n{reason}"
).format(reason=reasons)
else:
formed = _(
"These packages could not be loaded for the following reasons:\n\n{reasons}"
).format(reasons=reasons)
output.append(formed)
if repos_with_shared_libs:
if len(repos_with_shared_libs) == 1:
formed = _(
"**WARNING**: The following repo is using shared libs"
" which are marked for removal in Red 3.4: {repo}.\n"
"You should inform maintainer of the repo about this message."
).format(repo=inline(repos_with_shared_libs.pop()))
else:
formed = _(
"**WARNING**: The following repos are using shared libs"
" which are marked for removal in Red 3.4: {repos}.\n"
"You should inform maintainers of these repos about this message."
).format(repos=humanize_list([inline(repo) for repo in repos_with_shared_libs]))
output.append(formed)
if output:
total_message = "\n\n".join(output)
for page in pagify(total_message):
await ctx.send(page)
@commands.command()
@checks.is_owner()
async def unload(self, ctx: commands.Context, *cogs: str):
"""Unloads packages"""
if not cogs:
return await ctx.send_help()
cogs = tuple(map(lambda cog: cog.rstrip(","), cogs))
unloaded, failed = await self._unload(cogs)
output = []
if unloaded:
if len(unloaded) == 1:
formed = _("The following package was unloaded: {pack}.").format(
pack=inline(unloaded[0])
)
else:
formed = _("The following packages were unloaded: {packs}.").format(
packs=humanize_list([inline(package) for package in unloaded])
)
output.append(formed)
if failed:
if len(failed) == 1:
formed = _("The following package was not loaded: {pack}.").format(
pack=inline(failed[0])
)
else:
formed = _("The following packages were not loaded: {packs}.").format(
packs=humanize_list([inline(package) for package in failed])
)
output.append(formed)
if output:
total_message = "\n\n".join(output)
for page in pagify(total_message):
await ctx.send(page)
@commands.command(name="reload")
@checks.is_owner()
async def reload(self, ctx: commands.Context, *cogs: str):
"""Reloads packages"""
if not cogs:
return await ctx.send_help()
cogs = tuple(map(lambda cog: cog.rstrip(","), cogs))
async with ctx.typing():
(
loaded,
failed,
not_found,
already_loaded,
failed_with_reason,
repos_with_shared_libs,
) = await self._reload(cogs)
output = []
if loaded:
loaded_packages = humanize_list([inline(package) for package in loaded])
formed = _("Reloaded {packs}.").format(packs=loaded_packages)
output.append(formed)
if failed:
if len(failed) == 1:
formed = _(
"Failed to reload the following package: {pack}."
"\nCheck your console or logs for details."
).format(pack=inline(failed[0]))
else:
formed = _(
"Failed to reload the following packages: {packs}"
"\nCheck your console or logs for details."
).format(packs=humanize_list([inline(package) for package in failed]))
output.append(formed)
if not_found:
if len(not_found) == 1:
formed = _("The following package was not found in any cog path: {pack}.").format(
pack=inline(not_found[0])
)
else:
formed = _(
"The following packages were not found in any cog path: {packs}"
).format(packs=humanize_list([inline(package) for package in not_found]))
output.append(formed)
if failed_with_reason:
reasons = "\n".join([f"`{x}`: {y}" for x, y in failed_with_reason])
if len(failed_with_reason) == 1:
formed = _(
"This package could not be reloaded for the following reason:\n\n{reason}"
).format(reason=reasons)
else:
formed = _(
"These packages could not be reloaded for the following reasons:\n\n{reasons}"
).format(reasons=reasons)
output.append(formed)
if repos_with_shared_libs:
if len(repos_with_shared_libs) == 1:
formed = _(
"**WARNING**: The following repo is using shared libs"
" which are marked for removal in Red 3.4: {repo}.\n"
"You should inform maintainers of these repos about this message."
).format(repo=inline(repos_with_shared_libs.pop()))
else:
formed = _(
"**WARNING**: The following repos are using shared libs"
" which are marked for removal in Red 3.4: {repos}.\n"
"You should inform maintainers of these repos about this message."
).format(repos=humanize_list([inline(repo) for repo in repos_with_shared_libs]))
output.append(formed)
if output:
total_message = "\n\n".join(output)
for page in pagify(total_message):
await ctx.send(page)
@commands.command(name="shutdown")
@checks.is_owner()
async def _shutdown(self, ctx: commands.Context, silently: bool = False):
"""Shuts down the bot"""
wave = "\N{WAVING HAND SIGN}"
skin = "\N{EMOJI MODIFIER FITZPATRICK TYPE-3}"
with contextlib.suppress(discord.HTTPException):
if not silently:
await ctx.send(_("Shutting down... ") + wave + skin)
await ctx.bot.shutdown()
@commands.command(name="restart")
@checks.is_owner()
async def _restart(self, ctx: commands.Context, silently: bool = False):
"""Attempts to restart Red
Makes Red quit with exit code 26
The restart is not guaranteed: it must be dealt
with by the process manager in use"""
with contextlib.suppress(discord.HTTPException):
if not silently:
await ctx.send(_("Restarting..."))
await ctx.bot.shutdown(restart=True)
@commands.group(name="set")
async def _set(self, ctx: commands.Context):
"""Changes [botname]'s settings"""
if ctx.invoked_subcommand is None:
if ctx.guild:
guild = ctx.guild
admin_role_ids = await ctx.bot._config.guild(ctx.guild).admin_role()
admin_role_names = [r.name for r in guild.roles if r.id in admin_role_ids]
admin_roles_str = (
humanize_list(admin_role_names) if admin_role_names else "Not Set."
)
mod_role_ids = await ctx.bot._config.guild(ctx.guild).mod_role()
mod_role_names = [r.name for r in guild.roles if r.id in mod_role_ids]
mod_roles_str = humanize_list(mod_role_names) if mod_role_names else "Not Set."
guild_settings = _("Admin roles: {admin}\nMod roles: {mod}\n").format(
admin=admin_roles_str, mod=mod_roles_str
)
else:
guild_settings = ""
prefixes = await ctx.bot._prefix_cache.get_prefixes(ctx.guild)
locale = await ctx.bot._config.locale()
prefix_string = " ".join(prefixes)
settings = _(
"{bot_name} Settings:\n\n"
"Prefixes: {prefixes}\n"
"{guild_settings}"
"Locale: {locale}"
).format(
bot_name=ctx.bot.user.name,
prefixes=prefix_string,
guild_settings=guild_settings,
locale=locale,
)
for page in pagify(settings):
await ctx.send(box(page))
@checks.is_owner()
@_set.command(name="description")
async def setdescription(self, ctx: commands.Context, *, description: str = ""):
"""
Sets the bot's description.
Use without a description to reset.
This is shown in a few locations, including the help menu.
The default is "Red V3"
"""
if not description:
await ctx.bot._config.description.clear()
ctx.bot.description = "Red V3"
await ctx.send(_("Description reset."))
elif len(description) > 250: # While the limit is 256, we bold it adding characters.
await ctx.send(
_(
"This description is too long to properly display. "
"Please try again with below 250 characters"
)
)
else:
await ctx.bot._config.description.set(description)
ctx.bot.description = description
await ctx.tick()
@_set.command()
@checks.guildowner()
@commands.guild_only()
async def addadminrole(self, ctx: commands.Context, *, role: discord.Role):
"""
Adds an admin role for this guild.
"""
async with ctx.bot._config.guild(ctx.guild).admin_role() as roles:
if role.id in roles:
return await ctx.send(_("This role is already an admin role."))
roles.append(role.id)
await ctx.send(_("That role is now considered an admin role."))
@_set.command()
@checks.guildowner()
@commands.guild_only()
async def addmodrole(self, ctx: commands.Context, *, role: discord.Role):
"""
Adds a mod role for this guild.
"""
async with ctx.bot._config.guild(ctx.guild).mod_role() as roles:
if role.id in roles:
return await ctx.send(_("This role is already a mod role."))
roles.append(role.id)
await ctx.send(_("That role is now considered a mod role."))
@_set.command(aliases=["remadmindrole", "deladminrole", "deleteadminrole"])
@checks.guildowner()
@commands.guild_only()
async def removeadminrole(self, ctx: commands.Context, *, role: discord.Role):
"""
Removes an admin role for this guild.
"""
async with ctx.bot._config.guild(ctx.guild).admin_role() as roles:
if role.id not in roles:
return await ctx.send(_("That role was not an admin role to begin with."))
roles.remove(role.id)
await ctx.send(_("That role is no longer considered an admin role."))
@_set.command(aliases=["remmodrole", "delmodrole", "deletemodrole"])
@checks.guildowner()
@commands.guild_only()
async def removemodrole(self, ctx: commands.Context, *, role: discord.Role):
"""
Removes a mod role for this guild.
"""
async with ctx.bot._config.guild(ctx.guild).mod_role() as roles:
if role.id not in roles:
return await ctx.send(_("That role was not a mod role to begin with."))
roles.remove(role.id)
await ctx.send(_("That role is no longer considered a mod role."))
@_set.command(aliases=["usebotcolor"])
@checks.guildowner()
@commands.guild_only()
async def usebotcolour(self, ctx: commands.Context):
"""
Toggle whether to use the bot owner-configured colour for embeds.
Default is to use the bot's configured colour.
Otherwise, the colour used will be the colour of the bot's top role.
"""
current_setting = await ctx.bot._config.guild(ctx.guild).use_bot_color()
await ctx.bot._config.guild(ctx.guild).use_bot_color.set(not current_setting)
await ctx.send(
_("The bot {} use its configured color for embeds.").format(
_("will not") if not current_setting else _("will")
)
)