【问题标题】:Discord.py Create a check decorator for number of argumentsDiscord.py 为参数数量创建一个检查装饰器
【发布时间】:2021-11-16 11:05:48
【问题描述】:

在 discord.py 1.7.3 上,当我想确保命令在给定参数时出错时,我会这样做:

    @commands.command(name='hi')
    @commands.is_owner()
    async def hi(self, ctx, *, arg=None):
        if arg:
            raise commands.TooManyArguments
        else:
            await ctx.send(f'hi')

我想创建一个在文档中描述的检查装饰器,让它更优雅一点:https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#checks

所以我做到了:

def has_args():
    def predicate(ctx):
        print(ctx.args, ctx.kwargs)
        if len(ctx.args) > 2 or kwargs:
            raise commands.TooManyArguments
        return True
    return commands.check(predicate)
    ...
    @commands.command(name='hi')
    @commands.is_owner()
    @has_args()
    async def hi(self, ctx, *, arg=None):
        await ctx.send(f'hi')

但 ctx.args 和 ctx.kwargs 始终为空,无论我传递给命令的参数数量如何(又名 {prefix}hi 1 2 3 产生与 {prefix}hi 相同的打印)

有没有更好的方法来做到这一点?我错过了什么?

【问题讨论】:

    标签: python discord.py python-decorators


    【解决方案1】:

    使用@commands.command(name='hi') 时,您可以传递ignore_extra,因此它会引发TooManyArguments 错误。 例子: @commands.command(name='hi', ignore_extra=False)
    如果您想使用装饰器,这在我的初始测试中确实有效(见注):

    def custom_command(**kwargs):
        kwargs['ignore_extra'] = False
        def decorator(func):
            return commands.Command(func, **kwargs)
        return decorator
    
    @custom_command(name='hi')
    @commands.is_owner()
    async def hi(self, ctx, *, arg=None):
        await ctx.send(f'hi')
    

    注意:当使用第二种方法(自定义装饰器)时,此装饰器只创建一个commands.Command 的实例。如果@commands.command 进行除Command 实例化之外的任何额外检查,此方法将跳过这些检查。

    【讨论】:

    • 我不知道ignore_extra,完全错过了。谢谢你。仍然很好奇为什么 ctx.args 总是空的。
    • this issue。检查在解析和转换器之前运行。
    • 很失望这不是一个错误 :) 谢谢。
    • ignore_extra 和自定义转换器应该涵盖参数验证的大部分用例。
    猜你喜欢
    • 2021-04-14
    • 2020-06-02
    • 2020-06-20
    • 1970-01-01
    • 2014-11-03
    • 2014-10-15
    • 2017-11-16
    • 2015-03-28
    相关资源
    最近更新 更多