From 57919e65069e62fc31666adebd6c107be067b724 Mon Sep 17 00:00:00 2001 From: timotheyca Date: Mon, 20 Dec 2021 19:12:56 +0300 Subject: [PATCH] bot utils --- v6d2ctx/handle_args.py | 18 ++++++++++++++++++ v6d2ctx/handle_command.py | 5 +++++ v6d2ctx/handle_content.py | 15 +++++++++++++++ v6d2ctx/lock_for.py | 15 +++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 v6d2ctx/handle_args.py create mode 100644 v6d2ctx/handle_command.py create mode 100644 v6d2ctx/handle_content.py create mode 100644 v6d2ctx/lock_for.py 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())