khl.py icon indicating copy to clipboard operation
khl.py copied to clipboard

The custom parser feature is completely broken

Open Yqloss opened this issue 1 year ago • 0 comments

Describe the bug The Parser.register method requires the parser passed in to be non-async and have only 1 parameter with str type. However, even if I passed in the correct type of parser, khl.command.exception.Exceptions.Parser.ParseFailed would still be raised.

Possible cause In this (khl/command/parser.py) file, the default parsers have 3 parameters like (Message, Client, str) -> Type. Both async and non-async functions are acceptable as well. The Parser.parse method calls the parsers like func(msg, client, token), which conflicts with the Parser.register requirements. The async check in Parser.register should be removed and the parameter check should be fixed.

To Reproduce

from khl.command import Parser

def parser_bool(token: str) -> bool:
    return bool(token)

class CustomParser(Parser):

    def __init__(self) -> None:
        super().__init__()
        self.register(parser_bool)

CUSTOM_PARSER: CustomParser = CustomParser()

And use the parser in @bot.command.

Expected behavior Either the function above can be accepted, or change the requirements so that I can pass such functions as these two in, whose parameter types are the same as those of default ones.

def parser_bool(message: Message, client: Client, token: str) -> bool:
    return bool(token)

async def parser_bool_async(message: Message, client: Client, token: str) -> bool:
    return bool(token)

Logs/Screenshots Registration failures:

  File "D:\Program Files\Python\3.10.7\lib\site-packages\khl\command\parser.py", line 114, in register
    raise TypeError('parse function should not be async')
TypeError: parse function should not be async
  File "D:\Program Files\Python\3.10.7\lib\site-packages\khl\command\parser.py", line 116, in register
    raise TypeError('parse function should own only one param, and the param type is str')
TypeError: parse function should own only one param, and the param type is str

Parse failures (successfully registered (str) -> Type functions):

Traceback (most recent call last):
  File "D:\Program Files\Python\3.10.7\lib\site-packages\khl\command\command.py", line 139, in handle
    parsed_args = await self.parser.parse(msg, client, self.lexer.lex(msg), to_be_parsed)
  File "D:\Program Files\Python\3.10.7\lib\site-packages\khl\command\parser.py", line 98, in parse
    raise Exceptions.Parser.ParseFailed(param, token, func, e)
khl.command.exception.Exceptions.Parser.ParseFailed

Environment

  • Python version: 3.10.7
  • khl.py version: 0.3.13
  • OS: Windows 11 Home

Additional context

Yqloss avatar Jun 21 '24 17:06 Yqloss