disagreement 0.2.0rc1__py3-none-any.whl → 0.3.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,563 +1,690 @@
1
- # disagreement/ext/commands/core.py
2
-
3
- from __future__ import annotations
4
-
5
- import asyncio
6
- import logging
7
- import inspect
8
- from typing import (
9
- TYPE_CHECKING,
10
- Optional,
11
- List,
12
- Dict,
13
- Any,
14
- Union,
15
- Callable,
16
- Awaitable,
17
- Tuple,
18
- get_origin,
19
- get_args,
20
- )
21
-
22
- from .view import StringView
23
- from .errors import (
24
- CommandError,
25
- CommandNotFound,
26
- BadArgument,
27
- MissingRequiredArgument,
28
- ArgumentParsingError,
29
- CheckFailure,
30
- CommandInvokeError,
31
- )
32
- from .converters import run_converters, DEFAULT_CONVERTERS, Converter
33
- from disagreement.typing import Typing
34
-
35
- logger = logging.getLogger(__name__)
36
-
37
- if TYPE_CHECKING:
38
- from .cog import Cog
39
- from disagreement.client import Client
40
- from disagreement.models import Message, User
41
-
42
-
43
- class Command:
44
- """
45
- Represents a bot command.
46
-
47
- Attributes:
48
- name (str): The primary name of the command.
49
- callback (Callable[..., Awaitable[None]]): The coroutine function to execute.
50
- aliases (List[str]): Alternative names for the command.
51
- brief (Optional[str]): A short description for help commands.
52
- description (Optional[str]): A longer description for help commands.
53
- cog (Optional['Cog']): Reference to the Cog this command belongs to.
54
- params (Dict[str, inspect.Parameter]): Cached parameters of the callback.
55
- """
56
-
57
- def __init__(self, callback: Callable[..., Awaitable[None]], **attrs: Any):
58
- if not asyncio.iscoroutinefunction(callback):
59
- raise TypeError("Command callback must be a coroutine function.")
60
-
61
- self.callback: Callable[..., Awaitable[None]] = callback
62
- self.name: str = attrs.get("name", callback.__name__)
63
- self.aliases: List[str] = attrs.get("aliases", [])
64
- self.brief: Optional[str] = attrs.get("brief")
65
- self.description: Optional[str] = attrs.get("description") or callback.__doc__
66
- self.cog: Optional["Cog"] = attrs.get("cog")
67
-
68
- self.params = inspect.signature(callback).parameters
69
- self.checks: List[Callable[["CommandContext"], Awaitable[bool] | bool]] = []
70
- if hasattr(callback, "__command_checks__"):
71
- self.checks.extend(getattr(callback, "__command_checks__"))
72
-
73
- self.max_concurrency: Optional[Tuple[int, str]] = None
74
- if hasattr(callback, "__max_concurrency__"):
75
- self.max_concurrency = getattr(callback, "__max_concurrency__")
76
-
77
- def add_check(
78
- self, predicate: Callable[["CommandContext"], Awaitable[bool] | bool]
79
- ) -> None:
80
- self.checks.append(predicate)
81
-
82
- async def invoke(self, ctx: "CommandContext", *args: Any, **kwargs: Any) -> None:
83
- from .errors import CheckFailure
84
-
85
- for predicate in self.checks:
86
- result = predicate(ctx)
87
- if inspect.isawaitable(result):
88
- result = await result
89
- if not result:
90
- raise CheckFailure("Check predicate failed.")
91
-
92
- if self.cog:
93
- await self.callback(self.cog, ctx, *args, **kwargs)
94
- else:
95
- await self.callback(ctx, *args, **kwargs)
96
-
97
-
98
- PrefixCommand = Command # Alias for clarity in hybrid commands
99
-
100
-
101
- class CommandContext:
102
- """
103
- Represents the context in which a command is being invoked.
104
- """
105
-
106
- def __init__(
107
- self,
108
- *,
109
- message: "Message",
110
- bot: "Client",
111
- prefix: str,
112
- command: "Command",
113
- invoked_with: str,
114
- args: Optional[List[Any]] = None,
115
- kwargs: Optional[Dict[str, Any]] = None,
116
- cog: Optional["Cog"] = None,
117
- ):
118
- self.message: "Message" = message
119
- self.bot: "Client" = bot
120
- self.prefix: str = prefix
121
- self.command: "Command" = command
122
- self.invoked_with: str = invoked_with
123
- self.args: List[Any] = args or []
124
- self.kwargs: Dict[str, Any] = kwargs or {}
125
- self.cog: Optional["Cog"] = cog
126
-
127
- self.author: "User" = message.author
128
-
129
- @property
130
- def guild(self):
131
- """The guild this command was invoked in."""
132
- if self.message.guild_id and hasattr(self.bot, "get_guild"):
133
- return self.bot.get_guild(self.message.guild_id)
134
- return None
135
-
136
- async def reply(
137
- self,
138
- content: Optional[str] = None,
139
- *,
140
- mention_author: Optional[bool] = None,
141
- **kwargs: Any,
142
- ) -> "Message":
143
- """Replies to the invoking message.
144
-
145
- Parameters
146
- ----------
147
- content: str
148
- The content to send.
149
- mention_author: Optional[bool]
150
- Whether to mention the author in the reply. If ``None`` the
151
- client's :attr:`mention_replies` value is used.
152
- """
153
-
154
- allowed_mentions = kwargs.pop("allowed_mentions", None)
155
- if mention_author is None:
156
- mention_author = getattr(self.bot, "mention_replies", False)
157
-
158
- if allowed_mentions is None:
159
- allowed_mentions = {"replied_user": mention_author}
160
- else:
161
- allowed_mentions = dict(allowed_mentions)
162
- allowed_mentions.setdefault("replied_user", mention_author)
163
-
164
- return await self.bot.send_message(
165
- channel_id=self.message.channel_id,
166
- content=content,
167
- message_reference={
168
- "message_id": self.message.id,
169
- "channel_id": self.message.channel_id,
170
- "guild_id": self.message.guild_id,
171
- },
172
- allowed_mentions=allowed_mentions,
173
- **kwargs,
174
- )
175
-
176
- async def send(self, content: str, **kwargs: Any) -> "Message":
177
- return await self.bot.send_message(
178
- channel_id=self.message.channel_id, content=content, **kwargs
179
- )
180
-
181
- async def edit(
182
- self,
183
- message: Union[str, "Message"],
184
- *,
185
- content: Optional[str] = None,
186
- **kwargs: Any,
187
- ) -> "Message":
188
- """Edits a message previously sent by the bot."""
189
-
190
- message_id = message if isinstance(message, str) else message.id
191
- return await self.bot.edit_message(
192
- channel_id=self.message.channel_id,
193
- message_id=message_id,
194
- content=content,
195
- **kwargs,
196
- )
197
-
198
- def typing(self) -> "Typing":
199
- """Return a typing context manager for this context's channel."""
200
-
201
- return self.bot.typing(self.message.channel_id)
202
-
203
-
204
- class CommandHandler:
205
- """
206
- Manages command registration, parsing, and dispatching.
207
- """
208
-
209
- def __init__(
210
- self,
211
- client: "Client",
212
- prefix: Union[
213
- str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
214
- ],
215
- ):
216
- self.client: "Client" = client
217
- self.prefix: Union[
218
- str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
219
- ] = prefix
220
- self.commands: Dict[str, Command] = {}
221
- self.cogs: Dict[str, "Cog"] = {}
222
- self._concurrency: Dict[str, Dict[str, int]] = {}
223
-
224
- from .help import HelpCommand
225
-
226
- self.add_command(HelpCommand(self))
227
-
228
- def add_command(self, command: Command) -> None:
229
- if command.name in self.commands:
230
- raise ValueError(f"Command '{command.name}' is already registered.")
231
-
232
- self.commands[command.name.lower()] = command
233
- for alias in command.aliases:
234
- if alias in self.commands:
235
- logger.warning(
236
- "Alias '%s' for command '%s' conflicts with an existing command or alias.",
237
- alias,
238
- command.name,
239
- )
240
- self.commands[alias.lower()] = command
241
-
242
- def remove_command(self, name: str) -> Optional[Command]:
243
- command = self.commands.pop(name.lower(), None)
244
- if command:
245
- for alias in command.aliases:
246
- self.commands.pop(alias.lower(), None)
247
- return command
248
-
249
- def get_command(self, name: str) -> Optional[Command]:
250
- return self.commands.get(name.lower())
251
-
252
- def add_cog(self, cog_to_add: "Cog") -> None:
253
- from .cog import Cog
254
-
255
- if not isinstance(cog_to_add, Cog):
256
- raise TypeError("Argument must be a subclass of Cog.")
257
-
258
- if cog_to_add.cog_name in self.cogs:
259
- raise ValueError(
260
- f"Cog with name '{cog_to_add.cog_name}' is already registered."
261
- )
262
-
263
- self.cogs[cog_to_add.cog_name] = cog_to_add
264
-
265
- for cmd in cog_to_add.get_commands():
266
- self.add_command(cmd)
267
-
268
- if hasattr(self.client, "_event_dispatcher"):
269
- for event_name, callback in cog_to_add.get_listeners():
270
- self.client._event_dispatcher.register(event_name.upper(), callback)
271
- else:
272
- logger.warning(
273
- "Client does not have '_event_dispatcher'. Listeners for cog '%s' not registered.",
274
- cog_to_add.cog_name,
275
- )
276
-
277
- if hasattr(cog_to_add, "cog_load") and inspect.iscoroutinefunction(
278
- cog_to_add.cog_load
279
- ):
280
- asyncio.create_task(cog_to_add.cog_load())
281
-
282
- logger.info("Cog '%s' added.", cog_to_add.cog_name)
283
-
284
- def remove_cog(self, cog_name: str) -> Optional["Cog"]:
285
- cog_to_remove = self.cogs.pop(cog_name, None)
286
- if cog_to_remove:
287
- for cmd in cog_to_remove.get_commands():
288
- self.remove_command(cmd.name)
289
-
290
- if hasattr(self.client, "_event_dispatcher"):
291
- for event_name, callback in cog_to_remove.get_listeners():
292
- logger.debug(
293
- "Listener '%s' for event '%s' from cog '%s' needs manual unregistration logic in EventDispatcher.",
294
- callback.__name__,
295
- event_name,
296
- cog_name,
297
- )
298
-
299
- if hasattr(cog_to_remove, "cog_unload") and inspect.iscoroutinefunction(
300
- cog_to_remove.cog_unload
301
- ):
302
- asyncio.create_task(cog_to_remove.cog_unload())
303
-
304
- cog_to_remove._eject()
305
- logger.info("Cog '%s' removed.", cog_name)
306
- return cog_to_remove
307
-
308
- def _acquire_concurrency(self, ctx: CommandContext) -> None:
309
- mc = getattr(ctx.command, "max_concurrency", None)
310
- if not mc:
311
- return
312
- limit, scope = mc
313
- if scope == "user":
314
- key = ctx.author.id
315
- elif scope == "guild":
316
- key = ctx.message.guild_id or ctx.author.id
317
- else:
318
- key = "global"
319
- buckets = self._concurrency.setdefault(ctx.command.name, {})
320
- current = buckets.get(key, 0)
321
- if current >= limit:
322
- from .errors import MaxConcurrencyReached
323
-
324
- raise MaxConcurrencyReached(limit)
325
- buckets[key] = current + 1
326
-
327
- def _release_concurrency(self, ctx: CommandContext) -> None:
328
- mc = getattr(ctx.command, "max_concurrency", None)
329
- if not mc:
330
- return
331
- _, scope = mc
332
- if scope == "user":
333
- key = ctx.author.id
334
- elif scope == "guild":
335
- key = ctx.message.guild_id or ctx.author.id
336
- else:
337
- key = "global"
338
- buckets = self._concurrency.get(ctx.command.name)
339
- if not buckets:
340
- return
341
- current = buckets.get(key, 0)
342
- if current <= 1:
343
- buckets.pop(key, None)
344
- else:
345
- buckets[key] = current - 1
346
- if not buckets:
347
- self._concurrency.pop(ctx.command.name, None)
348
-
349
- async def get_prefix(self, message: "Message") -> Union[str, List[str], None]:
350
- if callable(self.prefix):
351
- if inspect.iscoroutinefunction(self.prefix):
352
- return await self.prefix(self.client, message)
353
- else:
354
- return self.prefix(self.client, message) # type: ignore
355
- return self.prefix
356
-
357
- async def _parse_arguments(
358
- self, command: Command, ctx: CommandContext, view: StringView
359
- ) -> Tuple[List[Any], Dict[str, Any]]:
360
- args_list = []
361
- kwargs_dict = {}
362
- params_to_parse = list(command.params.values())
363
-
364
- if params_to_parse and params_to_parse[0].name == "self" and command.cog:
365
- params_to_parse.pop(0)
366
- if params_to_parse and params_to_parse[0].name == "ctx":
367
- params_to_parse.pop(0)
368
-
369
- for param in params_to_parse:
370
- view.skip_whitespace()
371
- final_value_for_param: Any = inspect.Parameter.empty
372
-
373
- if param.kind == inspect.Parameter.VAR_POSITIONAL:
374
- while not view.eof:
375
- view.skip_whitespace()
376
- if view.eof:
377
- break
378
- word = view.get_word()
379
- if word or not view.eof:
380
- args_list.append(word)
381
- elif view.eof:
382
- break
383
- break
384
-
385
- arg_str_value: Optional[str] = (
386
- None # Holds the raw string for current param
387
- )
388
-
389
- if view.eof: # No more input string
390
- if param.default is not inspect.Parameter.empty:
391
- final_value_for_param = param.default
392
- elif param.kind != inspect.Parameter.VAR_KEYWORD:
393
- raise MissingRequiredArgument(param.name)
394
- else: # VAR_KEYWORD at EOF is fine
395
- break
396
- else: # Input available
397
- is_last_pos_str_greedy = (
398
- param == params_to_parse[-1]
399
- and param.annotation is str
400
- and param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
401
- )
402
-
403
- if is_last_pos_str_greedy:
404
- arg_str_value = view.read_rest().strip()
405
- if (
406
- not arg_str_value
407
- and param.default is not inspect.Parameter.empty
408
- ):
409
- final_value_for_param = param.default
410
- else: # Includes empty string if that's what's left
411
- final_value_for_param = arg_str_value
412
- else: # Not greedy, or not string, or not last positional
413
- if view.buffer[view.index] == '"':
414
- arg_str_value = view.get_quoted_string()
415
- if arg_str_value == "" and view.buffer[view.index] == '"':
416
- raise BadArgument(
417
- f"Unterminated quoted string for argument '{param.name}'."
418
- )
419
- else:
420
- arg_str_value = view.get_word()
421
-
422
- # If final_value_for_param was not set by greedy logic, try conversion
423
- if final_value_for_param is inspect.Parameter.empty:
424
- if (
425
- arg_str_value is None
426
- ): # Should not happen if view.get_word/get_quoted_string is robust
427
- if param.default is not inspect.Parameter.empty:
428
- final_value_for_param = param.default
429
- else:
430
- raise MissingRequiredArgument(param.name)
431
- else: # We have an arg_str_value (could be empty string "" from quotes)
432
- annotation = param.annotation
433
- origin = get_origin(annotation)
434
-
435
- if origin is Union: # Handles Optional[T] and Union[T1, T2]
436
- union_args = get_args(annotation)
437
- is_optional = (
438
- len(union_args) == 2 and type(None) in union_args
439
- )
440
-
441
- converted_for_union = False
442
- last_err_union: Optional[BadArgument] = None
443
- for t_arg in union_args:
444
- if t_arg is type(None):
445
- continue
446
- try:
447
- final_value_for_param = await run_converters(
448
- ctx, t_arg, arg_str_value
449
- )
450
- converted_for_union = True
451
- break
452
- except BadArgument as e:
453
- last_err_union = e
454
-
455
- if not converted_for_union:
456
- if (
457
- is_optional and param.default is None
458
- ): # Special handling for Optional[T] if conversion failed
459
- # If arg_str_value was "" and type was Optional[str], StringConverter would return ""
460
- # If arg_str_value was "" and type was Optional[int], BadArgument would be raised.
461
- # This path is for when all actual types in Optional[T] fail conversion.
462
- # If default is None, we can assign None.
463
- final_value_for_param = None
464
- elif last_err_union:
465
- raise last_err_union
466
- else: # Should not be reached if logic is correct
467
- raise BadArgument(
468
- f"Could not convert '{arg_str_value}' to any of {union_args} for param '{param.name}'."
469
- )
470
- elif annotation is inspect.Parameter.empty or annotation is str:
471
- final_value_for_param = arg_str_value
472
- else: # Standard type hint
473
- final_value_for_param = await run_converters(
474
- ctx, annotation, arg_str_value
475
- )
476
-
477
- # Final check if value was resolved
478
- if final_value_for_param is inspect.Parameter.empty:
479
- if param.default is not inspect.Parameter.empty:
480
- final_value_for_param = param.default
481
- elif param.kind != inspect.Parameter.VAR_KEYWORD:
482
- # This state implies an issue if required and no default, and no input was parsed.
483
- raise MissingRequiredArgument(
484
- f"Parameter '{param.name}' could not be resolved."
485
- )
486
-
487
- # Assign to args_list or kwargs_dict if a value was determined
488
- if final_value_for_param is not inspect.Parameter.empty:
489
- if (
490
- param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
491
- or param.kind == inspect.Parameter.POSITIONAL_ONLY
492
- ):
493
- args_list.append(final_value_for_param)
494
- elif param.kind == inspect.Parameter.KEYWORD_ONLY:
495
- kwargs_dict[param.name] = final_value_for_param
496
-
497
- return args_list, kwargs_dict
498
-
499
- async def process_commands(self, message: "Message") -> None:
500
- if not message.content:
501
- return
502
-
503
- prefix_to_use = await self.get_prefix(message)
504
- if not prefix_to_use:
505
- return
506
-
507
- actual_prefix: Optional[str] = None
508
- if isinstance(prefix_to_use, list):
509
- for p in prefix_to_use:
510
- if message.content.startswith(p):
511
- actual_prefix = p
512
- break
513
- if not actual_prefix:
514
- return
515
- elif isinstance(prefix_to_use, str):
516
- if message.content.startswith(prefix_to_use):
517
- actual_prefix = prefix_to_use
518
- else:
519
- return
520
- else:
521
- return
522
-
523
- if actual_prefix is None:
524
- return
525
-
526
- content_without_prefix = message.content[len(actual_prefix) :]
527
- view = StringView(content_without_prefix)
528
-
529
- command_name = view.get_word()
530
- if not command_name:
531
- return
532
-
533
- command = self.get_command(command_name)
534
- if not command:
535
- return
536
-
537
- ctx = CommandContext(
538
- message=message,
539
- bot=self.client,
540
- prefix=actual_prefix,
541
- command=command,
542
- invoked_with=command_name,
543
- cog=command.cog,
544
- )
545
-
546
- try:
547
- parsed_args, parsed_kwargs = await self._parse_arguments(command, ctx, view)
548
- ctx.args = parsed_args
549
- ctx.kwargs = parsed_kwargs
550
- self._acquire_concurrency(ctx)
551
- try:
552
- await command.invoke(ctx, *parsed_args, **parsed_kwargs)
553
- finally:
554
- self._release_concurrency(ctx)
555
- except CommandError as e:
556
- logger.error("Command error for '%s': %s", command.name, e)
557
- if hasattr(self.client, "on_command_error"):
558
- await self.client.on_command_error(ctx, e)
559
- except Exception as e:
560
- logger.error("Unexpected error invoking command '%s': %s", command.name, e)
561
- exc = CommandInvokeError(e)
562
- if hasattr(self.client, "on_command_error"):
563
- await self.client.on_command_error(ctx, exc)
1
+ # disagreement/ext/commands/core.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import inspect
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ Optional,
11
+ List,
12
+ Dict,
13
+ Any,
14
+ Union,
15
+ Callable,
16
+ Awaitable,
17
+ Tuple,
18
+ get_origin,
19
+ get_args,
20
+ )
21
+
22
+ from .view import StringView
23
+ from .errors import (
24
+ CommandError,
25
+ CommandNotFound,
26
+ BadArgument,
27
+ MissingRequiredArgument,
28
+ ArgumentParsingError,
29
+ CheckFailure,
30
+ CommandInvokeError,
31
+ )
32
+ from .converters import run_converters, DEFAULT_CONVERTERS, Converter
33
+ from disagreement.typing import Typing
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ if TYPE_CHECKING:
38
+ from .cog import Cog
39
+ from disagreement.client import Client
40
+ from disagreement.models import Message, User
41
+
42
+
43
+ class GroupMixin:
44
+ def __init__(self, *args, **kwargs):
45
+ super().__init__()
46
+ self.commands: Dict[str, "Command"] = {}
47
+ self.name: str = ""
48
+
49
+ def command(self, **attrs: Any) -> Callable[[Callable[..., Awaitable[None]]], "Command"]:
50
+ def decorator(func: Callable[..., Awaitable[None]]) -> "Command":
51
+ cmd = Command(func, **attrs)
52
+ cmd.cog = getattr(self, "cog", None)
53
+ self.add_command(cmd)
54
+ return cmd
55
+ return decorator
56
+
57
+ def group(self, **attrs: Any) -> Callable[[Callable[..., Awaitable[None]]], "Group"]:
58
+ def decorator(func: Callable[..., Awaitable[None]]) -> "Group":
59
+ cmd = Group(func, **attrs)
60
+ cmd.cog = getattr(self, "cog", None)
61
+ self.add_command(cmd)
62
+ return cmd
63
+ return decorator
64
+
65
+ def add_command(self, command: "Command") -> None:
66
+ if command.name in self.commands:
67
+ raise ValueError(f"Command '{command.name}' is already registered in group '{self.name}'.")
68
+ self.commands[command.name.lower()] = command
69
+ for alias in command.aliases:
70
+ if alias in self.commands:
71
+ logger.warning(f"Alias '{alias}' for command '{command.name}' in group '{self.name}' conflicts with an existing command or alias.")
72
+ self.commands[alias.lower()] = command
73
+
74
+ def get_command(self, name: str) -> Optional["Command"]:
75
+ return self.commands.get(name.lower())
76
+
77
+
78
+ class Command(GroupMixin):
79
+ """
80
+ Represents a bot command.
81
+
82
+ Attributes:
83
+ name (str): The primary name of the command.
84
+ callback (Callable[..., Awaitable[None]]): The coroutine function to execute.
85
+ aliases (List[str]): Alternative names for the command.
86
+ brief (Optional[str]): A short description for help commands.
87
+ description (Optional[str]): A longer description for help commands.
88
+ cog (Optional['Cog']): Reference to the Cog this command belongs to.
89
+ params (Dict[str, inspect.Parameter]): Cached parameters of the callback.
90
+ """
91
+
92
+ def __init__(self, callback: Callable[..., Awaitable[None]], **attrs: Any):
93
+ if not asyncio.iscoroutinefunction(callback):
94
+ raise TypeError("Command callback must be a coroutine function.")
95
+
96
+ super().__init__(**attrs)
97
+ self.callback: Callable[..., Awaitable[None]] = callback
98
+ self.name: str = attrs.get("name", callback.__name__)
99
+ self.aliases: List[str] = attrs.get("aliases", [])
100
+ self.brief: Optional[str] = attrs.get("brief")
101
+ self.description: Optional[str] = attrs.get("description") or callback.__doc__
102
+ self.cog: Optional["Cog"] = attrs.get("cog")
103
+ self.invoke_without_command: bool = attrs.get("invoke_without_command", False)
104
+
105
+ self.params = inspect.signature(callback).parameters
106
+ self.checks: List[Callable[["CommandContext"], Awaitable[bool] | bool]] = []
107
+ if hasattr(callback, "__command_checks__"):
108
+ self.checks.extend(getattr(callback, "__command_checks__"))
109
+
110
+ self.max_concurrency: Optional[Tuple[int, str]] = None
111
+ if hasattr(callback, "__max_concurrency__"):
112
+ self.max_concurrency = getattr(callback, "__max_concurrency__")
113
+
114
+ def add_check(
115
+ self, predicate: Callable[["CommandContext"], Awaitable[bool] | bool]
116
+ ) -> None:
117
+ self.checks.append(predicate)
118
+
119
+ async def _run_checks(self, ctx: "CommandContext") -> None:
120
+ """Runs all cog, local and global checks for the command."""
121
+ from .errors import CheckFailure
122
+
123
+ # Run cog-level check first
124
+ if self.cog:
125
+ cog_check = getattr(self.cog, "cog_check", None)
126
+ if cog_check:
127
+ try:
128
+ result = cog_check(ctx)
129
+ if inspect.isawaitable(result):
130
+ result = await result
131
+ if not result:
132
+ raise CheckFailure(
133
+ f"The cog-level check for command '{self.name}' failed."
134
+ )
135
+ except CheckFailure:
136
+ raise
137
+ except Exception as e:
138
+ raise CommandInvokeError(e) from e
139
+
140
+ # Run local checks
141
+ for predicate in self.checks:
142
+ result = predicate(ctx)
143
+ if inspect.isawaitable(result):
144
+ result = await result
145
+ if not result:
146
+ raise CheckFailure(f"A local check for command '{self.name}' failed.")
147
+
148
+ # Then run global checks from the handler
149
+ if hasattr(ctx.bot, "command_handler"):
150
+ for predicate in ctx.bot.command_handler._global_checks:
151
+ result = predicate(ctx)
152
+ if inspect.isawaitable(result):
153
+ result = await result
154
+ if not result:
155
+ raise CheckFailure(
156
+ f"A global check failed for command '{self.name}'."
157
+ )
158
+
159
+ async def invoke(self, ctx: "CommandContext", *args: Any, **kwargs: Any) -> None:
160
+ await self._run_checks(ctx)
161
+
162
+ before_invoke = None
163
+ after_invoke = None
164
+
165
+ if self.cog:
166
+ before_invoke = getattr(self.cog, "cog_before_invoke", None)
167
+ after_invoke = getattr(self.cog, "cog_after_invoke", None)
168
+
169
+ if before_invoke:
170
+ await before_invoke(ctx)
171
+
172
+ try:
173
+ if self.cog:
174
+ await self.callback(self.cog, ctx, *args, **kwargs)
175
+ else:
176
+ await self.callback(ctx, *args, **kwargs)
177
+ finally:
178
+ if after_invoke:
179
+ await after_invoke(ctx)
180
+
181
+
182
+ class Group(Command):
183
+ """A command that can have subcommands."""
184
+ def __init__(self, callback: Callable[..., Awaitable[None]], **attrs: Any):
185
+ super().__init__(callback, **attrs)
186
+
187
+
188
+ PrefixCommand = Command # Alias for clarity in hybrid commands
189
+
190
+
191
+ class CommandContext:
192
+ """
193
+ Represents the context in which a command is being invoked.
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ *,
199
+ message: "Message",
200
+ bot: "Client",
201
+ prefix: str,
202
+ command: "Command",
203
+ invoked_with: str,
204
+ args: Optional[List[Any]] = None,
205
+ kwargs: Optional[Dict[str, Any]] = None,
206
+ cog: Optional["Cog"] = None,
207
+ ):
208
+ self.message: "Message" = message
209
+ self.bot: "Client" = bot
210
+ self.prefix: str = prefix
211
+ self.command: "Command" = command
212
+ self.invoked_with: str = invoked_with
213
+ self.args: List[Any] = args or []
214
+ self.kwargs: Dict[str, Any] = kwargs or {}
215
+ self.cog: Optional["Cog"] = cog
216
+
217
+ self.author: "User" = message.author
218
+
219
+ @property
220
+ def guild(self):
221
+ """The guild this command was invoked in."""
222
+ if self.message.guild_id and hasattr(self.bot, "get_guild"):
223
+ return self.bot.get_guild(self.message.guild_id)
224
+ return None
225
+
226
+ async def reply(
227
+ self,
228
+ content: Optional[str] = None,
229
+ *,
230
+ mention_author: Optional[bool] = None,
231
+ **kwargs: Any,
232
+ ) -> "Message":
233
+ """Replies to the invoking message.
234
+
235
+ Parameters
236
+ ----------
237
+ content: str
238
+ The content to send.
239
+ mention_author: Optional[bool]
240
+ Whether to mention the author in the reply. If ``None`` the
241
+ client's :attr:`mention_replies` value is used.
242
+ """
243
+
244
+ allowed_mentions = kwargs.pop("allowed_mentions", None)
245
+ if mention_author is None:
246
+ mention_author = getattr(self.bot, "mention_replies", False)
247
+
248
+ if allowed_mentions is None:
249
+ allowed_mentions = {"replied_user": mention_author}
250
+ else:
251
+ allowed_mentions = dict(allowed_mentions)
252
+ allowed_mentions.setdefault("replied_user", mention_author)
253
+
254
+ return await self.bot.send_message(
255
+ channel_id=self.message.channel_id,
256
+ content=content,
257
+ message_reference={
258
+ "message_id": self.message.id,
259
+ "channel_id": self.message.channel_id,
260
+ "guild_id": self.message.guild_id,
261
+ },
262
+ allowed_mentions=allowed_mentions,
263
+ **kwargs,
264
+ )
265
+
266
+ async def send(self, content: str, **kwargs: Any) -> "Message":
267
+ return await self.bot.send_message(
268
+ channel_id=self.message.channel_id, content=content, **kwargs
269
+ )
270
+
271
+ async def edit(
272
+ self,
273
+ message: Union[str, "Message"],
274
+ *,
275
+ content: Optional[str] = None,
276
+ **kwargs: Any,
277
+ ) -> "Message":
278
+ """Edits a message previously sent by the bot."""
279
+
280
+ message_id = message if isinstance(message, str) else message.id
281
+ return await self.bot.edit_message(
282
+ channel_id=self.message.channel_id,
283
+ message_id=message_id,
284
+ content=content,
285
+ **kwargs,
286
+ )
287
+
288
+ def typing(self) -> "Typing":
289
+ """Return a typing context manager for this context's channel."""
290
+
291
+ return self.bot.typing(self.message.channel_id)
292
+
293
+
294
+ class CommandHandler:
295
+ """
296
+ Manages command registration, parsing, and dispatching.
297
+ """
298
+
299
+ def __init__(
300
+ self,
301
+ client: "Client",
302
+ prefix: Union[
303
+ str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
304
+ ],
305
+ ):
306
+ self.client: "Client" = client
307
+ self.prefix: Union[
308
+ str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
309
+ ] = prefix
310
+ self.commands: Dict[str, Command] = {}
311
+ self.cogs: Dict[str, "Cog"] = {}
312
+ self._concurrency: Dict[str, Dict[str, int]] = {}
313
+ self._global_checks: List[
314
+ Callable[["CommandContext"], Awaitable[bool] | bool]
315
+ ] = []
316
+
317
+ from .help import HelpCommand
318
+
319
+ self.add_command(HelpCommand(self))
320
+
321
+ def add_check(
322
+ self, predicate: Callable[["CommandContext"], Awaitable[bool] | bool]
323
+ ) -> None:
324
+ """Adds a global check to the command handler."""
325
+ self._global_checks.append(predicate)
326
+
327
+ def add_command(self, command: Command) -> None:
328
+ if command.name in self.commands:
329
+ raise ValueError(f"Command '{command.name}' is already registered.")
330
+
331
+ self.commands[command.name.lower()] = command
332
+ for alias in command.aliases:
333
+ if alias in self.commands:
334
+ logger.warning(
335
+ "Alias '%s' for command '%s' conflicts with an existing command or alias.",
336
+ alias,
337
+ command.name,
338
+ )
339
+ self.commands[alias.lower()] = command
340
+
341
+ if isinstance(command, Group):
342
+ for sub_cmd in command.commands.values():
343
+ if sub_cmd.name in self.commands:
344
+ logger.warning(
345
+ "Subcommand '%s' of group '%s' conflicts with a top-level command.",
346
+ sub_cmd.name,
347
+ command.name,
348
+ )
349
+
350
+ def remove_command(self, name: str) -> Optional[Command]:
351
+ command = self.commands.pop(name.lower(), None)
352
+ if command:
353
+ for alias in command.aliases:
354
+ self.commands.pop(alias.lower(), None)
355
+ return command
356
+
357
+ def get_command(self, name: str) -> Optional[Command]:
358
+ return self.commands.get(name.lower())
359
+
360
+ def add_cog(self, cog_to_add: "Cog") -> None:
361
+ from .cog import Cog
362
+
363
+ if not isinstance(cog_to_add, Cog):
364
+ raise TypeError("Argument must be a subclass of Cog.")
365
+
366
+ if cog_to_add.cog_name in self.cogs:
367
+ raise ValueError(
368
+ f"Cog with name '{cog_to_add.cog_name}' is already registered."
369
+ )
370
+
371
+ self.cogs[cog_to_add.cog_name] = cog_to_add
372
+
373
+ for cmd in cog_to_add.get_commands():
374
+ self.add_command(cmd)
375
+
376
+ if hasattr(self.client, "_event_dispatcher"):
377
+ for event_name, callback in cog_to_add.get_listeners():
378
+ self.client._event_dispatcher.register(event_name.upper(), callback)
379
+ else:
380
+ logger.warning(
381
+ "Client does not have '_event_dispatcher'. Listeners for cog '%s' not registered.",
382
+ cog_to_add.cog_name,
383
+ )
384
+
385
+ if hasattr(cog_to_add, "cog_load") and inspect.iscoroutinefunction(
386
+ cog_to_add.cog_load
387
+ ):
388
+ asyncio.create_task(cog_to_add.cog_load())
389
+
390
+ logger.info("Cog '%s' added.", cog_to_add.cog_name)
391
+
392
+ def remove_cog(self, cog_name: str) -> Optional["Cog"]:
393
+ cog_to_remove = self.cogs.pop(cog_name, None)
394
+ if cog_to_remove:
395
+ for cmd in cog_to_remove.get_commands():
396
+ self.remove_command(cmd.name)
397
+
398
+ if hasattr(self.client, "_event_dispatcher"):
399
+ for event_name, callback in cog_to_remove.get_listeners():
400
+ logger.debug(
401
+ "Listener '%s' for event '%s' from cog '%s' needs manual unregistration logic in EventDispatcher.",
402
+ callback.__name__,
403
+ event_name,
404
+ cog_name,
405
+ )
406
+
407
+ if hasattr(cog_to_remove, "cog_unload") and inspect.iscoroutinefunction(
408
+ cog_to_remove.cog_unload
409
+ ):
410
+ asyncio.create_task(cog_to_remove.cog_unload())
411
+
412
+ cog_to_remove._eject()
413
+ logger.info("Cog '%s' removed.", cog_name)
414
+ return cog_to_remove
415
+
416
+ def _acquire_concurrency(self, ctx: CommandContext) -> None:
417
+ mc = getattr(ctx.command, "max_concurrency", None)
418
+ if not mc:
419
+ return
420
+ limit, scope = mc
421
+ if scope == "user":
422
+ key = ctx.author.id
423
+ elif scope == "guild":
424
+ key = ctx.message.guild_id or ctx.author.id
425
+ else:
426
+ key = "global"
427
+ buckets = self._concurrency.setdefault(ctx.command.name, {})
428
+ current = buckets.get(key, 0)
429
+ if current >= limit:
430
+ from .errors import MaxConcurrencyReached
431
+
432
+ raise MaxConcurrencyReached(limit)
433
+ buckets[key] = current + 1
434
+
435
+ def _release_concurrency(self, ctx: CommandContext) -> None:
436
+ mc = getattr(ctx.command, "max_concurrency", None)
437
+ if not mc:
438
+ return
439
+ _, scope = mc
440
+ if scope == "user":
441
+ key = ctx.author.id
442
+ elif scope == "guild":
443
+ key = ctx.message.guild_id or ctx.author.id
444
+ else:
445
+ key = "global"
446
+ buckets = self._concurrency.get(ctx.command.name)
447
+ if not buckets:
448
+ return
449
+ current = buckets.get(key, 0)
450
+ if current <= 1:
451
+ buckets.pop(key, None)
452
+ else:
453
+ buckets[key] = current - 1
454
+ if not buckets:
455
+ self._concurrency.pop(ctx.command.name, None)
456
+
457
+ async def get_prefix(self, message: "Message") -> Union[str, List[str], None]:
458
+ if callable(self.prefix):
459
+ if inspect.iscoroutinefunction(self.prefix):
460
+ return await self.prefix(self.client, message)
461
+ else:
462
+ return self.prefix(self.client, message) # type: ignore
463
+ return self.prefix
464
+
465
+ async def _parse_arguments(
466
+ self, command: Command, ctx: CommandContext, view: StringView
467
+ ) -> Tuple[List[Any], Dict[str, Any]]:
468
+ args_list = []
469
+ kwargs_dict = {}
470
+ params_to_parse = list(command.params.values())
471
+
472
+ if params_to_parse and params_to_parse[0].name == "self" and command.cog:
473
+ params_to_parse.pop(0)
474
+ if params_to_parse and params_to_parse[0].name == "ctx":
475
+ params_to_parse.pop(0)
476
+
477
+ for param in params_to_parse:
478
+ view.skip_whitespace()
479
+ final_value_for_param: Any = inspect.Parameter.empty
480
+
481
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
482
+ while not view.eof:
483
+ view.skip_whitespace()
484
+ if view.eof:
485
+ break
486
+ word = view.get_word()
487
+ if word or not view.eof:
488
+ args_list.append(word)
489
+ elif view.eof:
490
+ break
491
+ break
492
+
493
+ arg_str_value: Optional[str] = (
494
+ None # Holds the raw string for current param
495
+ )
496
+
497
+ if view.eof: # No more input string
498
+ if param.default is not inspect.Parameter.empty:
499
+ final_value_for_param = param.default
500
+ elif param.kind != inspect.Parameter.VAR_KEYWORD:
501
+ raise MissingRequiredArgument(param.name)
502
+ else: # VAR_KEYWORD at EOF is fine
503
+ break
504
+ else: # Input available
505
+ is_last_pos_str_greedy = (
506
+ param == params_to_parse[-1]
507
+ and param.annotation is str
508
+ and param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
509
+ )
510
+
511
+ if is_last_pos_str_greedy:
512
+ arg_str_value = view.read_rest().strip()
513
+ if (
514
+ not arg_str_value
515
+ and param.default is not inspect.Parameter.empty
516
+ ):
517
+ final_value_for_param = param.default
518
+ else: # Includes empty string if that's what's left
519
+ final_value_for_param = arg_str_value
520
+ else: # Not greedy, or not string, or not last positional
521
+ if view.buffer[view.index] == '"':
522
+ arg_str_value = view.get_quoted_string()
523
+ if arg_str_value == "" and view.buffer[view.index] == '"':
524
+ raise BadArgument(
525
+ f"Unterminated quoted string for argument '{param.name}'."
526
+ )
527
+ else:
528
+ arg_str_value = view.get_word()
529
+
530
+ # If final_value_for_param was not set by greedy logic, try conversion
531
+ if final_value_for_param is inspect.Parameter.empty:
532
+ if (
533
+ arg_str_value is None
534
+ ): # Should not happen if view.get_word/get_quoted_string is robust
535
+ if param.default is not inspect.Parameter.empty:
536
+ final_value_for_param = param.default
537
+ else:
538
+ raise MissingRequiredArgument(param.name)
539
+ else: # We have an arg_str_value (could be empty string "" from quotes)
540
+ annotation = param.annotation
541
+ origin = get_origin(annotation)
542
+
543
+ if origin is Union: # Handles Optional[T] and Union[T1, T2]
544
+ union_args = get_args(annotation)
545
+ is_optional = (
546
+ len(union_args) == 2 and type(None) in union_args
547
+ )
548
+
549
+ converted_for_union = False
550
+ last_err_union: Optional[BadArgument] = None
551
+ for t_arg in union_args:
552
+ if t_arg is type(None):
553
+ continue
554
+ try:
555
+ final_value_for_param = await run_converters(
556
+ ctx, t_arg, arg_str_value
557
+ )
558
+ converted_for_union = True
559
+ break
560
+ except BadArgument as e:
561
+ last_err_union = e
562
+
563
+ if not converted_for_union:
564
+ if (
565
+ is_optional and param.default is None
566
+ ): # Special handling for Optional[T] if conversion failed
567
+ # If arg_str_value was "" and type was Optional[str], StringConverter would return ""
568
+ # If arg_str_value was "" and type was Optional[int], BadArgument would be raised.
569
+ # This path is for when all actual types in Optional[T] fail conversion.
570
+ # If default is None, we can assign None.
571
+ final_value_for_param = None
572
+ elif last_err_union:
573
+ raise last_err_union
574
+ else: # Should not be reached if logic is correct
575
+ raise BadArgument(
576
+ f"Could not convert '{arg_str_value}' to any of {union_args} for param '{param.name}'."
577
+ )
578
+ elif annotation is inspect.Parameter.empty or annotation is str:
579
+ final_value_for_param = arg_str_value
580
+ else: # Standard type hint
581
+ final_value_for_param = await run_converters(
582
+ ctx, annotation, arg_str_value
583
+ )
584
+
585
+ # Final check if value was resolved
586
+ if final_value_for_param is inspect.Parameter.empty:
587
+ if param.default is not inspect.Parameter.empty:
588
+ final_value_for_param = param.default
589
+ elif param.kind != inspect.Parameter.VAR_KEYWORD:
590
+ # This state implies an issue if required and no default, and no input was parsed.
591
+ raise MissingRequiredArgument(
592
+ f"Parameter '{param.name}' could not be resolved."
593
+ )
594
+
595
+ # Assign to args_list or kwargs_dict if a value was determined
596
+ if final_value_for_param is not inspect.Parameter.empty:
597
+ if (
598
+ param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
599
+ or param.kind == inspect.Parameter.POSITIONAL_ONLY
600
+ ):
601
+ args_list.append(final_value_for_param)
602
+ elif param.kind == inspect.Parameter.KEYWORD_ONLY:
603
+ kwargs_dict[param.name] = final_value_for_param
604
+
605
+ return args_list, kwargs_dict
606
+
607
+ async def process_commands(self, message: "Message") -> None:
608
+ if not message.content:
609
+ return
610
+
611
+ prefix_to_use = await self.get_prefix(message)
612
+ if not prefix_to_use:
613
+ return
614
+
615
+ actual_prefix: Optional[str] = None
616
+ if isinstance(prefix_to_use, list):
617
+ for p in prefix_to_use:
618
+ if message.content.startswith(p):
619
+ actual_prefix = p
620
+ break
621
+ if not actual_prefix:
622
+ return
623
+ elif isinstance(prefix_to_use, str):
624
+ if message.content.startswith(prefix_to_use):
625
+ actual_prefix = prefix_to_use
626
+ else:
627
+ return
628
+ else:
629
+ return
630
+
631
+ if actual_prefix is None:
632
+ return
633
+
634
+ content_without_prefix = message.content[len(actual_prefix) :]
635
+ view = StringView(content_without_prefix)
636
+
637
+ command_name = view.get_word()
638
+ if not command_name:
639
+ return
640
+
641
+ command = self.get_command(command_name)
642
+ if not command:
643
+ return
644
+
645
+ invoked_with = command_name
646
+ original_command = command
647
+
648
+ if isinstance(command, Group):
649
+ view.skip_whitespace()
650
+ potential_subcommand = view.get_word()
651
+ if potential_subcommand:
652
+ subcommand = command.get_command(potential_subcommand)
653
+ if subcommand:
654
+ command = subcommand
655
+ invoked_with += f" {potential_subcommand}"
656
+ elif command.invoke_without_command:
657
+ view.index -= len(potential_subcommand) + view.previous
658
+ else:
659
+ raise CommandNotFound(f"Subcommand '{potential_subcommand}' not found.")
660
+
661
+ ctx = CommandContext(
662
+ message=message,
663
+ bot=self.client,
664
+ prefix=actual_prefix,
665
+ command=command,
666
+ invoked_with=invoked_with,
667
+ cog=command.cog,
668
+ )
669
+
670
+ try:
671
+ parsed_args, parsed_kwargs = await self._parse_arguments(command, ctx, view)
672
+ ctx.args = parsed_args
673
+ ctx.kwargs = parsed_kwargs
674
+ self._acquire_concurrency(ctx)
675
+ try:
676
+ await command.invoke(ctx, *parsed_args, **parsed_kwargs)
677
+ finally:
678
+ self._release_concurrency(ctx)
679
+ except CommandError as e:
680
+ logger.error("Command error for '%s': %s", original_command.name, e)
681
+ if hasattr(self.client, "on_command_error"):
682
+ await self.client.on_command_error(ctx, e)
683
+ except Exception as e:
684
+ logger.error("Unexpected error invoking command '%s': %s", original_command.name, e)
685
+ exc = CommandInvokeError(e)
686
+ if hasattr(self.client, "on_command_error"):
687
+ await self.client.on_command_error(ctx, exc)
688
+ else:
689
+ if hasattr(self.client, "on_command_completion"):
690
+ await self.client.on_command_completion(ctx)