Add get_context parsing for commands (#91)
This commit is contained in:
parent
c1c5cfb41a
commit
095e7e7192
@ -602,6 +602,11 @@ class Client:
|
||||
return
|
||||
await self.command_handler.process_commands(message)
|
||||
|
||||
async def get_context(self, message: "Message") -> Optional["CommandContext"]:
|
||||
"""Return a :class:`CommandContext` for ``message`` without executing the command."""
|
||||
|
||||
return await self.command_handler.get_context(message)
|
||||
|
||||
# --- Command Framework Methods ---
|
||||
|
||||
def add_cog(self, cog: Cog) -> None:
|
||||
|
@ -638,6 +638,78 @@ class CommandHandler:
|
||||
|
||||
return args_list, kwargs_dict
|
||||
|
||||
async def get_context(self, message: "Message") -> Optional[CommandContext]:
|
||||
"""Parse a message and return a :class:`CommandContext` without executing the command.
|
||||
|
||||
Returns ``None`` if the message does not invoke a command."""
|
||||
|
||||
if not message.content:
|
||||
return None
|
||||
|
||||
prefix_to_use = await self.get_prefix(message)
|
||||
if not prefix_to_use:
|
||||
return None
|
||||
|
||||
actual_prefix: Optional[str] = None
|
||||
if isinstance(prefix_to_use, list):
|
||||
for p in prefix_to_use:
|
||||
if message.content.startswith(p):
|
||||
actual_prefix = p
|
||||
break
|
||||
if not actual_prefix:
|
||||
return None
|
||||
elif isinstance(prefix_to_use, str):
|
||||
if message.content.startswith(prefix_to_use):
|
||||
actual_prefix = prefix_to_use
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
|
||||
if actual_prefix is None:
|
||||
return None
|
||||
|
||||
view = StringView(message.content[len(actual_prefix) :])
|
||||
|
||||
command_name = view.get_word()
|
||||
if not command_name:
|
||||
return None
|
||||
|
||||
command = self.get_command(command_name)
|
||||
if not command:
|
||||
return None
|
||||
|
||||
invoked_with = command_name
|
||||
|
||||
if isinstance(command, Group):
|
||||
view.skip_whitespace()
|
||||
potential_subcommand = view.get_word()
|
||||
if potential_subcommand:
|
||||
subcommand = command.get_command(potential_subcommand)
|
||||
if subcommand:
|
||||
command = subcommand
|
||||
invoked_with += f" {potential_subcommand}"
|
||||
elif command.invoke_without_command:
|
||||
view.index -= len(potential_subcommand) + view.previous
|
||||
else:
|
||||
raise CommandNotFound(
|
||||
f"Subcommand '{potential_subcommand}' not found."
|
||||
)
|
||||
|
||||
ctx = CommandContext(
|
||||
message=message,
|
||||
bot=self.client,
|
||||
prefix=actual_prefix,
|
||||
command=command,
|
||||
invoked_with=invoked_with,
|
||||
cog=command.cog,
|
||||
)
|
||||
|
||||
parsed_args, parsed_kwargs = await self._parse_arguments(command, ctx, view)
|
||||
ctx.args = parsed_args
|
||||
ctx.kwargs = parsed_kwargs
|
||||
return ctx
|
||||
|
||||
async def process_commands(self, message: "Message") -> None:
|
||||
if not message.content:
|
||||
return
|
||||
|
@ -1,7 +1,10 @@
|
||||
import asyncio
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
# pylint: disable=no-member
|
||||
|
||||
from disagreement.client import Client
|
||||
|
||||
|
||||
|
59
tests/test_get_context.py
Normal file
59
tests/test_get_context.py
Normal file
@ -0,0 +1,59 @@
|
||||
import pytest
|
||||
|
||||
from disagreement.client import Client
|
||||
from disagreement.ext.commands.core import Command, CommandHandler
|
||||
from disagreement.models import Message
|
||||
|
||||
|
||||
class DummyBot:
|
||||
def __init__(self):
|
||||
self.executed = False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_context_parses_without_execution():
|
||||
bot = DummyBot()
|
||||
handler = CommandHandler(client=bot, prefix="!")
|
||||
|
||||
async def foo(ctx, number: int, word: str):
|
||||
bot.executed = True
|
||||
|
||||
handler.add_command(Command(foo, name="foo"))
|
||||
|
||||
msg_data = {
|
||||
"id": "1",
|
||||
"channel_id": "c",
|
||||
"author": {"id": "2", "username": "u", "discriminator": "0001"},
|
||||
"content": "!foo 1 bar",
|
||||
"timestamp": "t",
|
||||
}
|
||||
msg = Message(msg_data, client_instance=bot)
|
||||
|
||||
ctx = await handler.get_context(msg)
|
||||
assert ctx is not None
|
||||
assert ctx.command.name == "foo"
|
||||
assert ctx.args == [1, "bar"]
|
||||
assert bot.executed is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_get_context():
|
||||
client = Client(token="t")
|
||||
|
||||
async def foo(ctx):
|
||||
raise RuntimeError("should not run")
|
||||
|
||||
client.command_handler.add_command(Command(foo, name="foo"))
|
||||
|
||||
msg_data = {
|
||||
"id": "1",
|
||||
"channel_id": "c",
|
||||
"author": {"id": "2", "username": "u", "discriminator": "0001"},
|
||||
"content": "!foo",
|
||||
"timestamp": "t",
|
||||
}
|
||||
msg = Message(msg_data, client_instance=client)
|
||||
|
||||
ctx = await client.get_context(msg)
|
||||
assert ctx is not None
|
||||
assert ctx.command.name == "foo"
|
Loading…
x
Reference in New Issue
Block a user