mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-12-09 19:02:32 -05:00
Merge branch 'V3/develop' into V3/feature/mutes
This commit is contained in:
@@ -22,7 +22,7 @@ class SharedLibImportWarner(MetaPathFinder):
|
||||
return None
|
||||
msg = (
|
||||
"One of cogs uses shared libraries which are"
|
||||
" deprecated and scheduled for removal in Red 3.3.\n"
|
||||
" deprecated and scheduled for removal in Red 3.4.\n"
|
||||
"You should inform author of the cog about this message."
|
||||
)
|
||||
warnings.warn(msg, SharedLibDeprecationWarning, stacklevel=2)
|
||||
|
||||
@@ -838,9 +838,9 @@ async def set_default_balance(amount: int, guild: discord.Guild = None) -> int:
|
||||
amount = int(amount)
|
||||
max_bal = await get_max_balance(guild)
|
||||
|
||||
if not (0 < amount <= max_bal):
|
||||
if not (0 <= amount <= max_bal):
|
||||
raise ValueError(
|
||||
"Amount must be greater than zero and less than {max}.".format(
|
||||
"Amount must be greater than or equal zero and less than or equal {max}.".format(
|
||||
max=humanize_number(max_bal, override_locale="en_US")
|
||||
)
|
||||
)
|
||||
|
||||
@@ -10,11 +10,25 @@ from datetime import datetime
|
||||
from enum import IntEnum
|
||||
from importlib.machinery import ModuleSpec
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union, List, Dict, NoReturn
|
||||
from typing import (
|
||||
Optional,
|
||||
Union,
|
||||
List,
|
||||
Dict,
|
||||
NoReturn,
|
||||
Set,
|
||||
Coroutine,
|
||||
TypeVar,
|
||||
Callable,
|
||||
Awaitable,
|
||||
Any,
|
||||
)
|
||||
from types import MappingProxyType
|
||||
|
||||
import discord
|
||||
from discord.ext import commands as dpy_commands
|
||||
from discord.ext.commands import when_mentioned_or
|
||||
from discord.ext.commands.bot import BotBase
|
||||
|
||||
from . import Config, i18n, commands, errors, drivers, modlog, bank
|
||||
from .cog_manager import CogManager, CogManagerUI
|
||||
@@ -24,6 +38,8 @@ from .dev_commands import Dev
|
||||
from .events import init_events
|
||||
from .global_checks import init_global_checks
|
||||
|
||||
from .settings_caches import PrefixManager
|
||||
|
||||
from .rpc import RPCMixin
|
||||
from .utils import common_filters
|
||||
|
||||
@@ -36,13 +52,18 @@ __all__ = ["RedBase", "Red", "ExitCodes"]
|
||||
|
||||
NotMessage = namedtuple("NotMessage", "guild")
|
||||
|
||||
PreInvokeCoroutine = Callable[[commands.Context], Awaitable[Any]]
|
||||
T_BIC = TypeVar("T_BIC", bound=PreInvokeCoroutine)
|
||||
|
||||
|
||||
def _is_submodule(parent, child):
|
||||
return parent == child or child.startswith(parent + ".")
|
||||
|
||||
|
||||
# barely spurious warning caused by our intentional shadowing
|
||||
class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: disable=no-member
|
||||
class RedBase(
|
||||
commands.GroupMixin, dpy_commands.bot.BotBase, RPCMixin
|
||||
): # pylint: disable=no-member
|
||||
"""Mixin for the main bot class.
|
||||
|
||||
This exists because `Red` inherits from `discord.AutoShardedClient`, which
|
||||
@@ -71,11 +92,13 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
custom_info=None,
|
||||
help__page_char_limit=1000,
|
||||
help__max_pages_in_guild=2,
|
||||
help__delete_delay=0,
|
||||
help__use_menus=False,
|
||||
help__show_hidden=False,
|
||||
help__verify_checks=True,
|
||||
help__verify_exists=False,
|
||||
help__tagline="",
|
||||
description="Red V3",
|
||||
invite_public=False,
|
||||
invite_perm=0,
|
||||
disabled_commands=[],
|
||||
@@ -101,6 +124,7 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
autoimmune_ids=[],
|
||||
)
|
||||
|
||||
self._config.register_channel(embeds=None)
|
||||
self._config.register_user(embeds=None)
|
||||
|
||||
self._config.init_custom(CUSTOM_GROUPS, 2)
|
||||
@@ -108,23 +132,13 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
|
||||
self._config.init_custom(SHARED_API_TOKENS, 2)
|
||||
self._config.register_custom(SHARED_API_TOKENS)
|
||||
self._prefix_cache = PrefixManager(self._config, cli_flags)
|
||||
|
||||
async def prefix_manager(bot, message):
|
||||
if not cli_flags.prefix:
|
||||
global_prefix = await bot._config.prefix()
|
||||
else:
|
||||
global_prefix = cli_flags.prefix
|
||||
if message.guild is None:
|
||||
return global_prefix
|
||||
server_prefix = await bot._config.guild(message.guild).prefix()
|
||||
async def prefix_manager(bot, message) -> List[str]:
|
||||
prefixes = await self._prefix_cache.get_prefixes(message.guild)
|
||||
if cli_flags.mentionable:
|
||||
return (
|
||||
when_mentioned_or(*server_prefix)(bot, message)
|
||||
if server_prefix
|
||||
else when_mentioned_or(*global_prefix)(bot, message)
|
||||
)
|
||||
else:
|
||||
return server_prefix if server_prefix else global_prefix
|
||||
return when_mentioned_or(*prefixes)(bot, message)
|
||||
return prefixes
|
||||
|
||||
if "command_prefix" not in kwargs:
|
||||
kwargs["command_prefix"] = prefix_manager
|
||||
@@ -135,12 +149,19 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
if "command_not_found" not in kwargs:
|
||||
kwargs["command_not_found"] = "Command {} not found.\n{}"
|
||||
|
||||
message_cache_size = cli_flags.message_cache_size
|
||||
if cli_flags.no_message_cache:
|
||||
message_cache_size = None
|
||||
kwargs["max_messages"] = message_cache_size
|
||||
self._max_messages = message_cache_size
|
||||
|
||||
self._uptime = None
|
||||
self._checked_time_accuracy = None
|
||||
self._color = discord.Embed.Empty # This is needed or color ends up 0x000000
|
||||
|
||||
self._main_dir = bot_dir
|
||||
self._cog_mgr = CogManager()
|
||||
self._use_team_features = cli_flags.use_team_features
|
||||
super().__init__(*args, help_command=None, **kwargs)
|
||||
# Do not manually use the help formatter attribute here, see `send_help_for`,
|
||||
# for a documented API. The internals of this object are still subject to change.
|
||||
@@ -149,6 +170,74 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
|
||||
self._permissions_hooks: List[commands.CheckPredicate] = []
|
||||
self._red_ready = asyncio.Event()
|
||||
self._red_before_invoke_objs: Set[PreInvokeCoroutine] = set()
|
||||
|
||||
def get_command(self, name: str) -> Optional[commands.Command]:
|
||||
com = super().get_command(name)
|
||||
assert com is None or isinstance(com, commands.Command)
|
||||
return com
|
||||
|
||||
def get_cog(self, name: str) -> Optional[commands.Cog]:
|
||||
cog = super().get_cog(name)
|
||||
assert cog is None or isinstance(cog, commands.Cog)
|
||||
return cog
|
||||
|
||||
@property
|
||||
def _before_invoke(self): # DEP-WARN
|
||||
return self._red_before_invoke_method
|
||||
|
||||
@_before_invoke.setter
|
||||
def _before_invoke(self, val): # DEP-WARN
|
||||
"""Prevent this from being overwritten in super().__init__"""
|
||||
pass
|
||||
|
||||
async def _red_before_invoke_method(self, ctx):
|
||||
await self.wait_until_red_ready()
|
||||
return_exceptions = isinstance(ctx.command, commands.commands._AlwaysAvailableCommand)
|
||||
if self._red_before_invoke_objs:
|
||||
await asyncio.gather(
|
||||
*(coro(ctx) for coro in self._red_before_invoke_objs),
|
||||
return_exceptions=return_exceptions,
|
||||
)
|
||||
|
||||
def remove_before_invoke_hook(self, coro: PreInvokeCoroutine) -> None:
|
||||
"""
|
||||
Functional method to remove a `before_invoke` hook.
|
||||
"""
|
||||
self._red_before_invoke_objs.discard(coro)
|
||||
|
||||
def before_invoke(self, coro: T_BIC) -> T_BIC:
|
||||
"""
|
||||
Overridden decorator method for Red's ``before_invoke`` behavior.
|
||||
|
||||
This can safely be used purely functionally as well.
|
||||
|
||||
3rd party cogs should remove any hooks which they register at unload
|
||||
using `remove_before_invoke_hook`
|
||||
|
||||
Below behavior shared with discord.py:
|
||||
|
||||
.. note::
|
||||
The ``before_invoke`` hooks are
|
||||
only called if all checks and argument parsing procedures pass
|
||||
without error. If any check or argument parsing procedures fail
|
||||
then the hooks are not called.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
coro: Callable[[commands.Context], Awaitable[Any]]
|
||||
The coroutine to register as the pre-invoke hook.
|
||||
|
||||
Raises
|
||||
------
|
||||
TypeError
|
||||
The coroutine passed is not actually a coroutine.
|
||||
"""
|
||||
if not asyncio.iscoroutinefunction(coro):
|
||||
raise TypeError("The pre-invoke hook must be a coroutine.")
|
||||
|
||||
self._red_before_invoke_objs.add(coro)
|
||||
return coro
|
||||
|
||||
@property
|
||||
def cog_mgr(self) -> NoReturn:
|
||||
@@ -188,6 +277,10 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
def colour(self) -> NoReturn:
|
||||
raise AttributeError("Please fetch the embed colour with `get_embed_colour`")
|
||||
|
||||
@property
|
||||
def max_messages(self) -> Optional[int]:
|
||||
return self._max_messages
|
||||
|
||||
async def allowed_by_whitelist_blacklist(
|
||||
self,
|
||||
who: Optional[Union[discord.Member, discord.User]] = None,
|
||||
@@ -199,15 +292,15 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
"""
|
||||
This checks if a user or member is allowed to run things,
|
||||
as considered by Red's whitelist and blacklist.
|
||||
|
||||
|
||||
If given a user object, this function will check the global lists
|
||||
|
||||
|
||||
If given a member, this will additionally check guild lists
|
||||
|
||||
|
||||
If omiting a user or member, you must provide a value for ``who_id``
|
||||
|
||||
|
||||
You may also provide a value for ``guild_id`` in this case
|
||||
|
||||
|
||||
If providing a member by guild and member ids,
|
||||
you should supply ``role_ids`` as well
|
||||
|
||||
@@ -215,7 +308,7 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
----------
|
||||
who : Optional[Union[discord.Member, discord.User]]
|
||||
The user or member object to check
|
||||
|
||||
|
||||
Other Parameters
|
||||
----------------
|
||||
who_id : Optional[int]
|
||||
@@ -232,7 +325,7 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
------
|
||||
TypeError
|
||||
Did not provide ``who`` or ``who_id``
|
||||
|
||||
|
||||
Returns
|
||||
-------
|
||||
bool
|
||||
@@ -400,6 +493,7 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
This should only be run once, prior to connecting to discord.
|
||||
"""
|
||||
await self._maybe_update_config()
|
||||
self.description = await self._config.description()
|
||||
|
||||
init_global_checks(self)
|
||||
init_events(self, cli_flags)
|
||||
@@ -547,23 +641,57 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
bool
|
||||
:code:`True` if an embed is requested
|
||||
"""
|
||||
if isinstance(channel, discord.abc.PrivateChannel) or (
|
||||
command and command == self.get_command("help")
|
||||
):
|
||||
if isinstance(channel, discord.abc.PrivateChannel):
|
||||
user_setting = await self._config.user(user).embeds()
|
||||
if user_setting is not None:
|
||||
return user_setting
|
||||
else:
|
||||
channel_setting = await self._config.channel(channel).embeds()
|
||||
if channel_setting is not None:
|
||||
return channel_setting
|
||||
guild_setting = await self._config.guild(channel.guild).embeds()
|
||||
if guild_setting is not None:
|
||||
return guild_setting
|
||||
|
||||
global_setting = await self._config.embeds()
|
||||
return global_setting
|
||||
|
||||
async def is_owner(self, user) -> bool:
|
||||
async def is_owner(self, user: Union[discord.User, discord.Member]) -> bool:
|
||||
"""
|
||||
Determines if the user should be considered a bot owner.
|
||||
|
||||
This takes into account CLI flags and application ownership.
|
||||
|
||||
By default,
|
||||
application team members are not considered owners,
|
||||
while individual application owners are.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
user: Union[discord.User, discord.Member]
|
||||
|
||||
Returns
|
||||
-------
|
||||
bool
|
||||
"""
|
||||
if user.id in self._co_owners:
|
||||
return True
|
||||
return await super().is_owner(user)
|
||||
|
||||
if self.owner_id:
|
||||
return self.owner_id == user.id
|
||||
elif self.owner_ids:
|
||||
return user.id in self.owner_ids
|
||||
else:
|
||||
app = await self.application_info()
|
||||
if app.team:
|
||||
if self._use_team_features:
|
||||
self.owner_ids = ids = {m.id for m in app.team.members}
|
||||
return user.id in ids
|
||||
else:
|
||||
self.owner_id = owner_id = app.owner.id
|
||||
return user.id == owner_id
|
||||
|
||||
return False
|
||||
|
||||
async def is_admin(self, member: discord.Member) -> bool:
|
||||
"""Checks if a member is an admin of their guild."""
|
||||
@@ -831,7 +959,7 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
This should realistically only be used for responding using user provided
|
||||
input. (unfortunately, including usernames)
|
||||
Manually crafted messages which dont take any user input have no need of this
|
||||
|
||||
|
||||
Returns
|
||||
-------
|
||||
discord.Message
|
||||
@@ -1002,10 +1130,11 @@ class RedBase(commands.GroupMixin, commands.bot.BotBase, RPCMixin): # pylint: d
|
||||
await self.wait_until_red_ready()
|
||||
destinations = []
|
||||
opt_outs = await self._config.owner_opt_out_list()
|
||||
for user_id in (self.owner_id, *self._co_owners):
|
||||
team_ids = () if not self._use_team_features else self.owner_ids
|
||||
for user_id in set((self.owner_id, *self._co_owners, *team_ids)):
|
||||
if user_id not in opt_outs:
|
||||
user = self.get_user(user_id)
|
||||
if user:
|
||||
if user and not user.bot: # user.bot is possible with flags and teams
|
||||
destinations.append(user)
|
||||
else:
|
||||
log.warning(
|
||||
|
||||
@@ -74,6 +74,22 @@ async def interactive_config(red, token_set, prefix_set, *, print_header=True):
|
||||
return token
|
||||
|
||||
|
||||
def positive_int(arg: str) -> int:
|
||||
try:
|
||||
x = int(arg)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError("Message cache size has to be a number.")
|
||||
if x < 1000:
|
||||
raise argparse.ArgumentTypeError(
|
||||
"Message cache size has to be greater than or equal to 1000."
|
||||
)
|
||||
if x > sys.maxsize:
|
||||
raise argparse.ArgumentTypeError(
|
||||
f"Message cache size has to be lower than or equal to {sys.maxsize}."
|
||||
)
|
||||
return x
|
||||
|
||||
|
||||
def parse_cli_flags(args):
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Red - Discord Bot", usage="redbot <instance_name> [arguments]"
|
||||
@@ -90,7 +106,7 @@ def parse_cli_flags(args):
|
||||
action="store_true",
|
||||
help="Edit the instance. This can be done without console interaction "
|
||||
"by passing --no-prompt and arguments that you want to change (available arguments: "
|
||||
"--edit-instance-name, --edit-data-path, --copy-data, --owner, --token).",
|
||||
"--edit-instance-name, --edit-data-path, --copy-data, --owner, --token, --prefix).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--edit-instance-name",
|
||||
@@ -135,7 +151,9 @@ def parse_cli_flags(args):
|
||||
"security implications if misused. Can be "
|
||||
"multiple.",
|
||||
)
|
||||
parser.add_argument("--prefix", "-p", action="append", help="Global prefix. Can be multiple")
|
||||
parser.add_argument(
|
||||
"--prefix", "-p", action="append", help="Global prefix. Can be multiple", default=[]
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-prompt",
|
||||
action="store_true",
|
||||
@@ -198,6 +216,27 @@ def parse_cli_flags(args):
|
||||
parser.add_argument(
|
||||
"instance_name", nargs="?", help="Name of the bot instance created during `redbot-setup`."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--team-members-are-owners",
|
||||
action="store_true",
|
||||
dest="use_team_features",
|
||||
default=False,
|
||||
help=(
|
||||
"Treat application team members as owners. "
|
||||
"This is off by default. Owners can load and run arbitrary code. "
|
||||
"Do not enable if you would not trust all of your team members with "
|
||||
"all of the data on the host machine."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--message-cache-size",
|
||||
type=positive_int,
|
||||
default=1000,
|
||||
help="Set the maximum number of messages to store in the internal message cache.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-message-cache", action="store_true", help="Disable the internal message cache.",
|
||||
)
|
||||
|
||||
args = parser.parse_args(args)
|
||||
|
||||
|
||||
@@ -1,7 +1,145 @@
|
||||
from discord.ext.commands import *
|
||||
from .commands import *
|
||||
from .context import *
|
||||
from .converter import *
|
||||
from .errors import *
|
||||
from .requires import *
|
||||
from .help import *
|
||||
########## SENSITIVE SECTION WARNING ###########
|
||||
################################################
|
||||
# Any edits of any of the exported names #
|
||||
# may result in a breaking change. #
|
||||
# Ensure no names are removed without warning. #
|
||||
################################################
|
||||
|
||||
from .commands import (
|
||||
Cog as Cog,
|
||||
CogMixin as CogMixin,
|
||||
CogCommandMixin as CogCommandMixin,
|
||||
CogGroupMixin as CogGroupMixin,
|
||||
Command as Command,
|
||||
Group as Group,
|
||||
GroupMixin as GroupMixin,
|
||||
command as command,
|
||||
group as group,
|
||||
RESERVED_COMMAND_NAMES as RESERVED_COMMAND_NAMES,
|
||||
)
|
||||
from .context import Context as Context, GuildContext as GuildContext, DMContext as DMContext
|
||||
from .converter import (
|
||||
APIToken as APIToken,
|
||||
DictConverter as DictConverter,
|
||||
GuildConverter as GuildConverter,
|
||||
TimedeltaConverter as TimedeltaConverter,
|
||||
get_dict_converter as get_dict_converter,
|
||||
get_timedelta_converter as get_timedelta_converter,
|
||||
parse_timedelta as parse_timedelta,
|
||||
NoParseOptional as NoParseOptional,
|
||||
UserInputOptional as UserInputOptional,
|
||||
Literal as Literal,
|
||||
)
|
||||
from .errors import (
|
||||
ConversionFailure as ConversionFailure,
|
||||
BotMissingPermissions as BotMissingPermissions,
|
||||
UserFeedbackCheckFailure as UserFeedbackCheckFailure,
|
||||
ArgParserFailure as ArgParserFailure,
|
||||
)
|
||||
from .help import (
|
||||
red_help as red_help,
|
||||
RedHelpFormatter as RedHelpFormatter,
|
||||
HelpSettings as HelpSettings,
|
||||
)
|
||||
from .requires import (
|
||||
CheckPredicate as CheckPredicate,
|
||||
DM_PERMS as DM_PERMS,
|
||||
GlobalPermissionModel as GlobalPermissionModel,
|
||||
GuildPermissionModel as GuildPermissionModel,
|
||||
PermissionModel as PermissionModel,
|
||||
PrivilegeLevel as PrivilegeLevel,
|
||||
PermState as PermState,
|
||||
Requires as Requires,
|
||||
permissions_check as permissions_check,
|
||||
bot_has_permissions as bot_has_permissions,
|
||||
has_permissions as has_permissions,
|
||||
has_guild_permissions as has_guild_permissions,
|
||||
is_owner as is_owner,
|
||||
guildowner as guildowner,
|
||||
guildowner_or_permissions as guildowner_or_permissions,
|
||||
admin as admin,
|
||||
admin_or_permissions as admin_or_permissions,
|
||||
mod as mod,
|
||||
mod_or_permissions as mod_or_permissions,
|
||||
)
|
||||
|
||||
from ._dpy_reimplements import (
|
||||
check as check,
|
||||
guild_only as guild_only,
|
||||
cooldown as cooldown,
|
||||
dm_only as dm_only,
|
||||
is_nsfw as is_nsfw,
|
||||
has_role as has_role,
|
||||
has_any_role as has_any_role,
|
||||
bot_has_role as bot_has_role,
|
||||
when_mentioned_or as when_mentioned_or,
|
||||
when_mentioned as when_mentioned,
|
||||
bot_has_any_role as bot_has_any_role,
|
||||
)
|
||||
|
||||
### DEP-WARN: Check this *every* discord.py update
|
||||
from discord.ext.commands import (
|
||||
BadArgument as BadArgument,
|
||||
EmojiConverter as EmojiConverter,
|
||||
InvalidEndOfQuotedStringError as InvalidEndOfQuotedStringError,
|
||||
MemberConverter as MemberConverter,
|
||||
BotMissingRole as BotMissingRole,
|
||||
PrivateMessageOnly as PrivateMessageOnly,
|
||||
HelpCommand as HelpCommand,
|
||||
MinimalHelpCommand as MinimalHelpCommand,
|
||||
DisabledCommand as DisabledCommand,
|
||||
ExtensionFailed as ExtensionFailed,
|
||||
Bot as Bot,
|
||||
NotOwner as NotOwner,
|
||||
CategoryChannelConverter as CategoryChannelConverter,
|
||||
CogMeta as CogMeta,
|
||||
ConversionError as ConversionError,
|
||||
UserInputError as UserInputError,
|
||||
Converter as Converter,
|
||||
InviteConverter as InviteConverter,
|
||||
ExtensionError as ExtensionError,
|
||||
Cooldown as Cooldown,
|
||||
CheckFailure as CheckFailure,
|
||||
MessageConverter as MessageConverter,
|
||||
MissingPermissions as MissingPermissions,
|
||||
BadUnionArgument as BadUnionArgument,
|
||||
DefaultHelpCommand as DefaultHelpCommand,
|
||||
ExtensionNotFound as ExtensionNotFound,
|
||||
UserConverter as UserConverter,
|
||||
MissingRole as MissingRole,
|
||||
CommandOnCooldown as CommandOnCooldown,
|
||||
MissingAnyRole as MissingAnyRole,
|
||||
ExtensionNotLoaded as ExtensionNotLoaded,
|
||||
clean_content as clean_content,
|
||||
CooldownMapping as CooldownMapping,
|
||||
ArgumentParsingError as ArgumentParsingError,
|
||||
RoleConverter as RoleConverter,
|
||||
CommandError as CommandError,
|
||||
TextChannelConverter as TextChannelConverter,
|
||||
UnexpectedQuoteError as UnexpectedQuoteError,
|
||||
Paginator as Paginator,
|
||||
BucketType as BucketType,
|
||||
NoEntryPointError as NoEntryPointError,
|
||||
CommandInvokeError as CommandInvokeError,
|
||||
TooManyArguments as TooManyArguments,
|
||||
Greedy as Greedy,
|
||||
ExpectedClosingQuoteError as ExpectedClosingQuoteError,
|
||||
ColourConverter as ColourConverter,
|
||||
VoiceChannelConverter as VoiceChannelConverter,
|
||||
NSFWChannelRequired as NSFWChannelRequired,
|
||||
IDConverter as IDConverter,
|
||||
MissingRequiredArgument as MissingRequiredArgument,
|
||||
GameConverter as GameConverter,
|
||||
CommandNotFound as CommandNotFound,
|
||||
BotMissingAnyRole as BotMissingAnyRole,
|
||||
NoPrivateMessage as NoPrivateMessage,
|
||||
AutoShardedBot as AutoShardedBot,
|
||||
ExtensionAlreadyLoaded as ExtensionAlreadyLoaded,
|
||||
PartialEmojiConverter as PartialEmojiConverter,
|
||||
check_any as check_any,
|
||||
max_concurrency as max_concurrency,
|
||||
CheckAnyFailure as CheckAnyFailure,
|
||||
MaxConcurrency as MaxConcurrency,
|
||||
MaxConcurrencyReached as MaxConcurrencyReached,
|
||||
bot_has_guild_permissions as bot_has_guild_permissions,
|
||||
)
|
||||
|
||||
126
redbot/core/commands/_dpy_reimplements.py
Normal file
126
redbot/core/commands/_dpy_reimplements.py
Normal file
@@ -0,0 +1,126 @@
|
||||
from __future__ import annotations
|
||||
import inspect
|
||||
import functools
|
||||
from typing import (
|
||||
TypeVar,
|
||||
Callable,
|
||||
Awaitable,
|
||||
Coroutine,
|
||||
Union,
|
||||
Type,
|
||||
TYPE_CHECKING,
|
||||
List,
|
||||
Any,
|
||||
Generator,
|
||||
Protocol,
|
||||
overload,
|
||||
)
|
||||
|
||||
import discord
|
||||
from discord.ext import commands as dpy_commands
|
||||
|
||||
# So much of this can be stripped right back out with proper stubs.
|
||||
if not TYPE_CHECKING:
|
||||
from discord.ext.commands import (
|
||||
check as check,
|
||||
guild_only as guild_only,
|
||||
dm_only as dm_only,
|
||||
is_nsfw as is_nsfw,
|
||||
has_role as has_role,
|
||||
has_any_role as has_any_role,
|
||||
bot_has_role as bot_has_role,
|
||||
bot_has_any_role as bot_has_any_role,
|
||||
cooldown as cooldown,
|
||||
)
|
||||
|
||||
from ..i18n import Translator
|
||||
from .context import Context
|
||||
from .commands import Command
|
||||
|
||||
|
||||
_ = Translator("nah", __file__)
|
||||
|
||||
|
||||
"""
|
||||
Anything here is either a reimplementation or re-export
|
||||
of a discord.py funtion or class with more lies for mypy
|
||||
"""
|
||||
|
||||
__all__ = [
|
||||
"check",
|
||||
# "check_any", # discord.py 1.3
|
||||
"guild_only",
|
||||
"dm_only",
|
||||
"is_nsfw",
|
||||
"has_role",
|
||||
"has_any_role",
|
||||
"bot_has_role",
|
||||
"bot_has_any_role",
|
||||
"when_mentioned_or",
|
||||
"cooldown",
|
||||
"when_mentioned",
|
||||
]
|
||||
|
||||
_CT = TypeVar("_CT", bound=Context)
|
||||
_T = TypeVar("_T")
|
||||
_F = TypeVar("_F")
|
||||
CheckType = Union[Callable[[_CT], bool], Callable[[_CT], Coroutine[Any, Any, bool]]]
|
||||
CoroLike = Callable[..., Union[Awaitable[_T], Generator[Any, None, _T]]]
|
||||
|
||||
|
||||
class CheckDecorator(Protocol):
|
||||
predicate: Coroutine[Any, Any, bool]
|
||||
|
||||
@overload
|
||||
def __call__(self, func: _CT) -> _CT:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __call__(self, func: CoroLike) -> CoroLike:
|
||||
...
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def check(predicate: CheckType) -> CheckDecorator:
|
||||
...
|
||||
|
||||
def guild_only() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def dm_only() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def is_nsfw() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def has_role() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def has_any_role() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def bot_has_role() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def bot_has_any_role() -> CheckDecorator:
|
||||
...
|
||||
|
||||
def cooldown(rate: int, per: float, type: dpy_commands.BucketType = ...) -> Callable[[_F], _F]:
|
||||
...
|
||||
|
||||
|
||||
PrefixCallable = Callable[[dpy_commands.bot.BotBase, discord.Message], List[str]]
|
||||
|
||||
|
||||
def when_mentioned(bot: dpy_commands.bot.BotBase, msg: discord.Message) -> List[str]:
|
||||
return [f"<@{bot.user.id}> ", f"<@!{bot.user.id}> "]
|
||||
|
||||
|
||||
def when_mentioned_or(*prefixes) -> PrefixCallable:
|
||||
def inner(bot: dpy_commands.bot.BotBase, msg: discord.Message) -> List[str]:
|
||||
r = list(prefixes)
|
||||
r = when_mentioned(bot, msg) + r
|
||||
return r
|
||||
|
||||
return inner
|
||||
@@ -1,23 +1,53 @@
|
||||
"""Module for command helpers and classes.
|
||||
|
||||
This module contains extended classes and functions which are intended to
|
||||
replace those from the `discord.ext.commands` module.
|
||||
be used instead of those from the `discord.ext.commands` module.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import re
|
||||
import weakref
|
||||
from typing import Awaitable, Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING
|
||||
from typing import (
|
||||
Awaitable,
|
||||
Callable,
|
||||
Coroutine,
|
||||
TypeVar,
|
||||
Type,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
MutableMapping,
|
||||
TYPE_CHECKING,
|
||||
cast,
|
||||
)
|
||||
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from discord.ext.commands import (
|
||||
BadArgument,
|
||||
CommandError,
|
||||
CheckFailure,
|
||||
DisabledCommand,
|
||||
command as dpy_command_deco,
|
||||
Command as DPYCommand,
|
||||
Cog as DPYCog,
|
||||
CogMeta as DPYCogMeta,
|
||||
Group as DPYGroup,
|
||||
Greedy,
|
||||
)
|
||||
|
||||
from . import converter as converters
|
||||
from .errors import ConversionFailure
|
||||
from .requires import PermState, PrivilegeLevel, Requires
|
||||
from .requires import PermState, PrivilegeLevel, Requires, PermStateAllowedStates
|
||||
from ..i18n import Translator
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# circular import avoidance
|
||||
from .context import Context
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Cog",
|
||||
"CogMixin",
|
||||
@@ -37,11 +67,17 @@ RESERVED_COMMAND_NAMES = (
|
||||
)
|
||||
|
||||
_ = Translator("commands.commands", __file__)
|
||||
DisablerDictType = MutableMapping[discord.Guild, Callable[["Context"], Awaitable[bool]]]
|
||||
|
||||
|
||||
class CogCommandMixin:
|
||||
"""A mixin for cogs and commands."""
|
||||
|
||||
@property
|
||||
def help(self) -> str:
|
||||
"""To be defined by subclasses"""
|
||||
...
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if isinstance(self, Command):
|
||||
@@ -57,6 +93,77 @@ class CogCommandMixin:
|
||||
checks=getattr(decorated, "__requires_checks__", []),
|
||||
)
|
||||
|
||||
def format_text_for_context(self, ctx: "Context", text: str) -> str:
|
||||
"""
|
||||
This formats text based on values in context
|
||||
|
||||
The steps are (currently, roughly) the following:
|
||||
|
||||
- substitute ``[p]`` with ``ctx.clean_prefix``
|
||||
- substitute ``[botname]`` with ``ctx.me.display_name``
|
||||
|
||||
More steps may be added at a later time.
|
||||
|
||||
Cog creators should only override this if they want
|
||||
help text to be modified, and may also want to
|
||||
look at `format_help_for_context` and (for commands only)
|
||||
``format_shortdoc_for_context``
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ctx: Context
|
||||
text: str
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
text which has had some portions replaced based on context
|
||||
"""
|
||||
formatting_pattern = re.compile(r"\[p\]|\[botname\]")
|
||||
|
||||
def replacement(m: re.Match) -> str:
|
||||
s = m.group(0)
|
||||
if s == "[p]":
|
||||
return ctx.clean_prefix
|
||||
if s == "[botname]":
|
||||
return ctx.me.display_name
|
||||
# We shouldnt get here:
|
||||
return s
|
||||
|
||||
return formatting_pattern.sub(replacement, text)
|
||||
|
||||
def format_help_for_context(self, ctx: "Context") -> str:
|
||||
"""
|
||||
This formats the help string based on values in context
|
||||
|
||||
The steps are (currently, roughly) the following:
|
||||
|
||||
- get the localized help
|
||||
- substitute ``[p]`` with ``ctx.clean_prefix``
|
||||
- substitute ``[botname]`` with ``ctx.me.display_name``
|
||||
|
||||
More steps may be added at a later time.
|
||||
|
||||
Cog creators may override this in their own command classes
|
||||
as long as the method signature stays the same.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ctx: Context
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
Localized help with some formatting
|
||||
"""
|
||||
|
||||
help_str = self.help
|
||||
if not help_str:
|
||||
# Short circuit out on an empty help string
|
||||
return help_str
|
||||
|
||||
return self.format_text_for_context(ctx, help_str)
|
||||
|
||||
def allow_for(self, model_id: Union[int, str], guild_id: int) -> None:
|
||||
"""Actively allow this command for the given model.
|
||||
|
||||
@@ -138,7 +245,7 @@ class CogCommandMixin:
|
||||
self.deny_to(Requires.DEFAULT, guild_id=guild_id)
|
||||
|
||||
|
||||
class Command(CogCommandMixin, commands.Command):
|
||||
class Command(CogCommandMixin, DPYCommand):
|
||||
"""Command class for Red.
|
||||
|
||||
This should not be created directly, and instead via the decorator.
|
||||
@@ -154,10 +261,21 @@ class Command(CogCommandMixin, commands.Command):
|
||||
`Requires.checks`.
|
||||
translator : Translator
|
||||
A translator for this command's help docstring.
|
||||
|
||||
ignore_optional_for_conversion : bool
|
||||
A value which can be set to not have discord.py's
|
||||
argument parsing behavior for ``typing.Optional``
|
||||
(type used will be of the inner type instead)
|
||||
"""
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
if self.cog:
|
||||
# We need to inject cog as self here
|
||||
return self.callback(self.cog, *args, **kwargs)
|
||||
else:
|
||||
return self.callback(*args, **kwargs)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.ignore_optional_for_conversion = kwargs.pop("ignore_optional_for_conversion", False)
|
||||
super().__init__(*args, **kwargs)
|
||||
self._help_override = kwargs.pop("help_override", None)
|
||||
self.translator = kwargs.pop("i18n", None)
|
||||
@@ -178,8 +296,62 @@ class Command(CogCommandMixin, commands.Command):
|
||||
|
||||
# Red specific
|
||||
other.requires = self.requires
|
||||
other.ignore_optional_for_conversion = self.ignore_optional_for_conversion
|
||||
return other
|
||||
|
||||
@property
|
||||
def callback(self):
|
||||
return self._callback
|
||||
|
||||
@callback.setter
|
||||
def callback(self, function):
|
||||
"""
|
||||
Below should be mostly the same as discord.py
|
||||
The only (current) change is to filter out typing.Optional
|
||||
if a user has specified the desire for this behavior
|
||||
"""
|
||||
self._callback = function
|
||||
self.module = function.__module__
|
||||
|
||||
signature = inspect.signature(function)
|
||||
self.params = signature.parameters.copy()
|
||||
|
||||
# PEP-563 allows postponing evaluation of annotations with a __future__
|
||||
# import. When postponed, Parameter.annotation will be a string and must
|
||||
# be replaced with the real value for the converters to work later on
|
||||
for key, value in self.params.items():
|
||||
if isinstance(value.annotation, str):
|
||||
self.params[key] = value = value.replace(
|
||||
annotation=eval(value.annotation, function.__globals__)
|
||||
)
|
||||
|
||||
# fail early for when someone passes an unparameterized Greedy type
|
||||
if value.annotation is Greedy:
|
||||
raise TypeError("Unparameterized Greedy[...] is disallowed in signature.")
|
||||
|
||||
if not self.ignore_optional_for_conversion:
|
||||
continue # reduces indentation compared to alternative
|
||||
|
||||
try:
|
||||
vtype = value.annotation.__origin__
|
||||
if vtype is Union:
|
||||
_NoneType = type if TYPE_CHECKING else type(None)
|
||||
args = value.annotation.__args__
|
||||
if _NoneType in args:
|
||||
args = tuple(a for a in args if a is not _NoneType)
|
||||
if len(args) == 1:
|
||||
# can't have a union of 1 or 0 items
|
||||
# 1 prevents this from becoming 0
|
||||
# we need to prevent 2 become 1
|
||||
# (Don't change that to becoming, it's intentional :musical_note:)
|
||||
self.params[key] = value = value.replace(annotation=args[0])
|
||||
else:
|
||||
# and mypy wretches at the correct Union[args]
|
||||
temp_type = type if TYPE_CHECKING else Union[args]
|
||||
self.params[key] = value = value.replace(annotation=temp_type)
|
||||
except AttributeError:
|
||||
continue
|
||||
|
||||
@property
|
||||
def help(self):
|
||||
"""Help string for this command.
|
||||
@@ -260,7 +432,7 @@ class Command(CogCommandMixin, commands.Command):
|
||||
for parent in reversed(self.parents):
|
||||
try:
|
||||
result = await parent.can_run(ctx, change_permission_state=True)
|
||||
except commands.CommandError:
|
||||
except CommandError:
|
||||
result = False
|
||||
|
||||
if result is False:
|
||||
@@ -279,14 +451,24 @@ class Command(CogCommandMixin, commands.Command):
|
||||
if not change_permission_state:
|
||||
ctx.permission_state = original_state
|
||||
|
||||
async def _verify_checks(self, ctx):
|
||||
if not self.enabled:
|
||||
raise commands.DisabledCommand(f"{self.name} command is disabled")
|
||||
async def prepare(self, ctx):
|
||||
ctx.command = self
|
||||
|
||||
if not (await self.can_run(ctx, change_permission_state=True)):
|
||||
raise commands.CheckFailure(
|
||||
f"The check functions for command {self.qualified_name} failed."
|
||||
)
|
||||
if not self.enabled:
|
||||
raise DisabledCommand(f"{self.name} command is disabled")
|
||||
|
||||
if not await self.can_run(ctx, change_permission_state=True):
|
||||
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
|
||||
|
||||
if self.cooldown_after_parsing:
|
||||
await self._parse_arguments(ctx)
|
||||
self._prepare_cooldowns(ctx)
|
||||
else:
|
||||
self._prepare_cooldowns(ctx)
|
||||
await self._parse_arguments(ctx)
|
||||
if self._max_concurrency is not None:
|
||||
await self._max_concurrency.acquire(ctx)
|
||||
await self.call_before_hooks(ctx)
|
||||
|
||||
async def do_conversion(
|
||||
self, ctx: "Context", converter, argument: str, param: inspect.Parameter
|
||||
@@ -310,7 +492,7 @@ class Command(CogCommandMixin, commands.Command):
|
||||
|
||||
try:
|
||||
return await super().do_conversion(ctx, converter, argument, param)
|
||||
except commands.BadArgument as exc:
|
||||
except BadArgument as exc:
|
||||
raise ConversionFailure(converter, argument, param, *exc.args) from exc
|
||||
except ValueError as exc:
|
||||
# Some common converters need special treatment...
|
||||
@@ -345,7 +527,7 @@ class Command(CogCommandMixin, commands.Command):
|
||||
can_run = await self.can_run(
|
||||
ctx, check_all_parents=True, change_permission_state=False
|
||||
)
|
||||
except (commands.CheckFailure, commands.errors.DisabledCommand):
|
||||
except (CheckFailure, DisabledCommand):
|
||||
return False
|
||||
else:
|
||||
if can_run is False:
|
||||
@@ -465,6 +647,28 @@ class Command(CogCommandMixin, commands.Command):
|
||||
"""
|
||||
return super().error(coro)
|
||||
|
||||
def format_shortdoc_for_context(self, ctx: "Context") -> str:
|
||||
"""
|
||||
This formats the short version of the help
|
||||
tring based on values in context
|
||||
|
||||
See ``format_text_for_context`` for the actual implementation details
|
||||
|
||||
Cog creators may override this in their own command classes
|
||||
as long as the method signature stays the same.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ctx: Context
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
Localized help with some formatting
|
||||
"""
|
||||
sh = self.short_doc
|
||||
return self.format_text_for_context(ctx, sh) if sh else sh
|
||||
|
||||
|
||||
class GroupMixin(discord.ext.commands.GroupMixin):
|
||||
"""Mixin for `Group` and `Red` classes.
|
||||
@@ -501,10 +705,9 @@ class GroupMixin(discord.ext.commands.GroupMixin):
|
||||
|
||||
class CogGroupMixin:
|
||||
requires: Requires
|
||||
all_commands: Dict[str, Command]
|
||||
|
||||
def reevaluate_rules_for(
|
||||
self, model_id: Union[str, int], guild_id: Optional[int]
|
||||
self, model_id: Union[str, int], guild_id: int = 0
|
||||
) -> Tuple[PermState, bool]:
|
||||
"""Re-evaluate a rule by checking subcommand rules.
|
||||
|
||||
@@ -527,15 +730,16 @@ class CogGroupMixin:
|
||||
|
||||
"""
|
||||
cur_rule = self.requires.get_rule(model_id, guild_id=guild_id)
|
||||
if cur_rule in (PermState.NORMAL, PermState.ACTIVE_ALLOW, PermState.ACTIVE_DENY):
|
||||
# These three states are unaffected by subcommand rules
|
||||
return cur_rule, False
|
||||
else:
|
||||
if cur_rule not in (PermState.NORMAL, PermState.ACTIVE_ALLOW, PermState.ACTIVE_DENY):
|
||||
# The above three states are unaffected by subcommand rules
|
||||
# Remaining states can be changed if there exists no actively-allowed
|
||||
# subcommand (this includes subcommands multiple levels below)
|
||||
|
||||
all_commands: Dict[str, Command] = getattr(self, "all_commands", {})
|
||||
|
||||
if any(
|
||||
cmd.requires.get_rule(model_id, guild_id=guild_id) in PermState.ALLOWED_STATES
|
||||
for cmd in self.all_commands.values()
|
||||
cmd.requires.get_rule(model_id, guild_id=guild_id) in PermStateAllowedStates
|
||||
for cmd in all_commands.values()
|
||||
):
|
||||
return cur_rule, False
|
||||
elif cur_rule is PermState.PASSIVE_ALLOW:
|
||||
@@ -545,8 +749,11 @@ class CogGroupMixin:
|
||||
self.requires.set_rule(model_id, PermState.ACTIVE_DENY, guild_id=guild_id)
|
||||
return PermState.ACTIVE_DENY, True
|
||||
|
||||
# Default return value
|
||||
return cur_rule, False
|
||||
|
||||
class Group(GroupMixin, Command, CogGroupMixin, commands.Group):
|
||||
|
||||
class Group(GroupMixin, Command, CogGroupMixin, DPYGroup):
|
||||
"""Group command class for Red.
|
||||
|
||||
This class inherits from `Command`, with :class:`GroupMixin` and
|
||||
@@ -574,14 +781,14 @@ class Group(GroupMixin, Command, CogGroupMixin, commands.Group):
|
||||
|
||||
if ctx.invoked_subcommand is None or self == ctx.invoked_subcommand:
|
||||
if self.autohelp and not self.invoke_without_command:
|
||||
await self._verify_checks(ctx)
|
||||
await self.can_run(ctx, change_permission_state=True)
|
||||
await ctx.send_help()
|
||||
elif self.invoke_without_command:
|
||||
# So invoke_without_command when a subcommand of this group is invoked
|
||||
# will skip the the invokation of *this* command. However, because of
|
||||
# how our permissions system works, we don't want it to skip the checks
|
||||
# as well.
|
||||
await self._verify_checks(ctx)
|
||||
await self.can_run(ctx, change_permission_state=True)
|
||||
# this is actually why we don't prepare earlier.
|
||||
|
||||
await super().invoke(ctx)
|
||||
@@ -590,14 +797,6 @@ class Group(GroupMixin, Command, CogGroupMixin, commands.Group):
|
||||
class CogMixin(CogGroupMixin, CogCommandMixin):
|
||||
"""Mixin class for a cog, intended for use with discord.py's cog class"""
|
||||
|
||||
@property
|
||||
def all_commands(self) -> Dict[str, Command]:
|
||||
"""
|
||||
This does not have identical behavior to
|
||||
Group.all_commands but should return what you expect
|
||||
"""
|
||||
return {cmd.name: cmd for cmd in self.__cog_commands__}
|
||||
|
||||
@property
|
||||
def help(self):
|
||||
doc = self.__doc__
|
||||
@@ -609,7 +808,7 @@ class CogMixin(CogGroupMixin, CogCommandMixin):
|
||||
"""
|
||||
This really just exists to allow easy use with other methods using can_run
|
||||
on commands and groups such as help formatters.
|
||||
|
||||
|
||||
kwargs used in that won't apply here as they don't make sense to,
|
||||
but will be swallowed silently for a compatible signature for ease of use.
|
||||
|
||||
@@ -626,7 +825,7 @@ class CogMixin(CogGroupMixin, CogCommandMixin):
|
||||
|
||||
try:
|
||||
can_run = await self.requires.verify(ctx)
|
||||
except commands.CommandError:
|
||||
except CommandError:
|
||||
return False
|
||||
|
||||
return can_run
|
||||
@@ -655,16 +854,22 @@ class CogMixin(CogGroupMixin, CogCommandMixin):
|
||||
return await self.can_run(ctx)
|
||||
|
||||
|
||||
class Cog(CogMixin, commands.Cog):
|
||||
class Cog(CogMixin, DPYCog, metaclass=DPYCogMeta):
|
||||
"""
|
||||
Red's Cog base class
|
||||
|
||||
This includes a metaclass from discord.py
|
||||
"""
|
||||
|
||||
# NB: Do not move the inheritcance of this. Keeping the mix of that metaclass
|
||||
# seperate gives us more freedoms in several places.
|
||||
pass
|
||||
__cog_commands__: Tuple[Command]
|
||||
|
||||
@property
|
||||
def all_commands(self) -> Dict[str, Command]:
|
||||
"""
|
||||
This does not have identical behavior to
|
||||
Group.all_commands but should return what you expect
|
||||
"""
|
||||
return {cmd.name: cmd for cmd in self.__cog_commands__}
|
||||
|
||||
|
||||
def command(name=None, cls=Command, **attrs):
|
||||
@@ -673,7 +878,8 @@ def command(name=None, cls=Command, **attrs):
|
||||
Same interface as `discord.ext.commands.command`.
|
||||
"""
|
||||
attrs["help_override"] = attrs.pop("help", None)
|
||||
return commands.command(name, cls, **attrs)
|
||||
|
||||
return dpy_command_deco(name, cls, **attrs)
|
||||
|
||||
|
||||
def group(name=None, cls=Group, **attrs):
|
||||
@@ -681,10 +887,10 @@ def group(name=None, cls=Group, **attrs):
|
||||
|
||||
Same interface as `discord.ext.commands.group`.
|
||||
"""
|
||||
return command(name, cls, **attrs)
|
||||
return dpy_command_deco(name, cls, **attrs)
|
||||
|
||||
|
||||
__command_disablers = weakref.WeakValueDictionary()
|
||||
__command_disablers: DisablerDictType = weakref.WeakValueDictionary()
|
||||
|
||||
|
||||
def get_command_disabler(guild: discord.Guild) -> Callable[["Context"], Awaitable[bool]]:
|
||||
@@ -699,7 +905,7 @@ def get_command_disabler(guild: discord.Guild) -> Callable[["Context"], Awaitabl
|
||||
|
||||
async def disabler(ctx: "Context") -> bool:
|
||||
if ctx.guild == guild:
|
||||
raise commands.DisabledCommand()
|
||||
raise DisabledCommand()
|
||||
return True
|
||||
|
||||
__command_disablers[guild] = disabler
|
||||
@@ -727,6 +933,3 @@ class _AlwaysAvailableCommand(Command):
|
||||
|
||||
async def can_run(self, ctx, *args, **kwargs) -> bool:
|
||||
return not ctx.author.bot
|
||||
|
||||
async def _verify_checks(self, ctx) -> bool:
|
||||
return not ctx.author.bot
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
from typing import Iterable, List, Union
|
||||
from typing import Iterable, List, Union, Optional, TYPE_CHECKING
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from discord.ext.commands import Context as DPYContext
|
||||
|
||||
from .requires import PermState
|
||||
from ..utils.chat_formatting import box
|
||||
from ..utils.predicates import MessagePredicate
|
||||
from ..utils import common_filters
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .commands import Command
|
||||
from ..bot import Red
|
||||
|
||||
TICK = "\N{WHITE HEAVY CHECK MARK}"
|
||||
|
||||
__all__ = ["Context"]
|
||||
__all__ = ["Context", "GuildContext", "DMContext"]
|
||||
|
||||
|
||||
class Context(commands.Context):
|
||||
class Context(DPYContext):
|
||||
"""Command invocation context for Red.
|
||||
|
||||
All context passed into commands will be of this type.
|
||||
@@ -40,6 +47,10 @@ class Context(commands.Context):
|
||||
The permission state the current context is in.
|
||||
"""
|
||||
|
||||
command: "Command"
|
||||
invoked_subcommand: "Optional[Command]"
|
||||
bot: "Red"
|
||||
|
||||
def __init__(self, **attrs):
|
||||
self.assume_yes = attrs.pop("assume_yes", False)
|
||||
super().__init__(**attrs)
|
||||
@@ -254,7 +265,7 @@ class Context(commands.Context):
|
||||
return pattern.sub(f"@{me.display_name}", self.prefix)
|
||||
|
||||
@property
|
||||
def me(self) -> discord.abc.User:
|
||||
def me(self) -> Union[discord.ClientUser, discord.Member]:
|
||||
"""discord.abc.User: The bot member or user object.
|
||||
|
||||
If the context is DM, this will be a `discord.User` object.
|
||||
@@ -263,3 +274,63 @@ class Context(commands.Context):
|
||||
return self.guild.me
|
||||
else:
|
||||
return self.bot.user
|
||||
|
||||
|
||||
if TYPE_CHECKING or os.getenv("BUILDING_DOCS", False):
|
||||
|
||||
class DMContext(Context):
|
||||
"""
|
||||
At runtime, this will still be a normal context object.
|
||||
|
||||
This lies about some type narrowing for type analysis in commands
|
||||
using a dm_only decorator.
|
||||
|
||||
It is only correct to use when those types are already narrowed
|
||||
"""
|
||||
|
||||
@property
|
||||
def author(self) -> discord.User:
|
||||
...
|
||||
|
||||
@property
|
||||
def channel(self) -> discord.DMChannel:
|
||||
...
|
||||
|
||||
@property
|
||||
def guild(self) -> None:
|
||||
...
|
||||
|
||||
@property
|
||||
def me(self) -> discord.ClientUser:
|
||||
...
|
||||
|
||||
class GuildContext(Context):
|
||||
"""
|
||||
At runtime, this will still be a normal context object.
|
||||
|
||||
This lies about some type narrowing for type analysis in commands
|
||||
using a guild_only decorator.
|
||||
|
||||
It is only correct to use when those types are already narrowed
|
||||
"""
|
||||
|
||||
@property
|
||||
def author(self) -> discord.Member:
|
||||
...
|
||||
|
||||
@property
|
||||
def channel(self) -> discord.TextChannel:
|
||||
...
|
||||
|
||||
@property
|
||||
def guild(self) -> discord.Guild:
|
||||
...
|
||||
|
||||
@property
|
||||
def me(self) -> discord.Member:
|
||||
...
|
||||
|
||||
|
||||
else:
|
||||
GuildContext = Context
|
||||
DMContext = Context
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
"""
|
||||
commands.converter
|
||||
==================
|
||||
This module contains useful functions and classes for command argument conversion.
|
||||
|
||||
Some of the converters within are included provisionaly and are marked as such.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import functools
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING, Optional, List, Dict
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Generic,
|
||||
Optional,
|
||||
Optional as NoParseOptional,
|
||||
Tuple,
|
||||
List,
|
||||
Dict,
|
||||
Type,
|
||||
TypeVar,
|
||||
Literal as Literal,
|
||||
)
|
||||
|
||||
import discord
|
||||
from discord.ext import commands as dpy_commands
|
||||
from discord.ext.commands import BadArgument
|
||||
|
||||
from . import BadArgument
|
||||
from ..i18n import Translator
|
||||
from ..utils.chat_formatting import humanize_timedelta
|
||||
from ..utils.chat_formatting import humanize_timedelta, humanize_list
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .context import Context
|
||||
@@ -17,10 +36,13 @@ __all__ = [
|
||||
"APIToken",
|
||||
"DictConverter",
|
||||
"GuildConverter",
|
||||
"UserInputOptional",
|
||||
"NoParseOptional",
|
||||
"TimedeltaConverter",
|
||||
"get_dict_converter",
|
||||
"get_timedelta_converter",
|
||||
"parse_timedelta",
|
||||
"Literal",
|
||||
]
|
||||
|
||||
_ = Translator("commands.converter", __file__)
|
||||
@@ -67,7 +89,7 @@ def parse_timedelta(
|
||||
allowed_units : Optional[List[str]]
|
||||
If provided, you can constrain a user to expressing the amount of time
|
||||
in specific units. The units you can chose to provide are the same as the
|
||||
parser understands. `weeks` `days` `hours` `minutes` `seconds`
|
||||
parser understands. (``weeks``, ``days``, ``hours``, ``minutes``, ``seconds``)
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -138,17 +160,18 @@ class APIToken(discord.ext.commands.Converter):
|
||||
This will parse the input argument separating the key value pairs into a
|
||||
format to be used for the core bots API token storage.
|
||||
|
||||
This will split the argument by either `;` ` `, or `,` and return a dict
|
||||
This will split the argument by a space, comma, or semicolon and return a dict
|
||||
to be stored. Since all API's are different and have different naming convention,
|
||||
this leaves the onus on the cog creator to clearly define how to setup the correct
|
||||
credential names for their cogs.
|
||||
|
||||
Note: Core usage of this has been replaced with DictConverter use instead.
|
||||
Note: Core usage of this has been replaced with `DictConverter` use instead.
|
||||
|
||||
This may be removed at a later date (with warning)
|
||||
.. warning::
|
||||
This will be removed in version 3.4.
|
||||
"""
|
||||
|
||||
async def convert(self, ctx, argument) -> dict:
|
||||
async def convert(self, ctx: "Context", argument) -> dict:
|
||||
bot = ctx.bot
|
||||
result = {}
|
||||
match = re.split(r";|,| ", argument)
|
||||
@@ -162,140 +185,263 @@ class APIToken(discord.ext.commands.Converter):
|
||||
return result
|
||||
|
||||
|
||||
class DictConverter(dpy_commands.Converter):
|
||||
"""
|
||||
Converts pairs of space seperated values to a dict
|
||||
"""
|
||||
# Below this line are a lot of lies for mypy about things that *end up* correct when
|
||||
# These are used for command conversion purposes. Please refer to the portion
|
||||
# which is *not* for type checking for the actual implementation
|
||||
# and ensure the lies stay correct for how the object should look as a typehint
|
||||
|
||||
def __init__(self, *expected_keys: str, delims: Optional[List[str]] = None):
|
||||
self.expected_keys = expected_keys
|
||||
self.delims = delims or [" "]
|
||||
self.pattern = re.compile(r"|".join(re.escape(d) for d in self.delims))
|
||||
if TYPE_CHECKING:
|
||||
DictConverter = Dict[str, str]
|
||||
else:
|
||||
|
||||
async def convert(self, ctx: "Context", argument: str) -> Dict[str, str]:
|
||||
class DictConverter(dpy_commands.Converter):
|
||||
"""
|
||||
Converts pairs of space seperated values to a dict
|
||||
"""
|
||||
|
||||
ret: Dict[str, str] = {}
|
||||
args = self.pattern.split(argument)
|
||||
def __init__(self, *expected_keys: str, delims: Optional[List[str]] = None):
|
||||
self.expected_keys = expected_keys
|
||||
self.delims = delims or [" "]
|
||||
self.pattern = re.compile(r"|".join(re.escape(d) for d in self.delims))
|
||||
|
||||
if len(args) % 2 != 0:
|
||||
raise BadArgument()
|
||||
async def convert(self, ctx: "Context", argument: str) -> Dict[str, str]:
|
||||
ret: Dict[str, str] = {}
|
||||
args = self.pattern.split(argument)
|
||||
|
||||
iterator = iter(args)
|
||||
if len(args) % 2 != 0:
|
||||
raise BadArgument()
|
||||
|
||||
for key in iterator:
|
||||
if self.expected_keys and key not in self.expected_keys:
|
||||
raise BadArgument(_("Unexpected key {key}").format(key=key))
|
||||
iterator = iter(args)
|
||||
|
||||
ret[key] = next(iterator)
|
||||
for key in iterator:
|
||||
if self.expected_keys and key not in self.expected_keys:
|
||||
raise BadArgument(_("Unexpected key {key}").format(key=key))
|
||||
|
||||
return ret
|
||||
ret[key] = next(iterator)
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def get_dict_converter(*expected_keys: str, delims: Optional[List[str]] = None) -> type:
|
||||
"""
|
||||
Returns a typechecking safe `DictConverter` suitable for use with discord.py
|
||||
"""
|
||||
if TYPE_CHECKING:
|
||||
|
||||
class PartialMeta(type(DictConverter)):
|
||||
__call__ = functools.partialmethod(
|
||||
type(DictConverter).__call__, *expected_keys, delims=delims
|
||||
)
|
||||
|
||||
class ValidatedConverter(DictConverter, metaclass=PartialMeta):
|
||||
pass
|
||||
|
||||
return ValidatedConverter
|
||||
def get_dict_converter(*expected_keys: str, delims: Optional[List[str]] = None) -> Type[dict]:
|
||||
...
|
||||
|
||||
|
||||
class TimedeltaConverter(dpy_commands.Converter):
|
||||
"""
|
||||
This is a converter for timedeltas.
|
||||
The units should be in order from largest to smallest.
|
||||
This works with or without whitespace.
|
||||
else:
|
||||
|
||||
See `parse_timedelta` for more information about how this functions.
|
||||
def get_dict_converter(*expected_keys: str, delims: Optional[List[str]] = None) -> Type[dict]:
|
||||
"""
|
||||
Returns a typechecking safe `DictConverter` suitable for use with discord.py
|
||||
"""
|
||||
|
||||
Attributes
|
||||
----------
|
||||
maximum : Optional[timedelta]
|
||||
If provided, any parsed value higher than this will raise an exception
|
||||
minimum : Optional[timedelta]
|
||||
If provided, any parsed value lower than this will raise an exception
|
||||
allowed_units : Optional[List[str]]
|
||||
If provided, you can constrain a user to expressing the amount of time
|
||||
in specific units. The units you can chose to provide are the same as the
|
||||
parser understands: `weeks` `days` `hours` `minutes` `seconds`
|
||||
default_unit : Optional[str]
|
||||
If provided, it will additionally try to match integer-only input into
|
||||
a timedelta, using the unit specified. Same units as in `allowed_units`
|
||||
apply.
|
||||
"""
|
||||
class PartialMeta(type):
|
||||
__call__ = functools.partialmethod(
|
||||
type(DictConverter).__call__, *expected_keys, delims=delims
|
||||
)
|
||||
|
||||
def __init__(self, *, minimum=None, maximum=None, allowed_units=None, default_unit=None):
|
||||
self.allowed_units = allowed_units
|
||||
self.default_unit = default_unit
|
||||
self.minimum = minimum
|
||||
self.maximum = maximum
|
||||
class ValidatedConverter(DictConverter, metaclass=PartialMeta):
|
||||
pass
|
||||
|
||||
return ValidatedConverter
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
TimedeltaConverter = timedelta
|
||||
else:
|
||||
|
||||
class TimedeltaConverter(dpy_commands.Converter):
|
||||
"""
|
||||
This is a converter for timedeltas.
|
||||
The units should be in order from largest to smallest.
|
||||
This works with or without whitespace.
|
||||
|
||||
See `parse_timedelta` for more information about how this functions.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
maximum : Optional[timedelta]
|
||||
If provided, any parsed value higher than this will raise an exception
|
||||
minimum : Optional[timedelta]
|
||||
If provided, any parsed value lower than this will raise an exception
|
||||
allowed_units : Optional[List[str]]
|
||||
If provided, you can constrain a user to expressing the amount of time
|
||||
in specific units. The units you can choose to provide are the same as the
|
||||
parser understands: (``weeks``, ``days``, ``hours``, ``minutes``, ``seconds``)
|
||||
default_unit : Optional[str]
|
||||
If provided, it will additionally try to match integer-only input into
|
||||
a timedelta, using the unit specified. Same units as in ``allowed_units``
|
||||
apply.
|
||||
"""
|
||||
|
||||
def __init__(self, *, minimum=None, maximum=None, allowed_units=None, default_unit=None):
|
||||
self.allowed_units = allowed_units
|
||||
self.default_unit = default_unit
|
||||
self.minimum = minimum
|
||||
self.maximum = maximum
|
||||
|
||||
async def convert(self, ctx: "Context", argument: str) -> timedelta:
|
||||
if self.default_unit and argument.isdecimal():
|
||||
argument = argument + self.default_unit
|
||||
|
||||
async def convert(self, ctx: "Context", argument: str) -> timedelta:
|
||||
if self.default_unit and argument.isdecimal():
|
||||
delta = timedelta(**{self.default_unit: int(argument)})
|
||||
else:
|
||||
delta = parse_timedelta(
|
||||
argument,
|
||||
minimum=self.minimum,
|
||||
maximum=self.maximum,
|
||||
allowed_units=self.allowed_units,
|
||||
)
|
||||
if delta is not None:
|
||||
return delta
|
||||
raise BadArgument() # This allows this to be a required argument.
|
||||
|
||||
if delta is not None:
|
||||
return delta
|
||||
raise BadArgument() # This allows this to be a required argument.
|
||||
|
||||
|
||||
def get_timedelta_converter(
|
||||
*,
|
||||
default_unit: Optional[str] = None,
|
||||
maximum: Optional[timedelta] = None,
|
||||
minimum: Optional[timedelta] = None,
|
||||
allowed_units: Optional[List[str]] = None,
|
||||
) -> type:
|
||||
"""
|
||||
This creates a type suitable for typechecking which works with discord.py's
|
||||
commands.
|
||||
|
||||
See `parse_timedelta` for more information about how this functions.
|
||||
if TYPE_CHECKING:
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maximum : Optional[timedelta]
|
||||
If provided, any parsed value higher than this will raise an exception
|
||||
minimum : Optional[timedelta]
|
||||
If provided, any parsed value lower than this will raise an exception
|
||||
allowed_units : Optional[List[str]]
|
||||
If provided, you can constrain a user to expressing the amount of time
|
||||
in specific units. The units you can chose to provide are the same as the
|
||||
parser understands: `weeks` `days` `hours` `minutes` `seconds`
|
||||
default_unit : Optional[str]
|
||||
If provided, it will additionally try to match integer-only input into
|
||||
a timedelta, using the unit specified. Same units as in `allowed_units`
|
||||
apply.
|
||||
def get_timedelta_converter(
|
||||
*,
|
||||
default_unit: Optional[str] = None,
|
||||
maximum: Optional[timedelta] = None,
|
||||
minimum: Optional[timedelta] = None,
|
||||
allowed_units: Optional[List[str]] = None,
|
||||
) -> Type[timedelta]:
|
||||
...
|
||||
|
||||
Returns
|
||||
-------
|
||||
type
|
||||
The converter class, which will be a subclass of `TimedeltaConverter`
|
||||
"""
|
||||
|
||||
class PartialMeta(type(TimedeltaConverter)):
|
||||
__call__ = functools.partialmethod(
|
||||
type(DictConverter).__call__,
|
||||
allowed_units=allowed_units,
|
||||
default_unit=default_unit,
|
||||
minimum=minimum,
|
||||
maximum=maximum,
|
||||
)
|
||||
else:
|
||||
|
||||
class ValidatedConverter(TimedeltaConverter, metaclass=PartialMeta):
|
||||
pass
|
||||
def get_timedelta_converter(
|
||||
*,
|
||||
default_unit: Optional[str] = None,
|
||||
maximum: Optional[timedelta] = None,
|
||||
minimum: Optional[timedelta] = None,
|
||||
allowed_units: Optional[List[str]] = None,
|
||||
) -> Type[timedelta]:
|
||||
"""
|
||||
This creates a type suitable for typechecking which works with discord.py's
|
||||
commands.
|
||||
|
||||
return ValidatedConverter
|
||||
See `parse_timedelta` for more information about how this functions.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maximum : Optional[timedelta]
|
||||
If provided, any parsed value higher than this will raise an exception
|
||||
minimum : Optional[timedelta]
|
||||
If provided, any parsed value lower than this will raise an exception
|
||||
allowed_units : Optional[List[str]]
|
||||
If provided, you can constrain a user to expressing the amount of time
|
||||
in specific units. The units you can choose to provide are the same as the
|
||||
parser understands: (``weeks``, ``days``, ``hours``, ``minutes``, ``seconds``)
|
||||
default_unit : Optional[str]
|
||||
If provided, it will additionally try to match integer-only input into
|
||||
a timedelta, using the unit specified. Same units as in ``allowed_units``
|
||||
apply.
|
||||
|
||||
Returns
|
||||
-------
|
||||
type
|
||||
The converter class, which will be a subclass of `TimedeltaConverter`
|
||||
"""
|
||||
|
||||
class PartialMeta(type):
|
||||
__call__ = functools.partialmethod(
|
||||
type(DictConverter).__call__,
|
||||
allowed_units=allowed_units,
|
||||
default_unit=default_unit,
|
||||
minimum=minimum,
|
||||
maximum=maximum,
|
||||
)
|
||||
|
||||
class ValidatedConverter(TimedeltaConverter, metaclass=PartialMeta):
|
||||
pass
|
||||
|
||||
return ValidatedConverter
|
||||
|
||||
|
||||
if not TYPE_CHECKING:
|
||||
|
||||
class NoParseOptional:
|
||||
"""
|
||||
This can be used instead of `typing.Optional`
|
||||
to avoid discord.py special casing the conversion behavior.
|
||||
|
||||
.. warning::
|
||||
This converter class is still provisional.
|
||||
|
||||
.. seealso::
|
||||
The `ignore_optional_for_conversion` option of commands.
|
||||
"""
|
||||
|
||||
def __class_getitem__(cls, key):
|
||||
if isinstance(key, tuple):
|
||||
raise TypeError("Must only provide a single type to Optional")
|
||||
return key
|
||||
|
||||
|
||||
_T_OPT = TypeVar("_T_OPT", bound=Type)
|
||||
|
||||
if TYPE_CHECKING or os.getenv("BUILDING_DOCS", False):
|
||||
|
||||
class UserInputOptional(Generic[_T_OPT]):
|
||||
"""
|
||||
This can be used when user input should be converted as discord.py
|
||||
treats `typing.Optional`, but the type should not be equivalent to
|
||||
``typing.Union[DesiredType, None]`` for type checking.
|
||||
|
||||
|
||||
.. warning::
|
||||
This converter class is still provisional.
|
||||
|
||||
This class may not play well with mypy yet
|
||||
and may still require you guard this in a
|
||||
type checking conditional import vs the desired types
|
||||
|
||||
We're aware and looking into improving this.
|
||||
"""
|
||||
|
||||
def __class_getitem__(cls, key: _T_OPT) -> _T_OPT:
|
||||
if isinstance(key, tuple):
|
||||
raise TypeError("Must only provide a single type to Optional")
|
||||
return key
|
||||
|
||||
|
||||
else:
|
||||
UserInputOptional = Optional
|
||||
|
||||
|
||||
if not TYPE_CHECKING:
|
||||
|
||||
class Literal(dpy_commands.Converter):
|
||||
"""
|
||||
This can be used as a converter for `typing.Literal`.
|
||||
|
||||
In a type checking context it is `typing.Literal`.
|
||||
In a runtime context, it's a converter which only matches the literals it was given.
|
||||
|
||||
|
||||
.. warning::
|
||||
This converter class is still provisional.
|
||||
"""
|
||||
|
||||
def __init__(self, valid_names: Tuple[str]):
|
||||
self.valid_names = valid_names
|
||||
|
||||
def __call__(self, ctx, arg):
|
||||
# Callable's are treated as valid types:
|
||||
# https://github.com/python/cpython/blob/3.8/Lib/typing.py#L148
|
||||
# Without this, ``typing.Union[Literal["clear"], bool]`` would fail
|
||||
return self.convert(ctx, arg)
|
||||
|
||||
async def convert(self, ctx, arg):
|
||||
if arg in self.valid_names:
|
||||
return arg
|
||||
raise BadArgument(_("Expected one of: {}").format(humanize_list(self.valid_names)))
|
||||
|
||||
def __class_getitem__(cls, k):
|
||||
if not k:
|
||||
raise ValueError("Need at least one value for Literal")
|
||||
if isinstance(k, tuple):
|
||||
return cls(k)
|
||||
else:
|
||||
return cls((k,))
|
||||
|
||||
@@ -44,6 +44,7 @@ from . import commands
|
||||
from .context import Context
|
||||
from ..i18n import Translator
|
||||
from ..utils import menus
|
||||
from ..utils.mod import mass_purge
|
||||
from ..utils._internal_utils import fuzzy_command_search, format_fuzzy_results
|
||||
from ..utils.chat_formatting import box, pagify
|
||||
|
||||
@@ -162,10 +163,10 @@ class RedHelpFormatter:
|
||||
|
||||
@staticmethod
|
||||
def get_default_tagline(ctx: Context):
|
||||
return (
|
||||
f"Type {ctx.clean_prefix}help <command> for more info on a command. "
|
||||
f"You can also type {ctx.clean_prefix}help <category> for more info on a category."
|
||||
)
|
||||
return T_(
|
||||
"Type {ctx.clean_prefix}help <command> for more info on a command. "
|
||||
"You can also type {ctx.clean_prefix}help <category> for more info on a category."
|
||||
).format(ctx=ctx)
|
||||
|
||||
async def format_command_help(self, ctx: Context, obj: commands.Command):
|
||||
|
||||
@@ -187,7 +188,9 @@ class RedHelpFormatter:
|
||||
|
||||
description = command.description or ""
|
||||
tagline = (await ctx.bot._config.help.tagline()) or self.get_default_tagline(ctx)
|
||||
signature = f"`Syntax: {ctx.clean_prefix}{command.qualified_name} {command.signature}`"
|
||||
signature = (
|
||||
f"`{T_('Syntax')}: {ctx.clean_prefix}{command.qualified_name} {command.signature}`"
|
||||
)
|
||||
subcommands = None
|
||||
|
||||
if hasattr(command, "all_commands"):
|
||||
@@ -198,18 +201,19 @@ class RedHelpFormatter:
|
||||
emb = {"embed": {"title": "", "description": ""}, "footer": {"text": ""}, "fields": []}
|
||||
|
||||
if description:
|
||||
emb["embed"]["title"] = f"*{description[:2044]}*"
|
||||
emb["embed"]["title"] = f"*{description[:250]}*"
|
||||
|
||||
emb["footer"]["text"] = tagline
|
||||
emb["embed"]["description"] = signature
|
||||
|
||||
if command.help:
|
||||
splitted = command.help.split("\n\n")
|
||||
command_help = command.format_help_for_context(ctx)
|
||||
if command_help:
|
||||
splitted = command_help.split("\n\n")
|
||||
name = splitted[0]
|
||||
value = "\n\n".join(splitted[1:]).replace("[p]", ctx.clean_prefix)
|
||||
value = "\n\n".join(splitted[1:])
|
||||
if not value:
|
||||
value = EMPTY_STRING
|
||||
field = EmbedField(name[:252], value[:1024], False)
|
||||
field = EmbedField(name[:250], value[:1024], False)
|
||||
emb["fields"].append(field)
|
||||
|
||||
if subcommands:
|
||||
@@ -220,14 +224,14 @@ class RedHelpFormatter:
|
||||
return a_line[:67] + "..."
|
||||
|
||||
subtext = "\n".join(
|
||||
shorten_line(f"**{name}** {command.short_doc}")
|
||||
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
|
||||
for name, command in sorted(subcommands.items())
|
||||
)
|
||||
for i, page in enumerate(pagify(subtext, page_length=500, shorten_by=0)):
|
||||
if i == 0:
|
||||
title = "**__Subcommands:__**"
|
||||
title = T_("**__Subcommands:__**")
|
||||
else:
|
||||
title = "**__Subcommands:__** (continued)"
|
||||
title = T_("**__Subcommands:__** (continued)")
|
||||
field = EmbedField(title, page, False)
|
||||
emb["fields"].append(field)
|
||||
|
||||
@@ -238,14 +242,14 @@ class RedHelpFormatter:
|
||||
subtext = None
|
||||
subtext_header = None
|
||||
if subcommands:
|
||||
subtext_header = "Subcommands:"
|
||||
subtext_header = T_("Subcommands:")
|
||||
max_width = max(discord.utils._string_width(name) for name in subcommands.keys())
|
||||
|
||||
def width_maker(cmds):
|
||||
doc_max_width = 80 - max_width
|
||||
for nm, com in sorted(cmds):
|
||||
width_gap = discord.utils._string_width(nm) - len(nm)
|
||||
doc = com.short_doc
|
||||
doc = com.format_shortdoc_for_context(ctx)
|
||||
if len(doc) > doc_max_width:
|
||||
doc = doc[: doc_max_width - 3] + "..."
|
||||
yield nm, doc, max_width - width_gap
|
||||
@@ -261,7 +265,7 @@ class RedHelpFormatter:
|
||||
(
|
||||
description,
|
||||
signature[1:-1],
|
||||
command.help.replace("[p]", ctx.clean_prefix),
|
||||
command.format_help_for_context(ctx),
|
||||
subtext_header,
|
||||
subtext,
|
||||
),
|
||||
@@ -301,7 +305,10 @@ class RedHelpFormatter:
|
||||
page_char_limit = await ctx.bot._config.help.page_char_limit()
|
||||
page_char_limit = min(page_char_limit, 5500) # Just in case someone was manually...
|
||||
|
||||
author_info = {"name": f"{ctx.me.display_name} Help Menu", "icon_url": ctx.me.avatar_url}
|
||||
author_info = {
|
||||
"name": f"{ctx.me.display_name} {T_('Help Menu')}",
|
||||
"icon_url": ctx.me.avatar_url,
|
||||
}
|
||||
|
||||
# Offset calculation here is for total embed size limit
|
||||
# 20 accounts for# *Page {i} of {page_count}*
|
||||
@@ -346,7 +353,9 @@ class RedHelpFormatter:
|
||||
embed = discord.Embed(color=color, **embed_dict["embed"])
|
||||
|
||||
if page_count > 1:
|
||||
description = f"*Page {i} of {page_count}*\n{embed.description}"
|
||||
description = T_(
|
||||
"*Page {page_num} of {page_count}*\n{content_description}"
|
||||
).format(content_description=embed.description, page_num=i, page_count=page_count)
|
||||
embed.description = description
|
||||
|
||||
embed.set_author(**author_info)
|
||||
@@ -366,7 +375,7 @@ class RedHelpFormatter:
|
||||
if not (coms or await ctx.bot._config.help.verify_exists()):
|
||||
return
|
||||
|
||||
description = obj.help
|
||||
description = obj.format_help_for_context(ctx)
|
||||
tagline = (await ctx.bot._config.help.tagline()) or self.get_default_tagline(ctx)
|
||||
|
||||
if await ctx.embed_requested():
|
||||
@@ -376,7 +385,7 @@ class RedHelpFormatter:
|
||||
if description:
|
||||
splitted = description.split("\n\n")
|
||||
name = splitted[0]
|
||||
value = "\n\n".join(splitted[1:]).replace("[p]", ctx.clean_prefix)
|
||||
value = "\n\n".join(splitted[1:])
|
||||
if not value:
|
||||
value = EMPTY_STRING
|
||||
field = EmbedField(name[:252], value[:1024], False)
|
||||
@@ -390,14 +399,14 @@ class RedHelpFormatter:
|
||||
return a_line[:67] + "..."
|
||||
|
||||
command_text = "\n".join(
|
||||
shorten_line(f"**{name}** {command.short_doc}")
|
||||
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
|
||||
for name, command in sorted(coms.items())
|
||||
)
|
||||
for i, page in enumerate(pagify(command_text, page_length=500, shorten_by=0)):
|
||||
if i == 0:
|
||||
title = "**__Commands:__**"
|
||||
title = T_("**__Commands:__**")
|
||||
else:
|
||||
title = "**__Commands:__** (continued)"
|
||||
title = T_("**__Commands:__** (continued)")
|
||||
field = EmbedField(title, page, False)
|
||||
emb["fields"].append(field)
|
||||
|
||||
@@ -407,14 +416,14 @@ class RedHelpFormatter:
|
||||
subtext = None
|
||||
subtext_header = None
|
||||
if coms:
|
||||
subtext_header = "Commands:"
|
||||
subtext_header = T_("Commands:")
|
||||
max_width = max(discord.utils._string_width(name) for name in coms.keys())
|
||||
|
||||
def width_maker(cmds):
|
||||
doc_max_width = 80 - max_width
|
||||
for nm, com in sorted(cmds):
|
||||
width_gap = discord.utils._string_width(nm) - len(nm)
|
||||
doc = com.short_doc
|
||||
doc = com.format_shortdoc_for_context(ctx)
|
||||
if len(doc) > doc_max_width:
|
||||
doc = doc[: doc_max_width - 3] + "..."
|
||||
yield nm, doc, max_width - width_gap
|
||||
@@ -442,14 +451,14 @@ class RedHelpFormatter:
|
||||
|
||||
emb["footer"]["text"] = tagline
|
||||
if description:
|
||||
emb["embed"]["title"] = f"*{description[:2044]}*"
|
||||
emb["embed"]["title"] = f"*{description[:250]}*"
|
||||
|
||||
for cog_name, data in coms:
|
||||
|
||||
if cog_name:
|
||||
title = f"**__{cog_name}:__**"
|
||||
else:
|
||||
title = f"**__No Category:__**"
|
||||
title = f"**__{T_('No Category')}:__**"
|
||||
|
||||
def shorten_line(a_line: str) -> str:
|
||||
if len(a_line) < 70: # embed max width needs to be lower
|
||||
@@ -457,12 +466,12 @@ class RedHelpFormatter:
|
||||
return a_line[:67] + "..."
|
||||
|
||||
cog_text = "\n".join(
|
||||
shorten_line(f"**{name}** {command.short_doc}")
|
||||
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
|
||||
for name, command in sorted(data.items())
|
||||
)
|
||||
|
||||
for i, page in enumerate(pagify(cog_text, page_length=1000, shorten_by=0)):
|
||||
title = title if i < 1 else f"{title} (continued)"
|
||||
title = title if i < 1 else f"{title} {T_('(continued)')}"
|
||||
field = EmbedField(title, page, False)
|
||||
emb["fields"].append(field)
|
||||
|
||||
@@ -478,21 +487,21 @@ class RedHelpFormatter:
|
||||
names.extend(list(v.name for v in v.values()))
|
||||
|
||||
max_width = max(
|
||||
discord.utils._string_width((name or "No Category:")) for name in names
|
||||
discord.utils._string_width((name or T_("No Category:"))) for name in names
|
||||
)
|
||||
|
||||
def width_maker(cmds):
|
||||
doc_max_width = 80 - max_width
|
||||
for nm, com in cmds:
|
||||
width_gap = discord.utils._string_width(nm) - len(nm)
|
||||
doc = com.short_doc
|
||||
doc = com.format_shortdoc_for_context(ctx)
|
||||
if len(doc) > doc_max_width:
|
||||
doc = doc[: doc_max_width - 3] + "..."
|
||||
yield nm, doc, max_width - width_gap
|
||||
|
||||
for cog_name, data in coms:
|
||||
|
||||
title = f"{cog_name}:" if cog_name else "No Category:"
|
||||
title = f"{cog_name}:" if cog_name else T_("No Category:")
|
||||
to_join.append(title)
|
||||
|
||||
for name, doc, width in width_maker(sorted(data.items())):
|
||||
@@ -543,7 +552,9 @@ class RedHelpFormatter:
|
||||
if fuzzy_commands:
|
||||
ret = await format_fuzzy_results(ctx, fuzzy_commands, embed=use_embeds)
|
||||
if use_embeds:
|
||||
ret.set_author(name=f"{ctx.me.display_name} Help Menu", icon_url=ctx.me.avatar_url)
|
||||
ret.set_author(
|
||||
name=f"{ctx.me.display_name} {T_('Help Menu')}", icon_url=ctx.me.avatar_url
|
||||
)
|
||||
tagline = (await ctx.bot._config.help.tagline()) or self.get_default_tagline(ctx)
|
||||
ret.set_footer(text=tagline)
|
||||
await ctx.send(embed=ret)
|
||||
@@ -553,7 +564,9 @@ class RedHelpFormatter:
|
||||
ret = T_("Help topic for *{command_name}* not found.").format(command_name=help_for)
|
||||
if use_embeds:
|
||||
ret = discord.Embed(color=(await ctx.embed_color()), description=ret)
|
||||
ret.set_author(name=f"{ctx.me.display_name} Help Menu", icon_url=ctx.me.avatar_url)
|
||||
ret.set_author(
|
||||
name=f"{ctx.me.display_name} {T_('Help Menu')}", icon_url=ctx.me.avatar_url
|
||||
)
|
||||
tagline = (await ctx.bot._config.help.tagline()) or self.get_default_tagline(ctx)
|
||||
ret.set_footer(text=tagline)
|
||||
await ctx.send(embed=ret)
|
||||
@@ -569,7 +582,9 @@ class RedHelpFormatter:
|
||||
)
|
||||
if await ctx.embed_requested():
|
||||
ret = discord.Embed(color=(await ctx.embed_color()), description=ret)
|
||||
ret.set_author(name=f"{ctx.me.display_name} Help Menu", icon_url=ctx.me.avatar_url)
|
||||
ret.set_author(
|
||||
name=f"{ctx.me.display_name} {T_('Help Menu')}", icon_url=ctx.me.avatar_url
|
||||
)
|
||||
tagline = (await ctx.bot._config.help.tagline()) or self.get_default_tagline(ctx)
|
||||
ret.set_footer(text=tagline)
|
||||
await ctx.send(embed=ret)
|
||||
@@ -613,36 +628,52 @@ class RedHelpFormatter:
|
||||
Sends pages based on settings.
|
||||
"""
|
||||
|
||||
if not (
|
||||
ctx.channel.permissions_for(ctx.me).add_reactions
|
||||
and await ctx.bot._config.help.use_menus()
|
||||
):
|
||||
# save on config calls
|
||||
config_help = await ctx.bot._config.help()
|
||||
channel_permissions = ctx.channel.permissions_for(ctx.me)
|
||||
|
||||
max_pages_in_guild = await ctx.bot._config.help.max_pages_in_guild()
|
||||
destination = ctx.author if len(pages) > max_pages_in_guild else ctx
|
||||
if not (channel_permissions.add_reactions and config_help["use_menus"]):
|
||||
|
||||
if embed:
|
||||
for page in pages:
|
||||
try:
|
||||
await destination.send(embed=page)
|
||||
except discord.Forbidden:
|
||||
return await ctx.send(
|
||||
T_(
|
||||
"I couldn't send the help message to you in DM. "
|
||||
"Either you blocked me or you disabled DMs in this server."
|
||||
)
|
||||
)
|
||||
else:
|
||||
for page in pages:
|
||||
try:
|
||||
await destination.send(page)
|
||||
except discord.Forbidden:
|
||||
return await ctx.send(
|
||||
T_(
|
||||
"I couldn't send the help message to you in DM. "
|
||||
"Either you blocked me or you disabled DMs in this server."
|
||||
)
|
||||
max_pages_in_guild = config_help["max_pages_in_guild"]
|
||||
use_DMs = len(pages) > max_pages_in_guild
|
||||
destination = ctx.author if use_DMs else ctx.channel
|
||||
delete_delay = config_help["delete_delay"]
|
||||
|
||||
messages: List[discord.Message] = []
|
||||
for page in pages:
|
||||
try:
|
||||
if embed:
|
||||
msg = await destination.send(embed=page)
|
||||
else:
|
||||
msg = await destination.send(page)
|
||||
except discord.Forbidden:
|
||||
return await ctx.send(
|
||||
T_(
|
||||
"I couldn't send the help message to you in DM. "
|
||||
"Either you blocked me or you disabled DMs in this server."
|
||||
)
|
||||
)
|
||||
else:
|
||||
messages.append(msg)
|
||||
|
||||
# The if statement takes into account that 'destination' will be
|
||||
# the context channel in non-DM context, reusing 'channel_permissions' to avoid
|
||||
# computing the permissions twice.
|
||||
if (
|
||||
not use_DMs # we're not in DMs
|
||||
and delete_delay > 0 # delete delay is enabled
|
||||
and channel_permissions.manage_messages # we can manage messages here
|
||||
):
|
||||
|
||||
# We need to wrap this in a task to not block after-sending-help interactions.
|
||||
# The channel has to be TextChannel as we can't bulk-delete from DMs
|
||||
async def _delete_delay_help(
|
||||
channel: discord.TextChannel, messages: List[discord.Message], delay: int
|
||||
):
|
||||
await asyncio.sleep(delay)
|
||||
await mass_purge(messages, channel)
|
||||
|
||||
asyncio.create_task(_delete_delay_help(destination, messages, delete_delay))
|
||||
else:
|
||||
# Specifically ensuring the menu's message is sent prior to returning
|
||||
m = await (ctx.send(embed=pages[0]) if embed else ctx.send(pages[0]))
|
||||
|
||||
@@ -8,6 +8,8 @@ checks like bot permissions checks.
|
||||
"""
|
||||
import asyncio
|
||||
import enum
|
||||
import inspect
|
||||
from collections import ChainMap
|
||||
from typing import (
|
||||
Union,
|
||||
Optional,
|
||||
@@ -20,6 +22,7 @@ from typing import (
|
||||
TypeVar,
|
||||
Tuple,
|
||||
ClassVar,
|
||||
Mapping,
|
||||
)
|
||||
|
||||
import discord
|
||||
@@ -45,6 +48,7 @@ __all__ = [
|
||||
"permissions_check",
|
||||
"bot_has_permissions",
|
||||
"has_permissions",
|
||||
"has_guild_permissions",
|
||||
"is_owner",
|
||||
"guildowner",
|
||||
"guildowner_or_permissions",
|
||||
@@ -52,6 +56,9 @@ __all__ = [
|
||||
"admin_or_permissions",
|
||||
"mod",
|
||||
"mod_or_permissions",
|
||||
"transition_permstate_to",
|
||||
"PermStateTransitions",
|
||||
"PermStateAllowedStates",
|
||||
]
|
||||
|
||||
_T = TypeVar("_T")
|
||||
@@ -95,8 +102,8 @@ class PrivilegeLevel(enum.IntEnum):
|
||||
"""Enumeration for special privileges."""
|
||||
|
||||
# Maintainer Note: do NOT re-order these.
|
||||
# Each privelege level also implies access to the ones before it.
|
||||
# Inserting new privelege levels at a later point is fine if that is considered.
|
||||
# Each privilege level also implies access to the ones before it.
|
||||
# Inserting new privilege levels at a later point is fine if that is considered.
|
||||
|
||||
NONE = enum.auto()
|
||||
"""No special privilege level."""
|
||||
@@ -182,11 +189,6 @@ class PermState(enum.Enum):
|
||||
"""This command has been actively denied by a permission hook
|
||||
check validation doesn't need this, but is useful to developers"""
|
||||
|
||||
def transition_to(
|
||||
self, next_state: "PermState"
|
||||
) -> Tuple[Optional[bool], Union["PermState", Dict[bool, "PermState"]]]:
|
||||
return self.TRANSITIONS[self][next_state]
|
||||
|
||||
@classmethod
|
||||
def from_bool(cls, value: Optional[bool]) -> "PermState":
|
||||
"""Get a PermState from a bool or ``NoneType``."""
|
||||
@@ -211,7 +213,11 @@ class PermState(enum.Enum):
|
||||
# result of the default permission checks - the transition from NORMAL
|
||||
# to PASSIVE_ALLOW. In this case "next state" is a dict mapping the
|
||||
# permission check results to the actual next state.
|
||||
PermState.TRANSITIONS = {
|
||||
|
||||
TransitionResult = Tuple[Optional[bool], Union[PermState, Dict[bool, PermState]]]
|
||||
TransitionDict = Dict[PermState, Dict[PermState, TransitionResult]]
|
||||
|
||||
PermStateTransitions: TransitionDict = {
|
||||
PermState.ACTIVE_ALLOW: {
|
||||
PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW),
|
||||
PermState.NORMAL: (True, PermState.ACTIVE_ALLOW),
|
||||
@@ -248,13 +254,18 @@ PermState.TRANSITIONS = {
|
||||
PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY),
|
||||
},
|
||||
}
|
||||
PermState.ALLOWED_STATES = (
|
||||
|
||||
PermStateAllowedStates = (
|
||||
PermState.ACTIVE_ALLOW,
|
||||
PermState.PASSIVE_ALLOW,
|
||||
PermState.CAUTIOUS_ALLOW,
|
||||
)
|
||||
|
||||
|
||||
def transition_permstate_to(prev: PermState, next_state: PermState) -> TransitionResult:
|
||||
return PermStateTransitions[prev][next_state]
|
||||
|
||||
|
||||
class Requires:
|
||||
"""This class describes the requirements for executing a specific command.
|
||||
|
||||
@@ -326,13 +337,13 @@ class Requires:
|
||||
|
||||
@staticmethod
|
||||
def get_decorator(
|
||||
privilege_level: Optional[PrivilegeLevel], user_perms: Dict[str, bool]
|
||||
privilege_level: Optional[PrivilegeLevel], user_perms: Optional[Dict[str, bool]]
|
||||
) -> Callable[["_CommandOrCoro"], "_CommandOrCoro"]:
|
||||
if not user_perms:
|
||||
user_perms = None
|
||||
|
||||
def decorator(func: "_CommandOrCoro") -> "_CommandOrCoro":
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
if inspect.iscoroutinefunction(func):
|
||||
func.__requires_privilege_level__ = privilege_level
|
||||
func.__requires_user_perms__ = user_perms
|
||||
else:
|
||||
@@ -341,6 +352,7 @@ class Requires:
|
||||
func.requires.user_perms = None
|
||||
else:
|
||||
_validate_perms_dict(user_perms)
|
||||
assert func.requires.user_perms is not None
|
||||
func.requires.user_perms.update(**user_perms)
|
||||
return func
|
||||
|
||||
@@ -357,6 +369,8 @@ class Requires:
|
||||
guild_id : int
|
||||
The ID of the guild for the rule's scope. Set to
|
||||
`Requires.GLOBAL` for a global rule.
|
||||
If a global rule is set for a model,
|
||||
it will be prefered over the guild rule.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -367,8 +381,9 @@ class Requires:
|
||||
"""
|
||||
if not isinstance(model, (str, int)):
|
||||
model = model.id
|
||||
rules: Mapping[Union[int, str], PermState]
|
||||
if guild_id:
|
||||
rules = self._guild_rules.get(guild_id, _RulesDict())
|
||||
rules = ChainMap(self._global_rules, self._guild_rules.get(guild_id, _RulesDict()))
|
||||
else:
|
||||
rules = self._global_rules
|
||||
return rules.get(model, PermState.NORMAL)
|
||||
@@ -488,7 +503,7 @@ class Requires:
|
||||
async def _transition_state(self, ctx: "Context") -> bool:
|
||||
prev_state = ctx.permission_state
|
||||
cur_state = self._get_rule_from_ctx(ctx)
|
||||
should_invoke, next_state = prev_state.transition_to(cur_state)
|
||||
should_invoke, next_state = transition_permstate_to(prev_state, cur_state)
|
||||
if should_invoke is None:
|
||||
# NORMAL invokation, we simply follow standard procedure
|
||||
should_invoke = await self._verify_user(ctx)
|
||||
@@ -509,6 +524,7 @@ class Requires:
|
||||
would_invoke = await self._verify_user(ctx)
|
||||
next_state = next_state[would_invoke]
|
||||
|
||||
assert isinstance(next_state, PermState)
|
||||
ctx.permission_state = next_state
|
||||
return should_invoke
|
||||
|
||||
@@ -635,6 +651,20 @@ def permissions_check(predicate: CheckPredicate):
|
||||
return decorator
|
||||
|
||||
|
||||
def has_guild_permissions(**perms):
|
||||
"""Restrict the command to users with these guild permissions.
|
||||
|
||||
This check can be overridden by rules.
|
||||
"""
|
||||
|
||||
_validate_perms_dict(perms)
|
||||
|
||||
def predicate(ctx):
|
||||
return ctx.guild and ctx.author.guild_permissions >= discord.Permissions(**perms)
|
||||
|
||||
return permissions_check(predicate)
|
||||
|
||||
|
||||
def bot_has_permissions(**perms: bool):
|
||||
"""Complain if the bot is missing permissions.
|
||||
|
||||
@@ -757,16 +787,10 @@ class _RulesDict(Dict[Union[int, str], PermState]):
|
||||
|
||||
|
||||
def _validate_perms_dict(perms: Dict[str, bool]) -> None:
|
||||
invalid_keys = set(perms.keys()) - set(discord.Permissions.VALID_FLAGS)
|
||||
if invalid_keys:
|
||||
raise TypeError(f"Invalid perm name(s): {', '.join(invalid_keys)}")
|
||||
for perm, value in perms.items():
|
||||
try:
|
||||
attr = getattr(discord.Permissions, perm)
|
||||
except AttributeError:
|
||||
attr = None
|
||||
|
||||
if attr is None or not isinstance(attr, property):
|
||||
# We reject invalid permissions
|
||||
raise TypeError(f"Unknown permission name '{perm}'")
|
||||
|
||||
if value is not True:
|
||||
# We reject any permission not specified as 'True', since this is the only value which
|
||||
# makes practical sense.
|
||||
|
||||
@@ -979,7 +979,7 @@ class Config:
|
||||
"""
|
||||
return self._get_base_group(self.CHANNEL, str(channel_id))
|
||||
|
||||
def channel(self, channel: discord.TextChannel) -> Group:
|
||||
def channel(self, channel: discord.abc.GuildChannel) -> Group:
|
||||
"""Returns a `Group` for the given channel.
|
||||
|
||||
This does not discriminate between text and voice channels.
|
||||
|
||||
@@ -126,7 +126,7 @@ class CoreLogic:
|
||||
else:
|
||||
await bot.add_loaded_package(name)
|
||||
loaded_packages.append(name)
|
||||
# remove in Red 3.3
|
||||
# remove in Red 3.4
|
||||
downloader = bot.get_cog("Downloader")
|
||||
if downloader is None:
|
||||
continue
|
||||
@@ -257,10 +257,9 @@ class CoreLogic:
|
||||
The current (or new) list of prefixes.
|
||||
"""
|
||||
if prefixes:
|
||||
prefixes = sorted(prefixes, reverse=True)
|
||||
await self.bot._config.prefix.set(prefixes)
|
||||
await self.bot._prefix_cache.set_prefixes(guild=None, prefixes=prefixes)
|
||||
return prefixes
|
||||
return await self.bot._config.prefix()
|
||||
return await self.bot._prefix_cache.get_prefixes(guild=None)
|
||||
|
||||
@classmethod
|
||||
async def _version_info(cls) -> Dict[str, str]:
|
||||
@@ -320,7 +319,10 @@ class Core(commands.Cog, CoreLogic):
|
||||
python_version = "[{}.{}.{}]({})".format(*sys.version_info[:3], python_url)
|
||||
red_version = "[{}]({})".format(__version__, red_pypi)
|
||||
app_info = await self.bot.application_info()
|
||||
owner = app_info.owner
|
||||
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:
|
||||
@@ -359,7 +361,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
|
||||
@commands.command()
|
||||
async def uptime(self, ctx: commands.Context):
|
||||
"""Shows Red's uptime"""
|
||||
"""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")
|
||||
@@ -386,6 +388,9 @@ class Core(commands.Cog, CoreLogic):
|
||||
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))
|
||||
@@ -431,6 +436,31 @@ class Core(commands.Cog, CoreLogic):
|
||||
)
|
||||
)
|
||||
|
||||
@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):
|
||||
"""
|
||||
@@ -472,7 +502,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@commands.command()
|
||||
@commands.check(CoreLogic._can_get_invite_url)
|
||||
async def invite(self, ctx):
|
||||
"""Show's Red's invite url"""
|
||||
"""Show's [botname]'s invite url"""
|
||||
try:
|
||||
await ctx.author.send(await self._invite_url())
|
||||
except discord.errors.Forbidden:
|
||||
@@ -563,7 +593,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
msg = ""
|
||||
responses = []
|
||||
for i, server in enumerate(guilds, 1):
|
||||
msg += "{}: {}\n".format(i, server.name)
|
||||
msg += "{}: {} (`{}`)\n".format(i, server.name, server.id)
|
||||
responses.append(str(i))
|
||||
|
||||
for page in pagify(msg, ["\n"]):
|
||||
@@ -675,13 +705,13 @@ class Core(commands.Cog, CoreLogic):
|
||||
if len(repos_with_shared_libs) == 1:
|
||||
formed = _(
|
||||
"**WARNING**: The following repo is using shared libs"
|
||||
" which are marked for removal in Red 3.3: {repo}.\n"
|
||||
" 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.3: {repos}.\n"
|
||||
" 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)
|
||||
@@ -793,13 +823,13 @@ class Core(commands.Cog, CoreLogic):
|
||||
if len(repos_with_shared_libs) == 1:
|
||||
formed = _(
|
||||
"**WARNING**: The following repo is using shared libs"
|
||||
" which are marked for removal in Red 3.3: {repo}.\n"
|
||||
" 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.3: {repos}.\n"
|
||||
" 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)
|
||||
@@ -835,7 +865,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
|
||||
@commands.group(name="set")
|
||||
async def _set(self, ctx: commands.Context):
|
||||
"""Changes Red's settings"""
|
||||
"""Changes [botname]'s settings"""
|
||||
if ctx.invoked_subcommand is None:
|
||||
if ctx.guild:
|
||||
guild = ctx.guild
|
||||
@@ -847,15 +877,13 @@ class Core(commands.Cog, CoreLogic):
|
||||
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."
|
||||
prefixes = await ctx.bot._config.guild(ctx.guild).prefix()
|
||||
guild_settings = _("Admin roles: {admin}\nMod roles: {mod}\n").format(
|
||||
admin=admin_roles_str, mod=mod_roles_str
|
||||
)
|
||||
else:
|
||||
guild_settings = ""
|
||||
prefixes = None # This is correct. The below can happen in a guild.
|
||||
if not prefixes:
|
||||
prefixes = await ctx.bot._config.prefix()
|
||||
|
||||
prefixes = await ctx.bot._prefix_cache.get_prefixes(ctx.guild)
|
||||
locale = await ctx.bot._config.locale()
|
||||
|
||||
prefix_string = " ".join(prefixes)
|
||||
@@ -873,6 +901,32 @@ class Core(commands.Cog, CoreLogic):
|
||||
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()
|
||||
@@ -997,7 +1051,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@_set.command()
|
||||
@checks.is_owner()
|
||||
async def avatar(self, ctx: commands.Context, url: str):
|
||||
"""Sets Red's avatar"""
|
||||
"""Sets [botname]'s avatar"""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as r:
|
||||
data = await r.read()
|
||||
@@ -1021,7 +1075,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.bot_in_a_guild()
|
||||
@checks.is_owner()
|
||||
async def _game(self, ctx: commands.Context, *, game: str = None):
|
||||
"""Sets Red's playing status"""
|
||||
"""Sets [botname]'s playing status"""
|
||||
|
||||
if game:
|
||||
game = discord.Game(name=game)
|
||||
@@ -1035,7 +1089,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.bot_in_a_guild()
|
||||
@checks.is_owner()
|
||||
async def _listening(self, ctx: commands.Context, *, listening: str = None):
|
||||
"""Sets Red's listening status"""
|
||||
"""Sets [botname]'s listening status"""
|
||||
|
||||
status = ctx.bot.guilds[0].me.status if len(ctx.bot.guilds) > 0 else discord.Status.online
|
||||
if listening:
|
||||
@@ -1049,7 +1103,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.bot_in_a_guild()
|
||||
@checks.is_owner()
|
||||
async def _watching(self, ctx: commands.Context, *, watching: str = None):
|
||||
"""Sets Red's watching status"""
|
||||
"""Sets [botname]'s watching status"""
|
||||
|
||||
status = ctx.bot.guilds[0].me.status if len(ctx.bot.guilds) > 0 else discord.Status.online
|
||||
if watching:
|
||||
@@ -1063,7 +1117,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.bot_in_a_guild()
|
||||
@checks.is_owner()
|
||||
async def status(self, ctx: commands.Context, *, status: str):
|
||||
"""Sets Red's status
|
||||
"""Sets [botname]'s status
|
||||
|
||||
Available statuses:
|
||||
online
|
||||
@@ -1092,7 +1146,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.bot_in_a_guild()
|
||||
@checks.is_owner()
|
||||
async def stream(self, ctx: commands.Context, streamer=None, *, stream_title=None):
|
||||
"""Sets Red's streaming status
|
||||
"""Sets [botname]'s streaming status
|
||||
Leaving both streamer and stream_title empty will clear it."""
|
||||
|
||||
status = ctx.bot.guilds[0].me.status if len(ctx.bot.guilds) > 0 else None
|
||||
@@ -1113,7 +1167,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@_set.command(name="username", aliases=["name"])
|
||||
@checks.is_owner()
|
||||
async def _username(self, ctx: commands.Context, *, username: str):
|
||||
"""Sets Red's username"""
|
||||
"""Sets [botname]'s username"""
|
||||
try:
|
||||
await self._name(name=username)
|
||||
except discord.HTTPException:
|
||||
@@ -1132,7 +1186,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.admin()
|
||||
@commands.guild_only()
|
||||
async def _nickname(self, ctx: commands.Context, *, nickname: str = None):
|
||||
"""Sets Red's nickname"""
|
||||
"""Sets [botname]'s nickname"""
|
||||
try:
|
||||
await ctx.guild.me.edit(nick=nickname)
|
||||
except discord.Forbidden:
|
||||
@@ -1143,7 +1197,7 @@ class Core(commands.Cog, CoreLogic):
|
||||
@_set.command(aliases=["prefixes"])
|
||||
@checks.is_owner()
|
||||
async def prefix(self, ctx: commands.Context, *prefixes: str):
|
||||
"""Sets Red's global prefix(es)"""
|
||||
"""Sets [botname]'s global prefix(es)"""
|
||||
if not prefixes:
|
||||
await ctx.send_help()
|
||||
return
|
||||
@@ -1154,13 +1208,13 @@ class Core(commands.Cog, CoreLogic):
|
||||
@checks.admin()
|
||||
@commands.guild_only()
|
||||
async def serverprefix(self, ctx: commands.Context, *prefixes: str):
|
||||
"""Sets Red's server prefix(es)"""
|
||||
"""Sets [botname]'s server prefix(es)"""
|
||||
if not prefixes:
|
||||
await ctx.bot._config.guild(ctx.guild).prefix.set([])
|
||||
await ctx.bot._prefix_cache.set_prefixes(guild=ctx.guild, prefixes=[])
|
||||
await ctx.send(_("Guild prefixes have been reset."))
|
||||
return
|
||||
prefixes = sorted(prefixes, reverse=True)
|
||||
await ctx.bot._config.guild(ctx.guild).prefix.set(prefixes)
|
||||
await ctx.bot._prefix_cache.set_prefixes(guild=ctx.guild, prefixes=prefixes)
|
||||
await ctx.send(_("Prefix set."))
|
||||
|
||||
@_set.command()
|
||||
@@ -1345,6 +1399,30 @@ class Core(commands.Cog, CoreLogic):
|
||||
await ctx.bot._config.help.max_pages_in_guild.set(pages)
|
||||
await ctx.send(_("Done. The page limit has been set to {}.").format(pages))
|
||||
|
||||
@helpset.command(name="deletedelay")
|
||||
@commands.bot_has_permissions(manage_messages=True)
|
||||
async def helpset_deletedelay(self, ctx: commands.Context, seconds: int):
|
||||
"""Set the delay after which help pages will be deleted.
|
||||
|
||||
The setting is disabled by default, and only applies to non-menu help,
|
||||
sent in server text channels.
|
||||
Setting the delay to 0 disables this feature.
|
||||
|
||||
The bot has to have MANAGE_MESSAGES permission for this to work.
|
||||
"""
|
||||
if seconds < 0:
|
||||
await ctx.send(_("You must give a value of zero or greater!"))
|
||||
return
|
||||
if seconds > 60 * 60 * 24 * 14: # 14 days
|
||||
await ctx.send(_("The delay cannot be longer than 14 days!"))
|
||||
return
|
||||
|
||||
await ctx.bot._config.help.delete_delay.set(seconds)
|
||||
if seconds == 0:
|
||||
await ctx.send(_("Done. Help messages will not be deleted now."))
|
||||
else:
|
||||
await ctx.send(_("Done. The delete delay has been set to {} seconds.").format(seconds))
|
||||
|
||||
@helpset.command(name="tagline")
|
||||
async def helpset_tagline(self, ctx: commands.Context, *, tagline: str = None):
|
||||
"""
|
||||
@@ -1434,7 +1512,9 @@ class Core(commands.Cog, CoreLogic):
|
||||
if not destination.permissions_for(destination.guild.me).send_messages:
|
||||
continue
|
||||
if destination.permissions_for(destination.guild.me).embed_links:
|
||||
send_embed = await ctx.bot._config.guild(destination.guild).embeds()
|
||||
send_embed = await ctx.bot._config.channel(destination).embeds()
|
||||
if send_embed is None:
|
||||
send_embed = await ctx.bot._config.guild(destination.guild).embeds()
|
||||
else:
|
||||
send_embed = False
|
||||
|
||||
@@ -1501,12 +1581,12 @@ class Core(commands.Cog, CoreLogic):
|
||||
settings, 'appearance' tab. Then right click a user
|
||||
and copy their id"""
|
||||
destination = discord.utils.get(ctx.bot.get_all_members(), id=user_id)
|
||||
if destination is None:
|
||||
if destination is None or destination.bot:
|
||||
await ctx.send(
|
||||
_(
|
||||
"Invalid ID or user not found. You can only "
|
||||
"send messages to people I share a server "
|
||||
"with."
|
||||
"Invalid ID, user not found, or user is a bot. "
|
||||
"You can only send messages to people I share "
|
||||
"a server with."
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
@@ -271,7 +271,7 @@ class BaseDriver(abc.ABC):
|
||||
|
||||
The driver must be initialized before this operation.
|
||||
|
||||
The BaseDriver provides a generic method which may be overriden
|
||||
The BaseDriver provides a generic method which may be overridden
|
||||
by subclasses.
|
||||
|
||||
Parameters
|
||||
|
||||
@@ -217,7 +217,7 @@ class JsonDriver(BaseDriver):
|
||||
|
||||
def _save_json(path: Path, data: Dict[str, Any]) -> None:
|
||||
"""
|
||||
This fsync stuff here is entirely neccessary.
|
||||
This fsync stuff here is entirely necessary.
|
||||
|
||||
On windows, it is not available in entirety.
|
||||
If a windows user ends up with tons of temp files, they should consider hosting on
|
||||
|
||||
@@ -49,8 +49,13 @@ def init_events(bot, cli_flags):
|
||||
users = len(set([m for m in bot.get_all_members()]))
|
||||
|
||||
app_info = await bot.application_info()
|
||||
if bot.owner_id is None:
|
||||
bot.owner_id = app_info.owner.id
|
||||
|
||||
if app_info.team:
|
||||
if bot._use_team_features:
|
||||
bot.owner_ids = {m.id for m in app_info.team.members}
|
||||
else:
|
||||
if bot.owner_id is None:
|
||||
bot.owner_id = app_info.owner.id
|
||||
|
||||
try:
|
||||
invite_url = discord.utils.oauth_url(app_info.id)
|
||||
@@ -213,6 +218,12 @@ def init_events(bot, cli_flags):
|
||||
),
|
||||
delete_after=error.retry_after,
|
||||
)
|
||||
elif isinstance(error, commands.MaxConcurrencyReached):
|
||||
await ctx.send(
|
||||
"Too many people using this command. It can only be used {} time(s) per {} concurrently.".format(
|
||||
error.number, error.per.name
|
||||
)
|
||||
)
|
||||
else:
|
||||
log.exception(type(error).__name__, exc_info=error)
|
||||
|
||||
|
||||
@@ -4,18 +4,20 @@ from . import commands
|
||||
|
||||
def init_global_checks(bot):
|
||||
@bot.check_once
|
||||
def actually_up(ctx):
|
||||
"""
|
||||
Uptime is set during the initial startup process.
|
||||
If this hasn't been set, we should assume the bot isn't ready yet.
|
||||
def minimum_bot_perms(ctx) -> bool:
|
||||
"""
|
||||
return ctx.bot.uptime is not None
|
||||
Too many 403, 401, and 429 Errors can cause bots to get global'd
|
||||
|
||||
It's reasonable to assume the below as a minimum amount of perms for
|
||||
commands.
|
||||
"""
|
||||
return ctx.channel.permissions_for(ctx.me).send_messages
|
||||
|
||||
@bot.check_once
|
||||
async def whiteblacklist_checks(ctx):
|
||||
async def whiteblacklist_checks(ctx) -> bool:
|
||||
return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author)
|
||||
|
||||
@bot.check_once
|
||||
def bots(ctx):
|
||||
def bots(ctx) -> bool:
|
||||
"""Check the user is not another bot."""
|
||||
return not ctx.author.bot
|
||||
|
||||
@@ -142,6 +142,18 @@ async def _init(bot: Red):
|
||||
bot.add_listener(on_member_unban)
|
||||
|
||||
|
||||
async def handle_auditype_key():
|
||||
all_casetypes = {
|
||||
casetype_name: {
|
||||
inner_key: inner_value
|
||||
for inner_key, inner_value in casetype_data.items()
|
||||
if inner_key != "audit_type"
|
||||
}
|
||||
for casetype_name, casetype_data in (await _conf.custom(_CASETYPES).all()).items()
|
||||
}
|
||||
await _conf.custom(_CASETYPES).set(all_casetypes)
|
||||
|
||||
|
||||
async def _migrate_config(from_version: int, to_version: int):
|
||||
if from_version == to_version:
|
||||
return
|
||||
@@ -170,16 +182,7 @@ async def _migrate_config(from_version: int, to_version: int):
|
||||
await _conf.guild(cast(discord.Guild, discord.Object(id=guild_id))).clear_raw("cases")
|
||||
|
||||
if from_version < 3 <= to_version:
|
||||
all_casetypes = {
|
||||
casetype_name: {
|
||||
inner_key: inner_value
|
||||
for inner_key, inner_value in casetype_data.items()
|
||||
if inner_key != "audit_type"
|
||||
}
|
||||
for casetype_name, casetype_data in (await _conf.custom(_CASETYPES).all()).items()
|
||||
}
|
||||
|
||||
await _conf.custom(_CASETYPES).set(all_casetypes)
|
||||
await handle_auditype_key()
|
||||
await _conf.schema_version.set(3)
|
||||
|
||||
if from_version < 4 <= to_version:
|
||||
@@ -321,9 +324,7 @@ class Case:
|
||||
|
||||
if embed:
|
||||
emb = discord.Embed(title=title, description=reason)
|
||||
|
||||
if avatar_url is not None:
|
||||
emb.set_author(name=user, icon_url=avatar_url)
|
||||
emb.set_author(name=user)
|
||||
emb.add_field(name=_("Moderator"), value=moderator, inline=False)
|
||||
if until and duration:
|
||||
emb.add_field(name=_("Until"), value=until)
|
||||
@@ -507,8 +508,15 @@ class CaseType:
|
||||
self.image = image
|
||||
self.case_str = case_str
|
||||
self.guild = guild
|
||||
|
||||
if "audit_type" in kwargs:
|
||||
kwargs.pop("audit_type", None)
|
||||
log.warning(
|
||||
"Fix this using the hidden command: `modlogset fixcasetypes` in Discord: "
|
||||
"Got outdated key in casetype: audit_type"
|
||||
)
|
||||
if kwargs:
|
||||
log.warning("Got unexpected keys in case %s", ",".join(kwargs.keys()))
|
||||
log.warning("Got unexpected key(s) in casetype: %s", ",".join(kwargs.keys()))
|
||||
|
||||
async def to_json(self):
|
||||
"""Transforms the case type into a dict and saves it"""
|
||||
|
||||
53
redbot/core/settings_caches.py
Normal file
53
redbot/core/settings_caches.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
from argparse import Namespace
|
||||
|
||||
import discord
|
||||
|
||||
from .config import Config
|
||||
|
||||
|
||||
class PrefixManager:
|
||||
def __init__(self, config: Config, cli_flags: Namespace):
|
||||
self._config: Config = config
|
||||
self._global_prefix_overide: Optional[List[str]] = sorted(
|
||||
cli_flags.prefix, reverse=True
|
||||
) or None
|
||||
self._cached: Dict[Optional[int], List[str]] = {}
|
||||
|
||||
async def get_prefixes(self, guild: Optional[discord.Guild] = None) -> List[str]:
|
||||
ret: List[str]
|
||||
|
||||
gid: Optional[int] = guild.id if guild else None
|
||||
|
||||
if gid in self._cached:
|
||||
ret = self._cached[gid].copy()
|
||||
else:
|
||||
if gid is not None:
|
||||
ret = await self._config.guild_from_id(gid).prefix()
|
||||
if not ret:
|
||||
ret = await self.get_prefixes(None)
|
||||
else:
|
||||
ret = self._global_prefix_overide or (await self._config.prefix())
|
||||
|
||||
self._cached[gid] = ret.copy()
|
||||
|
||||
return ret
|
||||
|
||||
async def set_prefixes(
|
||||
self, guild: Optional[discord.Guild] = None, prefixes: Optional[List[str]] = None
|
||||
):
|
||||
gid: Optional[int] = guild.id if guild else None
|
||||
prefixes = prefixes or []
|
||||
if not isinstance(prefixes, list) and not all(isinstance(pfx, str) for pfx in prefixes):
|
||||
raise TypeError("Prefixes must be a list of strings")
|
||||
prefixes = sorted(prefixes, reverse=True)
|
||||
if gid is None:
|
||||
if not prefixes:
|
||||
raise ValueError("You must have at least one prefix.")
|
||||
self._cached.clear()
|
||||
await self._config.prefix.set(prefixes)
|
||||
else:
|
||||
del self._cached[gid]
|
||||
await self._config.guild_from_id(gid).prefix.set(prefixes)
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import warnings
|
||||
from asyncio import AbstractEventLoop, as_completed, Semaphore
|
||||
from asyncio.futures import isfuture
|
||||
from itertools import chain
|
||||
@@ -177,14 +178,20 @@ def bounded_gather_iter(
|
||||
TypeError
|
||||
When invalid parameters are passed
|
||||
"""
|
||||
if loop is None:
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop is not None:
|
||||
warnings.warn(
|
||||
"Explicitly passing the loop will not work in Red 3.4+ and is currently ignored."
|
||||
"Call this from the related event loop.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
if semaphore is None:
|
||||
if not isinstance(limit, int) or limit <= 0:
|
||||
raise TypeError("limit must be an int > 0")
|
||||
|
||||
semaphore = Semaphore(limit, loop=loop)
|
||||
semaphore = Semaphore(limit)
|
||||
|
||||
pending = []
|
||||
|
||||
@@ -195,7 +202,7 @@ def bounded_gather_iter(
|
||||
cof = _sem_wrapper(semaphore, cof)
|
||||
pending.append(cof)
|
||||
|
||||
return as_completed(pending, loop=loop)
|
||||
return as_completed(pending)
|
||||
|
||||
|
||||
def bounded_gather(
|
||||
@@ -228,15 +235,21 @@ def bounded_gather(
|
||||
TypeError
|
||||
When invalid parameters are passed
|
||||
"""
|
||||
if loop is None:
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop is not None:
|
||||
warnings.warn(
|
||||
"Explicitly passing the loop will not work in Red 3.4+ and is currently ignored."
|
||||
"Call this from the related event loop.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
if semaphore is None:
|
||||
if not isinstance(limit, int) or limit <= 0:
|
||||
raise TypeError("limit must be an int > 0")
|
||||
|
||||
semaphore = Semaphore(limit, loop=loop)
|
||||
semaphore = Semaphore(limit)
|
||||
|
||||
tasks = (_sem_wrapper(semaphore, task) for task in coros_or_futures)
|
||||
|
||||
return asyncio.gather(*tasks, loop=loop, return_exceptions=return_exceptions)
|
||||
return asyncio.gather(*tasks, return_exceptions=return_exceptions)
|
||||
|
||||
@@ -21,7 +21,7 @@ class AntiSpam:
|
||||
|
||||
# TODO : Decorator interface for command check using `spammy`
|
||||
# with insertion of the antispam element into context
|
||||
# for manual stamping on succesful command completion
|
||||
# for manual stamping on successful command completion
|
||||
|
||||
default_intervals = [
|
||||
(timedelta(seconds=5), 3),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import functools
|
||||
import warnings
|
||||
from typing import Union, Iterable, Optional
|
||||
import discord
|
||||
|
||||
@@ -200,7 +201,9 @@ def start_adding_reactions(
|
||||
await message.add_reaction(emoji)
|
||||
|
||||
if loop is None:
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
else:
|
||||
warnings.warn("Explicitly passing the loop will not work in Red 3.4+", DeprecationWarning)
|
||||
|
||||
return loop.create_task(task())
|
||||
|
||||
|
||||
@@ -38,12 +38,13 @@ async def mass_purge(messages: List[discord.Message], channel: discord.TextChann
|
||||
|
||||
"""
|
||||
while messages:
|
||||
if len(messages) > 1:
|
||||
# discord.NotFound can be raised when `len(messages) == 1` and the message does not exist.
|
||||
# As a result of this obscure behavior, this error needs to be caught just in case.
|
||||
try:
|
||||
await channel.delete_messages(messages[:100])
|
||||
messages = messages[100:]
|
||||
else:
|
||||
await messages[0].delete()
|
||||
messages = []
|
||||
except discord.errors.HTTPException:
|
||||
pass
|
||||
messages = messages[100:]
|
||||
await asyncio.sleep(1.5)
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Callable, ClassVar, List, Optional, Pattern, Sequence, Tuple, Union, cast
|
||||
|
||||
|
||||
Reference in New Issue
Block a user