创建具有命令特定属性的自定义命令对象
Create custom command object with command specific attributes
我想创建一个自定义命令类型,我猜你会这样称呼它。这个想法是每次调用命令时,它首先检查其自定义属性,然后修改相同的属性。
这是我到目前为止的代码,虽然它不起作用,但我希望它能展示我正在尝试做的事情。
class Perc(commands.Command):
def __init__(self , func , basePrice = 10):
super().__init__(func)
self.basePrice : int = basePrice
async def __call__(self, *args, **kwargs):
# modify base price
self.basePrice += 10
return await super().__call__(*args, **kwargs)
@Perc(basePrice = 25)
async def testPerc(ctx : commands.Context):
await ctx.send("command called")
您需要使 returns 成为新 class 的工厂函数。要装饰一个函数,你需要 @decorator(args)
来完成 (decorator(args))(func)
。这就是 __call__
不起作用的原因。
如果您查看源代码 here,在第 498 行,您有 __call__(self, context: Context[BotT], /, *args: P.args, **kwargs: P.kwargs) -> T:
。可以看出这不是创建装饰器,而是真正调用了对象。
有更好的方法,使用 before_invoke
。
@dataclass
class Perc:
basePrice: int
price = Perc(basePrice=25)
@commands.command(name='perc')
async def perc(ctx):
await ctx.send(f'I have finished the command: {price}.')
async def before_perc(ctx):
price.basePrice += 10
await ctx.send('I have finished before_invoke')
perc.before_invoke(before_perc)
client.add_command(perc)
这使得 before_perc
在执行命令之前立即执行。在这里您可以添加您的逻辑,例如提高基本价格。
输出(运行两次):
我想创建一个自定义命令类型,我猜你会这样称呼它。这个想法是每次调用命令时,它首先检查其自定义属性,然后修改相同的属性。
这是我到目前为止的代码,虽然它不起作用,但我希望它能展示我正在尝试做的事情。
class Perc(commands.Command):
def __init__(self , func , basePrice = 10):
super().__init__(func)
self.basePrice : int = basePrice
async def __call__(self, *args, **kwargs):
# modify base price
self.basePrice += 10
return await super().__call__(*args, **kwargs)
@Perc(basePrice = 25)
async def testPerc(ctx : commands.Context):
await ctx.send("command called")
您需要使 returns 成为新 class 的工厂函数。要装饰一个函数,你需要 @decorator(args)
来完成 (decorator(args))(func)
。这就是 __call__
不起作用的原因。
如果您查看源代码 here,在第 498 行,您有 __call__(self, context: Context[BotT], /, *args: P.args, **kwargs: P.kwargs) -> T:
。可以看出这不是创建装饰器,而是真正调用了对象。
有更好的方法,使用 before_invoke
。
@dataclass
class Perc:
basePrice: int
price = Perc(basePrice=25)
@commands.command(name='perc')
async def perc(ctx):
await ctx.send(f'I have finished the command: {price}.')
async def before_perc(ctx):
price.basePrice += 10
await ctx.send('I have finished before_invoke')
perc.before_invoke(before_perc)
client.add_command(perc)
这使得 before_perc
在执行命令之前立即执行。在这里您可以添加您的逻辑,例如提高基本价格。
输出(运行两次):