@bot.event 在一个 cog discord.py [英] @bot.event in a cog discord.py

查看:22
本文介绍了@bot.event 在一个 cog discord.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

in my cog class, but I get the error

NameError: name 'self' is not defined

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

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

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

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

推荐答案

new-style cog,你必须使用 commands.Cog.listener 装饰器.以下是 mental 转换为新样式的示例:

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

这篇关于@bot.event 在一个 cog discord.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆