diff --git a/v6d2ctx/handle_args.py b/v6d2ctx/handle_args.py new file mode 100644 index 0000000..e9caf55 --- /dev/null +++ b/v6d2ctx/handle_args.py @@ -0,0 +1,18 @@ +import discord + +from v6d2ctx.context import Context, Implicit, Explicit +from v6d2ctx.handle_command import handle_command + + +async def handle_args(message: discord.Message, args: list[str]): + match args: + case []: + return + case [command_name, *command_args]: + ctx = Context(message) + try: + await handle_command(ctx, command_name, command_args) + except Implicit: + pass + except Explicit as e: + await ctx.reply(e.msg) diff --git a/v6d2ctx/handle_command.py b/v6d2ctx/handle_command.py new file mode 100644 index 0000000..21263ed --- /dev/null +++ b/v6d2ctx/handle_command.py @@ -0,0 +1,5 @@ +from v6d2ctx.context import Context, of + + +async def handle_command(ctx: Context, name: str, args: list[str]) -> None: + await of('commands', name)(ctx, args) diff --git a/v6d2ctx/handle_content.py b/v6d2ctx/handle_content.py new file mode 100644 index 0000000..abf48e7 --- /dev/null +++ b/v6d2ctx/handle_content.py @@ -0,0 +1,15 @@ +import shlex + +import discord + +from v6d2ctx.handle_args import handle_args + + +async def handle_content(message: discord.Message, content: str, prefix: str): + if message.author.bot: + return + if not content.startswith(prefix): + return + content = content.removeprefix(prefix) + args = shlex.split(content) + await handle_args(message, args) diff --git a/v6d2ctx/lock_for.py b/v6d2ctx/lock_for.py new file mode 100644 index 0000000..6c6edaf --- /dev/null +++ b/v6d2ctx/lock_for.py @@ -0,0 +1,15 @@ +import asyncio +from typing import Hashable + +from v6d2ctx.context import Explicit + +locks: dict[Hashable, asyncio.Lock] = {} + + +def lock_for(key: Hashable, error_message: str) -> asyncio.Lock: + if key is None: + raise Explicit(error_message) + if key in locks: + return locks[key] + else: + return locks.setdefault(key, asyncio.Lock())