Python 如何扩展client.command的功能?

Python 如何扩展client.command的功能?,python,discord.py,discord.py-rewrite,Python,Discord.py,Discord.py Rewrite,我试图增加client.command(client是一个discord.ext.commands.Bot实例)的错误、arg、kwarg和函数的处理。 基本上,我试图让我的所有命令都具有某些共同的自定义行为 我最初的想法是创建一个函数,返回一个decorator,它用client.command装饰包装器 但是,我遇到的最大问题是,client.command(…)返回的decorator的参数处理完全取决于修饰函数的参数和注释的排列方式,这意味着包含如下参数的包装器 async def包装(

我试图增加
client.command
client
是一个
discord.ext.commands.Bot
实例)的错误、arg、kwarg和函数的处理。 基本上,我试图让我的所有命令都具有某些共同的自定义行为

我最初的想法是创建一个函数,返回一个decorator,它用
client.command
装饰包装器

但是,我遇到的最大问题是,
client.command(…)
返回的decorator的参数处理完全取决于修饰函数的参数和注释的排列方式,这意味着包含如下参数的包装器

async def包装(*args,**kwargs):
将接收原始参数。这意味着我必须自己在包装器中处理所有的事情,这一点从一开始就挫败了使用
discord.ext.commands
的全部意义

在阅读中,我试图想出一个解决办法。下面是代码的草图,删去了与问题无关的部分:

从discord.ext导入命令为c
将不和谐导入为d
client=c.Bot(command_prefix=“insert_prefix_here$”)
def命令(*args,**kwargs):
def装饰器(func):
command_name=kwargs.setdefault(“name”,func.\u name\uuuuuu)
异步def包装(ctx、*args、**kwargs):
#使用func和命令名进行操作
#……嗯?这是我见过的最脏的东西
包装器.\uuuu默认值\uuuu=func.\uuuu默认值__
包装器.\uuuu注释\uuuu=func.\uuu注释__
wrapper=client.command(*args,**kwargs)(wrapper)
@包装器错误
异步def包装器_错误(ctx,错误):
#用ctx做东西,错误,命令名。。。等
返回包装器
返回装饰器
#在此处插入带有@command(…)装饰符的命令
我简单地想到了通过将包装器的
\uuu default\uuu
\uu注释\uu
属性设置为装饰函数的属性,来“欺骗”客户机.command(…)返回的装饰器,使其认为包装器的参数结构与装饰函数的参数结构相同

是的,我完全意识到这是一个可怕的想法,也不是很好的想法(甚至不起作用)。这就是为什么我贴了这个,这意味着我的方向不好

有什么建议吗

有没有一种我完全不知道的更简单的方法来做这样的事情


我是否应该从头开始构建一个
命令
装饰程序,并坚持使用
discord.Client
而不是尝试添加到
Client.command

我认为您根本不需要扩展
命令
的功能。相反,您可以使用机器人范围的
on_command_error
on_command_completion
事件来提供所需的功能

唯一的问题是返回值。最简单的方法可能是分配一个未使用的属性
ctx
,而不是试图捕获返回值(您也可以使用返回值引发自定义错误)


你到底想做什么样的改变?可以使用
cls
参数对
Command
进行子类化,并将子类传递给
client.Command
。更具体地说,现在我正在尝试处理
BadArgument
MissingRequiredArgument
,发生另一个异常的情况以及没有异常发生的情况(并使用返回值执行操作)。我希望所有命令都以相同的方式执行。
from discord.commands.ext import Bot, BadArgument, MissingRequiredArgument
import sys

bot = Bot("!")

@bot.command()
async def some_command(ctx):
    ctx.return_value = 1

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, BadArgument):
        await ctx.send("That's a bad argument")
    elif isinstance(error, MissingRequiredArgument):
        await ctx.send("You're missing an argument")
    else:
        # This is what the standard on_command_error does
        print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
        traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)

@bot.event
async def on_command_completion(ctx):
    await ctx.send(str(ctx.return_value))

bot.run("TOKEN")