@bot.event 在 cog discord.py 中

新手上路,请多包涵

我想知道是否可以在 discord.py 的 cog 中使用 @bot.event。我试过做

@self.bot.event
async def on_member_join(self, ctx, member):
    channel = discord.utils.get(member.guild.channels, name='general')
    await channel.send("hello")

在我的齿轮类中,但我得到了错误

NameError: name 'self' is not defined

即使我在我的 __init __ 中定义了 self.bot。

在 cogs 中是否有不同的 bot.event 处理方式,还是根本不可能?

原文由 qspitzer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 504
2 个回答

要从 新式 cog 注册事件,您必须使用 commands.Cog.listener 装饰器。下面是转换为新样式的 mental 示例:

 from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_ready(self):
        print('Ready!')
        print('Logged in as ---->', self.bot.user)
        print('ID:', self.bot.user.id)

    @commands.Cog.listener()
    async def on_message(self, message):
        print(message)

def setup(bot):
    bot.add_cog(Events(bot))

原文由 Patrick Haugh 发布,翻译遵循 CC BY-SA 4.0 许可协议

我不推荐 qspitzers 的回答,因为这不是将您的事件转移到 cog 的明智方法,而且答案可能会引发一些未知/意外的异常。

而是做这样的事情。

 from discord.ext import commands

class Events:
    def __init__(self, bot):
        self.bot = bot

    async def on_ready(self):
        print('Ready!')
        print('Logged in as ---->', self.bot.user)
        print('ID:', self.bot.user.id)

    async def on_message(self, message):
        print(message)

def setup(bot):
    bot.add_cog(Events(bot))

请记住,要将事件放置在齿轮内,您不需要装饰器。此外,cog 内的事件不会覆盖默认事件,这些事件将存储在 bot.extra_events 中。

原文由 mental 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进