【问题标题】:@bot.event in a cog discord.py@bot.event 在一个 cog discord.py
【发布时间】:2018-06-10 20:37:48
【问题描述】:

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

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

在我的 cog 类中,但出现错误

NameError: name 'self' is not defined

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

是否有不同的方式在 cogs 中执行 bot.event,或者它是不可能的?

【问题讨论】:

    标签: python-3.x discord discord.py


    【解决方案1】:

    所以,我想出了一种方法来让它发挥作用。我所做的是创建了一个新函数并将设置函数中的 bot 变量传递给它。然后我创建了新功能的后台任务,并在其中运行了@bot.event。代码是

    def xyz(bot):
        @bot.event
        async def on_member_join(member):
            print("ABC")
    
    def setup(bot):
        bot.loop.create_task(xyz(bot))
        bot.add_cog(cogClass(bot))
    

    如果有人不明白我的解释

    编辑: 这是一种糟糕的做事方式。改用mental的方式

    【讨论】:

      【解决方案2】:

      我不推荐 qspitzer 回答,因为这不是将事件转移到 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 中,您不需要为它使用装饰器。此外,cog 内的事件不会覆盖默认事件,这些事件将存储在 bot.extra_events 中。

      【讨论】:

      • 当然,Events 类必须从 commands.Cog 中提取,就像 Patrick Haugh 的回答一样?
      • 这在 v1.0 及更高版本中停止工作。请参阅下面 Patrick Haugh 的回答。
      【解决方案3】:

      要从 new-style 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))
      

      【讨论】:

        猜你喜欢
        • 2020-09-16
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 2021-01-30
        • 2020-07-04
        • 1970-01-01
        • 2020-12-17
        • 2020-02-12
        相关资源
        最近更新 更多