disagreement 0.0.1__py3-none-any.whl → 0.0.2__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.
@@ -0,0 +1,490 @@
1
+ # disagreement/ext/commands/core.py
2
+
3
+ import asyncio
4
+ import inspect
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Optional,
8
+ List,
9
+ Dict,
10
+ Any,
11
+ Union,
12
+ Callable,
13
+ Awaitable,
14
+ Tuple,
15
+ get_origin,
16
+ get_args,
17
+ )
18
+
19
+ from .view import StringView
20
+ from .errors import (
21
+ CommandError,
22
+ CommandNotFound,
23
+ BadArgument,
24
+ MissingRequiredArgument,
25
+ ArgumentParsingError,
26
+ CheckFailure,
27
+ CommandInvokeError,
28
+ )
29
+ from .converters import run_converters, DEFAULT_CONVERTERS, Converter
30
+ from .cog import Cog
31
+ from disagreement.typing import Typing
32
+
33
+ if TYPE_CHECKING:
34
+ from disagreement.client import Client
35
+ from disagreement.models import Message, User
36
+
37
+
38
+ class Command:
39
+ """
40
+ Represents a bot command.
41
+
42
+ Attributes:
43
+ name (str): The primary name of the command.
44
+ callback (Callable[..., Awaitable[None]]): The coroutine function to execute.
45
+ aliases (List[str]): Alternative names for the command.
46
+ brief (Optional[str]): A short description for help commands.
47
+ description (Optional[str]): A longer description for help commands.
48
+ cog (Optional['Cog']): Reference to the Cog this command belongs to.
49
+ params (Dict[str, inspect.Parameter]): Cached parameters of the callback.
50
+ """
51
+
52
+ def __init__(self, callback: Callable[..., Awaitable[None]], **attrs: Any):
53
+ if not asyncio.iscoroutinefunction(callback):
54
+ raise TypeError("Command callback must be a coroutine function.")
55
+
56
+ self.callback: Callable[..., Awaitable[None]] = callback
57
+ self.name: str = attrs.get("name", callback.__name__)
58
+ self.aliases: List[str] = attrs.get("aliases", [])
59
+ self.brief: Optional[str] = attrs.get("brief")
60
+ self.description: Optional[str] = attrs.get("description") or callback.__doc__
61
+ self.cog: Optional["Cog"] = attrs.get("cog")
62
+
63
+ self.params = inspect.signature(callback).parameters
64
+ self.checks: List[Callable[["CommandContext"], Awaitable[bool] | bool]] = []
65
+ if hasattr(callback, "__command_checks__"):
66
+ self.checks.extend(getattr(callback, "__command_checks__"))
67
+
68
+ def add_check(
69
+ self, predicate: Callable[["CommandContext"], Awaitable[bool] | bool]
70
+ ) -> None:
71
+ self.checks.append(predicate)
72
+
73
+ async def invoke(self, ctx: "CommandContext", *args: Any, **kwargs: Any) -> None:
74
+ from .errors import CheckFailure
75
+
76
+ for predicate in self.checks:
77
+ result = predicate(ctx)
78
+ if inspect.isawaitable(result):
79
+ result = await result
80
+ if not result:
81
+ raise CheckFailure("Check predicate failed.")
82
+
83
+ if self.cog:
84
+ await self.callback(self.cog, ctx, *args, **kwargs)
85
+ else:
86
+ await self.callback(ctx, *args, **kwargs)
87
+
88
+
89
+ class CommandContext:
90
+ """
91
+ Represents the context in which a command is being invoked.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ *,
97
+ message: "Message",
98
+ bot: "Client",
99
+ prefix: str,
100
+ command: "Command",
101
+ invoked_with: str,
102
+ args: Optional[List[Any]] = None,
103
+ kwargs: Optional[Dict[str, Any]] = None,
104
+ cog: Optional["Cog"] = None,
105
+ ):
106
+ self.message: "Message" = message
107
+ self.bot: "Client" = bot
108
+ self.prefix: str = prefix
109
+ self.command: "Command" = command
110
+ self.invoked_with: str = invoked_with
111
+ self.args: List[Any] = args or []
112
+ self.kwargs: Dict[str, Any] = kwargs or {}
113
+ self.cog: Optional["Cog"] = cog
114
+
115
+ self.author: "User" = message.author
116
+
117
+ async def reply(
118
+ self,
119
+ content: str,
120
+ *,
121
+ mention_author: Optional[bool] = None,
122
+ **kwargs: Any,
123
+ ) -> "Message":
124
+ """Replies to the invoking message.
125
+
126
+ Parameters
127
+ ----------
128
+ content: str
129
+ The content to send.
130
+ mention_author: Optional[bool]
131
+ Whether to mention the author in the reply. If ``None`` the
132
+ client's :attr:`mention_replies` value is used.
133
+ """
134
+
135
+ allowed_mentions = kwargs.pop("allowed_mentions", None)
136
+ if mention_author is None:
137
+ mention_author = getattr(self.bot, "mention_replies", False)
138
+
139
+ if allowed_mentions is None:
140
+ allowed_mentions = {"replied_user": mention_author}
141
+ else:
142
+ allowed_mentions = dict(allowed_mentions)
143
+ allowed_mentions.setdefault("replied_user", mention_author)
144
+
145
+ return await self.bot.send_message(
146
+ channel_id=self.message.channel_id,
147
+ content=content,
148
+ message_reference={
149
+ "message_id": self.message.id,
150
+ "channel_id": self.message.channel_id,
151
+ "guild_id": self.message.guild_id,
152
+ },
153
+ allowed_mentions=allowed_mentions,
154
+ **kwargs,
155
+ )
156
+
157
+ async def send(self, content: str, **kwargs: Any) -> "Message":
158
+ return await self.bot.send_message(
159
+ channel_id=self.message.channel_id, content=content, **kwargs
160
+ )
161
+
162
+ async def edit(
163
+ self,
164
+ message: Union[str, "Message"],
165
+ *,
166
+ content: Optional[str] = None,
167
+ **kwargs: Any,
168
+ ) -> "Message":
169
+ """Edits a message previously sent by the bot."""
170
+
171
+ message_id = message if isinstance(message, str) else message.id
172
+ return await self.bot.edit_message(
173
+ channel_id=self.message.channel_id,
174
+ message_id=message_id,
175
+ content=content,
176
+ **kwargs,
177
+ )
178
+
179
+ def typing(self) -> "Typing":
180
+ """Return a typing context manager for this context's channel."""
181
+
182
+ return self.bot.typing(self.message.channel_id)
183
+
184
+
185
+ class CommandHandler:
186
+ """
187
+ Manages command registration, parsing, and dispatching.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ client: "Client",
193
+ prefix: Union[
194
+ str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
195
+ ],
196
+ ):
197
+ self.client: "Client" = client
198
+ self.prefix: Union[
199
+ str, List[str], Callable[["Client", "Message"], Union[str, List[str]]]
200
+ ] = prefix
201
+ self.commands: Dict[str, Command] = {}
202
+ self.cogs: Dict[str, "Cog"] = {}
203
+
204
+ from .help import HelpCommand
205
+
206
+ self.add_command(HelpCommand(self))
207
+
208
+ def add_command(self, command: Command) -> None:
209
+ if command.name in self.commands:
210
+ raise ValueError(f"Command '{command.name}' is already registered.")
211
+
212
+ self.commands[command.name.lower()] = command
213
+ for alias in command.aliases:
214
+ if alias in self.commands:
215
+ print(
216
+ f"Warning: Alias '{alias}' for command '{command.name}' conflicts with an existing command or alias."
217
+ )
218
+ self.commands[alias.lower()] = command
219
+
220
+ def remove_command(self, name: str) -> Optional[Command]:
221
+ command = self.commands.pop(name.lower(), None)
222
+ if command:
223
+ for alias in command.aliases:
224
+ self.commands.pop(alias.lower(), None)
225
+ return command
226
+
227
+ def get_command(self, name: str) -> Optional[Command]:
228
+ return self.commands.get(name.lower())
229
+
230
+ def add_cog(self, cog_to_add: "Cog") -> None:
231
+ if not isinstance(cog_to_add, Cog):
232
+ raise TypeError("Argument must be a subclass of Cog.")
233
+
234
+ if cog_to_add.cog_name in self.cogs:
235
+ raise ValueError(
236
+ f"Cog with name '{cog_to_add.cog_name}' is already registered."
237
+ )
238
+
239
+ self.cogs[cog_to_add.cog_name] = cog_to_add
240
+
241
+ for cmd in cog_to_add.get_commands():
242
+ self.add_command(cmd)
243
+
244
+ if hasattr(self.client, "_event_dispatcher"):
245
+ for event_name, callback in cog_to_add.get_listeners():
246
+ self.client._event_dispatcher.register(event_name.upper(), callback)
247
+ else:
248
+ print(
249
+ f"Warning: Client does not have '_event_dispatcher'. Listeners for cog '{cog_to_add.cog_name}' not registered."
250
+ )
251
+
252
+ if hasattr(cog_to_add, "cog_load") and inspect.iscoroutinefunction(
253
+ cog_to_add.cog_load
254
+ ):
255
+ asyncio.create_task(cog_to_add.cog_load())
256
+
257
+ print(f"Cog '{cog_to_add.cog_name}' added.")
258
+
259
+ def remove_cog(self, cog_name: str) -> Optional["Cog"]:
260
+ cog_to_remove = self.cogs.pop(cog_name, None)
261
+ if cog_to_remove:
262
+ for cmd in cog_to_remove.get_commands():
263
+ self.remove_command(cmd.name)
264
+
265
+ if hasattr(self.client, "_event_dispatcher"):
266
+ for event_name, callback in cog_to_remove.get_listeners():
267
+ print(
268
+ f"Note: Listener '{callback.__name__}' for event '{event_name}' from cog '{cog_name}' needs manual unregistration logic in EventDispatcher."
269
+ )
270
+
271
+ if hasattr(cog_to_remove, "cog_unload") and inspect.iscoroutinefunction(
272
+ cog_to_remove.cog_unload
273
+ ):
274
+ asyncio.create_task(cog_to_remove.cog_unload())
275
+
276
+ cog_to_remove._eject()
277
+ print(f"Cog '{cog_name}' removed.")
278
+ return cog_to_remove
279
+
280
+ async def get_prefix(self, message: "Message") -> Union[str, List[str], None]:
281
+ if callable(self.prefix):
282
+ if inspect.iscoroutinefunction(self.prefix):
283
+ return await self.prefix(self.client, message)
284
+ else:
285
+ return self.prefix(self.client, message) # type: ignore
286
+ return self.prefix
287
+
288
+ async def _parse_arguments(
289
+ self, command: Command, ctx: CommandContext, view: StringView
290
+ ) -> Tuple[List[Any], Dict[str, Any]]:
291
+ args_list = []
292
+ kwargs_dict = {}
293
+ params_to_parse = list(command.params.values())
294
+
295
+ if params_to_parse and params_to_parse[0].name == "self" and command.cog:
296
+ params_to_parse.pop(0)
297
+ if params_to_parse and params_to_parse[0].name == "ctx":
298
+ params_to_parse.pop(0)
299
+
300
+ for param in params_to_parse:
301
+ view.skip_whitespace()
302
+ final_value_for_param: Any = inspect.Parameter.empty
303
+
304
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
305
+ while not view.eof:
306
+ view.skip_whitespace()
307
+ if view.eof:
308
+ break
309
+ word = view.get_word()
310
+ if word or not view.eof:
311
+ args_list.append(word)
312
+ elif view.eof:
313
+ break
314
+ break
315
+
316
+ arg_str_value: Optional[str] = (
317
+ None # Holds the raw string for current param
318
+ )
319
+
320
+ if view.eof: # No more input string
321
+ if param.default is not inspect.Parameter.empty:
322
+ final_value_for_param = param.default
323
+ elif param.kind != inspect.Parameter.VAR_KEYWORD:
324
+ raise MissingRequiredArgument(param.name)
325
+ else: # VAR_KEYWORD at EOF is fine
326
+ break
327
+ else: # Input available
328
+ is_last_pos_str_greedy = (
329
+ param == params_to_parse[-1]
330
+ and param.annotation is str
331
+ and param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
332
+ )
333
+
334
+ if is_last_pos_str_greedy:
335
+ arg_str_value = view.read_rest().strip()
336
+ if (
337
+ not arg_str_value
338
+ and param.default is not inspect.Parameter.empty
339
+ ):
340
+ final_value_for_param = param.default
341
+ else: # Includes empty string if that's what's left
342
+ final_value_for_param = arg_str_value
343
+ else: # Not greedy, or not string, or not last positional
344
+ if view.buffer[view.index] == '"':
345
+ arg_str_value = view.get_quoted_string()
346
+ if arg_str_value == "" and view.buffer[view.index] == '"':
347
+ raise BadArgument(
348
+ f"Unterminated quoted string for argument '{param.name}'."
349
+ )
350
+ else:
351
+ arg_str_value = view.get_word()
352
+
353
+ # If final_value_for_param was not set by greedy logic, try conversion
354
+ if final_value_for_param is inspect.Parameter.empty:
355
+ if (
356
+ arg_str_value is None
357
+ ): # Should not happen if view.get_word/get_quoted_string is robust
358
+ if param.default is not inspect.Parameter.empty:
359
+ final_value_for_param = param.default
360
+ else:
361
+ raise MissingRequiredArgument(param.name)
362
+ else: # We have an arg_str_value (could be empty string "" from quotes)
363
+ annotation = param.annotation
364
+ origin = get_origin(annotation)
365
+
366
+ if origin is Union: # Handles Optional[T] and Union[T1, T2]
367
+ union_args = get_args(annotation)
368
+ is_optional = (
369
+ len(union_args) == 2 and type(None) in union_args
370
+ )
371
+
372
+ converted_for_union = False
373
+ last_err_union: Optional[BadArgument] = None
374
+ for t_arg in union_args:
375
+ if t_arg is type(None):
376
+ continue
377
+ try:
378
+ final_value_for_param = await run_converters(
379
+ ctx, t_arg, arg_str_value
380
+ )
381
+ converted_for_union = True
382
+ break
383
+ except BadArgument as e:
384
+ last_err_union = e
385
+
386
+ if not converted_for_union:
387
+ if (
388
+ is_optional and param.default is None
389
+ ): # Special handling for Optional[T] if conversion failed
390
+ # If arg_str_value was "" and type was Optional[str], StringConverter would return ""
391
+ # If arg_str_value was "" and type was Optional[int], BadArgument would be raised.
392
+ # This path is for when all actual types in Optional[T] fail conversion.
393
+ # If default is None, we can assign None.
394
+ final_value_for_param = None
395
+ elif last_err_union:
396
+ raise last_err_union
397
+ else: # Should not be reached if logic is correct
398
+ raise BadArgument(
399
+ f"Could not convert '{arg_str_value}' to any of {union_args} for param '{param.name}'."
400
+ )
401
+ elif annotation is inspect.Parameter.empty or annotation is str:
402
+ final_value_for_param = arg_str_value
403
+ else: # Standard type hint
404
+ final_value_for_param = await run_converters(
405
+ ctx, annotation, arg_str_value
406
+ )
407
+
408
+ # Final check if value was resolved
409
+ if final_value_for_param is inspect.Parameter.empty:
410
+ if param.default is not inspect.Parameter.empty:
411
+ final_value_for_param = param.default
412
+ elif param.kind != inspect.Parameter.VAR_KEYWORD:
413
+ # This state implies an issue if required and no default, and no input was parsed.
414
+ raise MissingRequiredArgument(
415
+ f"Parameter '{param.name}' could not be resolved."
416
+ )
417
+
418
+ # Assign to args_list or kwargs_dict if a value was determined
419
+ if final_value_for_param is not inspect.Parameter.empty:
420
+ if (
421
+ param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
422
+ or param.kind == inspect.Parameter.POSITIONAL_ONLY
423
+ ):
424
+ args_list.append(final_value_for_param)
425
+ elif param.kind == inspect.Parameter.KEYWORD_ONLY:
426
+ kwargs_dict[param.name] = final_value_for_param
427
+
428
+ return args_list, kwargs_dict
429
+
430
+ async def process_commands(self, message: "Message") -> None:
431
+ if not message.content:
432
+ return
433
+
434
+ prefix_to_use = await self.get_prefix(message)
435
+ if not prefix_to_use:
436
+ return
437
+
438
+ actual_prefix: Optional[str] = None
439
+ if isinstance(prefix_to_use, list):
440
+ for p in prefix_to_use:
441
+ if message.content.startswith(p):
442
+ actual_prefix = p
443
+ break
444
+ if not actual_prefix:
445
+ return
446
+ elif isinstance(prefix_to_use, str):
447
+ if message.content.startswith(prefix_to_use):
448
+ actual_prefix = prefix_to_use
449
+ else:
450
+ return
451
+ else:
452
+ return
453
+
454
+ if actual_prefix is None:
455
+ return
456
+
457
+ content_without_prefix = message.content[len(actual_prefix) :]
458
+ view = StringView(content_without_prefix)
459
+
460
+ command_name = view.get_word()
461
+ if not command_name:
462
+ return
463
+
464
+ command = self.get_command(command_name)
465
+ if not command:
466
+ return
467
+
468
+ ctx = CommandContext(
469
+ message=message,
470
+ bot=self.client,
471
+ prefix=actual_prefix,
472
+ command=command,
473
+ invoked_with=command_name,
474
+ cog=command.cog,
475
+ )
476
+
477
+ try:
478
+ parsed_args, parsed_kwargs = await self._parse_arguments(command, ctx, view)
479
+ ctx.args = parsed_args
480
+ ctx.kwargs = parsed_kwargs
481
+ await command.invoke(ctx, *parsed_args, **parsed_kwargs)
482
+ except CommandError as e:
483
+ print(f"Command error for '{command.name}': {e}")
484
+ if hasattr(self.client, "on_command_error"):
485
+ await self.client.on_command_error(ctx, e)
486
+ except Exception as e:
487
+ print(f"Unexpected error invoking command '{command.name}': {e}")
488
+ exc = CommandInvokeError(e)
489
+ if hasattr(self.client, "on_command_error"):
490
+ await self.client.on_command_error(ctx, exc)
@@ -0,0 +1,150 @@
1
+ # disagreement/ext/commands/decorators.py
2
+
3
+ import asyncio
4
+ import inspect
5
+ import time
6
+ from typing import Callable, Any, Optional, List, TYPE_CHECKING, Awaitable
7
+
8
+ if TYPE_CHECKING:
9
+ from .core import Command, CommandContext # For type hinting return or internal use
10
+
11
+ # from .cog import Cog # For Cog specific decorators
12
+
13
+
14
+ def command(
15
+ name: Optional[str] = None, aliases: Optional[List[str]] = None, **attrs: Any
16
+ ) -> Callable:
17
+ """
18
+ A decorator that transforms a function into a Command.
19
+
20
+ Args:
21
+ name (Optional[str]): The name of the command. Defaults to the function name.
22
+ aliases (Optional[List[str]]): Alternative names for the command.
23
+ **attrs: Additional attributes to pass to the Command constructor
24
+ (e.g., brief, description, hidden).
25
+
26
+ Returns:
27
+ Callable: A decorator that registers the command.
28
+ """
29
+
30
+ def decorator(
31
+ func: Callable[..., Awaitable[None]],
32
+ ) -> Callable[..., Awaitable[None]]:
33
+ if not asyncio.iscoroutinefunction(func):
34
+ raise TypeError("Command callback must be a coroutine function.")
35
+
36
+ from .core import (
37
+ Command,
38
+ ) # Late import to avoid circular dependencies at module load time
39
+
40
+ # The actual registration will happen when a Cog is added or if commands are global.
41
+ # For now, this decorator creates a Command instance and attaches it to the function,
42
+ # or returns a Command instance that can be collected.
43
+
44
+ cmd_name = name or func.__name__
45
+
46
+ # Store command attributes on the function itself for later collection by Cog or Client
47
+ # This is a common pattern.
48
+ if hasattr(func, "__command_attrs__"):
49
+ # This case might occur if decorators are stacked in an unusual way,
50
+ # or if a function is decorated multiple times (which should be disallowed or handled).
51
+ # For now, let's assume one @command decorator per function.
52
+ raise TypeError("Function is already a command or has command attributes.")
53
+
54
+ # Create the command object. It will be registered by the Cog or Client.
55
+ cmd = Command(callback=func, name=cmd_name, aliases=aliases or [], **attrs)
56
+
57
+ # We can attach the command object to the function, so Cogs can find it.
58
+ func.__command_object__ = cmd # type: ignore # type: ignore[attr-defined]
59
+ return func # Return the original function, now marked.
60
+ # Or return `cmd` if commands are registered globally immediately.
61
+ # For Cogs, returning `func` and letting Cog collect is cleaner.
62
+
63
+ return decorator
64
+
65
+
66
+ def listener(
67
+ name: Optional[str] = None,
68
+ ) -> Callable[[Callable[..., Awaitable[None]]], Callable[..., Awaitable[None]]]:
69
+ """
70
+ A decorator that marks a function as an event listener within a Cog.
71
+ The actual registration happens when the Cog is added to the client.
72
+
73
+ Args:
74
+ name (Optional[str]): The name of the event to listen to.
75
+ Defaults to the function name (e.g., `on_message`).
76
+ """
77
+
78
+ def decorator(
79
+ func: Callable[..., Awaitable[None]],
80
+ ) -> Callable[..., Awaitable[None]]:
81
+ if not asyncio.iscoroutinefunction(func):
82
+ raise TypeError("Listener callback must be a coroutine function.")
83
+
84
+ # 'name' here is from the outer 'listener' scope (closure)
85
+ actual_event_name = name or func.__name__
86
+ # Store listener info on the function for Cog to collect
87
+ setattr(func, "__listener_name__", actual_event_name)
88
+ return func
89
+
90
+ return decorator # This must be correctly indented under 'listener'
91
+
92
+
93
+ def check(
94
+ predicate: Callable[["CommandContext"], Awaitable[bool] | bool],
95
+ ) -> Callable[[Callable[..., Awaitable[None]]], Callable[..., Awaitable[None]]]:
96
+ """Decorator to add a check to a command."""
97
+
98
+ def decorator(
99
+ func: Callable[..., Awaitable[None]],
100
+ ) -> Callable[..., Awaitable[None]]:
101
+ checks = getattr(func, "__command_checks__", [])
102
+ checks.append(predicate)
103
+ setattr(func, "__command_checks__", checks)
104
+ return func
105
+
106
+ return decorator
107
+
108
+
109
+ def check_any(
110
+ *predicates: Callable[["CommandContext"], Awaitable[bool] | bool]
111
+ ) -> Callable[[Callable[..., Awaitable[None]]], Callable[..., Awaitable[None]]]:
112
+ """Decorator that passes if any predicate returns ``True``."""
113
+
114
+ async def predicate(ctx: "CommandContext") -> bool:
115
+ from .errors import CheckAnyFailure, CheckFailure
116
+
117
+ errors = []
118
+ for p in predicates:
119
+ try:
120
+ result = p(ctx)
121
+ if inspect.isawaitable(result):
122
+ result = await result
123
+ if result:
124
+ return True
125
+ except CheckFailure as e:
126
+ errors.append(e)
127
+ raise CheckAnyFailure(errors)
128
+
129
+ return check(predicate)
130
+
131
+
132
+ def cooldown(
133
+ rate: int, per: float
134
+ ) -> Callable[[Callable[..., Awaitable[None]]], Callable[..., Awaitable[None]]]:
135
+ """Simple per-user cooldown decorator."""
136
+
137
+ buckets: dict[str, dict[str, float]] = {}
138
+
139
+ async def predicate(ctx: "CommandContext") -> bool:
140
+ from .errors import CommandOnCooldown
141
+
142
+ now = time.monotonic()
143
+ user_buckets = buckets.setdefault(ctx.command.name, {})
144
+ reset = user_buckets.get(ctx.author.id, 0)
145
+ if now < reset:
146
+ raise CommandOnCooldown(reset - now)
147
+ user_buckets[ctx.author.id] = now + per
148
+ return True
149
+
150
+ return check(predicate)