首页 > 解决方案 > 在 python 类中使用装饰器,未定义的变量

问题描述

我有一个运行装饰器的函数,但我需要async def _test从类内部运行。

class Slash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


def setup(bot):
    bot.add_cog(Slash(bot))
    bot.slash = SlashCommand(bot, override_type=True, sync_commands=True)

    @bot.slash.slash(name="test")
    async def _test(ctx: SlashContext, a=None, b=None):
        embed = discord.Embed(title="embed test")
        await ctx.send(content="test", embeds=[embed])

bot如果我只是在类中移动代码,则没有定义,并且self.不能在装饰器中使用。知道如何让这个函数出现在课堂上吗?谢谢

标签: pythonfunctiondiscord.py

解决方案


您可以简单地使用cog_ext.cog_slash装饰器

from discord_slash import cog_ext

class Slash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @cog_ext.cog_slash(name="test")
    async def _test(self, ctx: SlashContext, a=None, b=None):
        embed = discord.Embed(title="embed test")
        await ctx.send(content="test", embeds=[embed])

PS:在介绍中,我什至没有看文档,只是在 PyPi 页面上......我不知道你怎么会错过它


推荐阅读