ekonda / kutana

The library for developing systems for messengers and social networks
MIT License
72 stars 17 forks source link

Add the ability to trigger commands without a prefix #64

Closed daeeros closed 3 years ago

daeeros commented 3 years ago

It would be convenient to add the is_prefix = False parameter to the usual on_commands decorator, after which it would be triggered on commands with or without a prefix, instead of crutches with on_messages

use:

prefixes (".",)

@plugin.on_commands(["test"])

.test - work

test - not work

@plugin.on_commands(["test"], is_prefix=False)

.test - work

test - work

michaelkryukov commented 3 years ago

Достаточно элегантное решение без сложностей с on_messages:

from kutana import Plugin, t

plugin = Plugin(name=t("Optional prefix"), description=t(""))

@plugin.on_commands(["test"])
@plugin.on_match("^test$")
async def __(msg, ctx):
    await ctx.reply('works')

При желании, можно сделать свой декоратор:

import re
from kutana import Plugin, t

plugin = Plugin(name=t("Optional prefix"), description=t(""))

def on_commands_extended(commands, prefix_optional=False):
    def decorator(func):
        plugin.on_commands(commands)(func)

        if prefix_optional:
            for command in commands:
                plugin.on_match("^" + re.escape(command) + "$")(func)

    return decorator
plugin.on_commands_extended = on_commands_extended

@plugin.on_commands_extended(["test"], prefix_optional=True)
async def __(msg, ctx):
    await ctx.reply('works')

Если будет большой спрос - можно будет подумать о добавлении такого декоратора сразу в библиотеку. Пока можно нормально использовать on_match.