@bot.event in a cog discord.py

孤街醉人 提交于 2019-12-22 18:28:29

问题


I was wondering if it is possible to use @bot.event in a cog for discord.py. I have tried doing

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

in my cog class, but I get the error

NameError: name 'self' is not defined

even though I define self.bot in my __init __.

Is there a different way of doing bot.event in cogs, or is it just not possible?


回答1:


I do not reccomend qspitzers answer since this is not a sensible way of moving your events to a cog and the answer may throw some unknown/unexpected exceptions.

Instead do something like this.

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))

Keep in mind that to place an event inside a cog you do not need a decorator for it. Also the events inside the cog do not overide the default events and these events will be stored in bot.extra_events.




回答2:


To register an event from a new-style cog, you must use the commands.Cog.listener decorator. Below is mental's example converted to the new style:

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))



回答3:


So, I figured out a way to get this to work. What I did was I created a new function and passed it the bot variable from the setup function. I then created a background task of the new function, and had @bot.event running in that. The code is

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))

in case anyone did not understand my explanation

EDIT: this is a bad way of doing things. use mental's way instead



来源:https://stackoverflow.com/questions/48038953/bot-event-in-a-cog-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!