1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
|
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import Any, TYPE_CHECKING, List, Optional, Sequence, Union
from ..enums import AppCommandOptionType, AppCommandType, Locale
from ..errors import DiscordException, HTTPException, _flatten_error_dict, MissingApplicationID as MissingApplicationID
from ..utils import _human_join
__all__ = (
'AppCommandError',
'CommandInvokeError',
'TransformerError',
'TranslationError',
'CheckFailure',
'CommandAlreadyRegistered',
'CommandSignatureMismatch',
'CommandNotFound',
'CommandLimitReached',
'NoPrivateMessage',
'MissingRole',
'MissingAnyRole',
'MissingPermissions',
'BotMissingPermissions',
'CommandOnCooldown',
'MissingApplicationID',
'CommandSyncFailure',
)
if TYPE_CHECKING:
from .commands import Command, Group, ContextMenu, Parameter
from .transformers import Transformer
from .translator import TranslationContextTypes, locale_str
from ..types.snowflake import Snowflake, SnowflakeList
from .checks import Cooldown
CommandTypes = Union[Command[Any, ..., Any], Group, ContextMenu]
class AppCommandError(DiscordException):
"""The base exception type for all application command related errors.
This inherits from :exc:`discord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into various error handlers
in this order:
- :meth:`Command.error <discord.app_commands.Command.error>`
- :meth:`Group.on_error <discord.app_commands.Group.on_error>`
- :meth:`CommandTree.on_error <discord.app_commands.CommandTree.on_error>`
.. versionadded:: 2.0
"""
pass
class CommandInvokeError(AppCommandError):
"""An exception raised when the command being invoked raised an exception.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
Attributes
-----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
command: Union[:class:`Command`, :class:`ContextMenu`]
The command that failed.
"""
def __init__(self, command: Union[Command[Any, ..., Any], ContextMenu], e: Exception) -> None:
self.original: Exception = e
self.command: Union[Command[Any, ..., Any], ContextMenu] = command
super().__init__(f'Command {command.name!r} raised an exception: {e.__class__.__name__}: {e}')
class TransformerError(AppCommandError):
"""An exception raised when a :class:`Transformer` or type annotation fails to
convert to its target type.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
If an exception occurs while converting that does not subclass
:exc:`AppCommandError` then the exception is wrapped into this exception.
The original exception can be retrieved using the ``__cause__`` attribute.
Otherwise if the exception derives from :exc:`AppCommandError` then it will
be propagated as-is.
.. versionadded:: 2.0
Attributes
-----------
value: Any
The value that failed to convert.
type: :class:`~discord.AppCommandOptionType`
The type of argument that failed to convert.
transformer: :class:`Transformer`
The transformer that failed the conversion.
"""
def __init__(self, value: Any, opt_type: AppCommandOptionType, transformer: Transformer):
self.value: Any = value
self.type: AppCommandOptionType = opt_type
self.transformer: Transformer = transformer
super().__init__(f'Failed to convert {value} to {transformer._error_display_name!s}')
class TranslationError(AppCommandError):
"""An exception raised when the library fails to translate a string.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
If an exception occurs while calling :meth:`Translator.translate` that does
not subclass this then the exception is wrapped into this exception.
The original exception can be retrieved using the ``__cause__`` attribute.
Otherwise it will be propagated as-is.
.. versionadded:: 2.0
Attributes
-----------
string: Optional[Union[:class:`str`, :class:`locale_str`]]
The string that caused the error, if any.
locale: Optional[:class:`~discord.Locale`]
The locale that caused the error, if any.
context: :class:`~discord.app_commands.TranslationContext`
The context of the translation that triggered the error.
"""
def __init__(
self,
*msg: str,
string: Optional[Union[str, locale_str]] = None,
locale: Optional[Locale] = None,
context: TranslationContextTypes,
) -> None:
self.string: Optional[Union[str, locale_str]] = string
self.locale: Optional[Locale] = locale
self.context: TranslationContextTypes = context
if msg:
super().__init__(*msg)
else:
ctx = context.location.name.replace('_', ' ')
fmt = f'Failed to translate {self.string!r} in a {ctx}'
if self.locale is not None:
fmt = f'{fmt} in the {self.locale.value} locale'
super().__init__(fmt)
class CheckFailure(AppCommandError):
"""An exception raised when check predicates in a command have failed.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
"""
pass
class NoPrivateMessage(CheckFailure):
"""An exception raised when a command does not work in a direct message.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or 'This command cannot be used in direct messages.')
class MissingRole(CheckFailure):
"""An exception raised when the command invoker lacks a role to run a command.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
Attributes
-----------
missing_role: Union[:class:`str`, :class:`int`]
The required role that is missing.
This is the parameter passed to :func:`~discord.app_commands.checks.has_role`.
"""
def __init__(self, missing_role: Snowflake) -> None:
self.missing_role: Snowflake = missing_role
message = f'Role {missing_role!r} is required to run this command.'
super().__init__(message)
class MissingAnyRole(CheckFailure):
"""An exception raised when the command invoker lacks any of the roles
specified to run a command.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
Attributes
-----------
missing_roles: List[Union[:class:`str`, :class:`int`]]
The roles that the invoker is missing.
These are the parameters passed to :func:`~discord.app_commands.checks.has_any_role`.
"""
def __init__(self, missing_roles: SnowflakeList) -> None:
self.missing_roles: SnowflakeList = missing_roles
fmt = _human_join([f"'{role}'" for role in missing_roles])
message = f'You are missing at least one of the required roles: {fmt}'
super().__init__(message)
class MissingPermissions(CheckFailure):
"""An exception raised when the command invoker lacks permissions to run a
command.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
Attributes
-----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions]
fmt = _human_join(missing, final='and')
message = f'You are missing {fmt} permission(s) to run this command.'
super().__init__(message, *args)
class BotMissingPermissions(CheckFailure):
"""An exception raised when the bot's member lacks permissions to run a
command.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
Attributes
-----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions]
fmt = _human_join(missing, final='and')
message = f'Bot requires {fmt} permission(s) to run this command.'
super().__init__(message, *args)
class CommandOnCooldown(CheckFailure):
"""An exception raised when the command being invoked is on cooldown.
This inherits from :exc:`~discord.app_commands.CheckFailure`.
.. versionadded:: 2.0
Attributes
-----------
cooldown: :class:`~discord.app_commands.Cooldown`
The cooldown that was triggered.
retry_after: :class:`float`
The amount of seconds to wait before you can retry again.
"""
def __init__(self, cooldown: Cooldown, retry_after: float) -> None:
self.cooldown: Cooldown = cooldown
self.retry_after: float = retry_after
super().__init__(f'You are on cooldown. Try again in {retry_after:.2f}s')
class CommandAlreadyRegistered(AppCommandError):
"""An exception raised when a command is already registered.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
Attributes
-----------
name: :class:`str`
The name of the command already registered.
guild_id: Optional[:class:`int`]
The guild ID this command was already registered at.
If ``None`` then it was a global command.
"""
def __init__(self, name: str, guild_id: Optional[int]):
self.name: str = name
self.guild_id: Optional[int] = guild_id
super().__init__(f'Command {name!r} already registered.')
class CommandNotFound(AppCommandError):
"""An exception raised when an application command could not be found.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
Attributes
------------
name: :class:`str`
The name of the application command not found.
parents: List[:class:`str`]
A list of parent command names that were previously found
prior to the application command not being found.
type: :class:`~discord.AppCommandType`
The type of command that was not found.
"""
def __init__(self, name: str, parents: List[str], type: AppCommandType = AppCommandType.chat_input):
self.name: str = name
self.parents: List[str] = parents
self.type: AppCommandType = type
super().__init__(f'Application command {name!r} not found')
class CommandLimitReached(AppCommandError):
"""An exception raised when the maximum number of application commands was reached
either globally or in a guild.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
Attributes
------------
type: :class:`~discord.AppCommandType`
The type of command that reached the limit.
guild_id: Optional[:class:`int`]
The guild ID that reached the limit or ``None`` if it was global.
limit: :class:`int`
The limit that was hit.
"""
def __init__(self, guild_id: Optional[int], limit: int, type: AppCommandType = AppCommandType.chat_input):
self.guild_id: Optional[int] = guild_id
self.limit: int = limit
self.type: AppCommandType = type
lookup = {
AppCommandType.chat_input: 'slash commands',
AppCommandType.message: 'message context menu commands',
AppCommandType.user: 'user context menu commands',
}
desc = lookup.get(type, 'application commands')
ns = 'globally' if self.guild_id is None else f'for guild ID {self.guild_id}'
super().__init__(f'maximum number of {desc} exceeded {limit} {ns}')
class CommandSignatureMismatch(AppCommandError):
"""An exception raised when an application command from Discord has a different signature
from the one provided in the code. This happens because your command definition differs
from the command definition you provided Discord. Either your code is out of date or the
data from Discord is out of sync.
This inherits from :exc:`~discord.app_commands.AppCommandError`.
.. versionadded:: 2.0
Attributes
------------
command: Union[:class:`~.app_commands.Command`, :class:`~.app_commands.ContextMenu`, :class:`~.app_commands.Group`]
The command that had the signature mismatch.
"""
def __init__(self, command: Union[Command[Any, ..., Any], ContextMenu, Group]):
self.command: Union[Command[Any, ..., Any], ContextMenu, Group] = command
msg = (
f'The signature for command {command.name!r} is different from the one provided by Discord. '
'This can happen because either your code is out of date or you have not synced the '
'commands with Discord, causing the mismatch in data. It is recommended to sync the '
'command tree to fix this issue.'
)
super().__init__(msg)
def _get_command_error(
index: str,
inner: Any,
objects: Sequence[Union[Parameter, CommandTypes]],
messages: List[str],
indent: int = 0,
) -> None:
# Import these here to avoid circular imports
from .commands import Command, Group, ContextMenu
indentation = ' ' * indent
# Top level errors are:
# <number>: { <key>: <error> }
# The dicts could be nested, e.g.
# <number>: { <key>: { <second>: <error> } }
# Luckily, this is already handled by the flatten_error_dict utility
if not index.isdigit():
errors = _flatten_error_dict(inner, index)
messages.extend(f'In {k}: {v}' for k, v in errors.items())
return
idx = int(index)
try:
obj = objects[idx]
except IndexError:
dedent_one_level = ' ' * (indent - 2)
errors = _flatten_error_dict(inner, index)
messages.extend(f'{dedent_one_level}In {k}: {v}' for k, v in errors.items())
return
children: Sequence[Union[Parameter, CommandTypes]] = []
if isinstance(obj, Command):
messages.append(f'{indentation}In command {obj.qualified_name!r} defined in function {obj.callback.__qualname__!r}')
children = obj.parameters
elif isinstance(obj, Group):
messages.append(f'{indentation}In group {obj.qualified_name!r} defined in module {obj.module!r}')
children = obj.commands
elif isinstance(obj, ContextMenu):
messages.append(
f'{indentation}In context menu {obj.qualified_name!r} defined in function {obj.callback.__qualname__!r}'
)
else:
messages.append(f'{indentation}In parameter {obj.name!r}')
for key, remaining in inner.items():
# Special case the 'options' key since they have well defined meanings
if key == 'options':
for index, d in remaining.items():
_get_command_error(index, d, children, messages, indent=indent + 2)
elif key == '_errors':
errors = [x.get('message', '') for x in remaining]
messages.extend(f'{indentation} {message}' for message in errors)
else:
if isinstance(remaining, dict):
try:
inner_errors = remaining['_errors']
except KeyError:
errors = _flatten_error_dict(remaining, key=key)
else:
errors = {key: ' '.join(x.get('message', '') for x in inner_errors)}
if isinstance(errors, dict):
messages.extend(f'{indentation} {k}: {v}' for k, v in errors.items())
class CommandSyncFailure(AppCommandError, HTTPException):
"""An exception raised when :meth:`CommandTree.sync` failed.
This provides syncing failures in a slightly more readable format.
This inherits from :exc:`~discord.app_commands.AppCommandError`
and :exc:`~discord.HTTPException`.
.. versionadded:: 2.0
"""
def __init__(self, child: HTTPException, commands: List[CommandTypes]) -> None:
# Consume the child exception and make it seem as if we are that exception
self.__dict__.update(child.__dict__)
messages = [f'Failed to upload commands to Discord (HTTP status {self.status}, error code {self.code})']
if self._errors:
# Handle case where the errors dict has no actual chain such as APPLICATION_COMMAND_TOO_LARGE
if len(self._errors) == 1 and '_errors' in self._errors:
errors = self._errors['_errors']
if len(errors) == 1:
extra = errors[0].get('message')
if extra:
messages[0] += f': {extra}'
else:
messages.extend(f'Error {e.get("code", "")}: {e.get("message", "")}' for e in errors)
else:
for index, inner in self._errors.items():
_get_command_error(index, inner, commands, messages)
# Equivalent to super().__init__(...) but skips other constructors
self.args = ('\n'.join(messages),)
|