discord.py中Cog文件内on_ready事件未触发问题排查
问题原因分析及解决方案
问题根源
你在main.py的on_ready事件回调中才执行Cogs的加载逻辑,但Discord.py的on_ready事件是Bot完成登录连接后触发的一次性事件。当你的load()函数开始加载Cogs时,on_ready事件已经执行完毕,Cog中注册的on_ready监听器自然错过了触发时机,因此不会打印"TEST"。
而on_message能正常工作,是因为它是持续监听的事件——只要Cog加载完成,后续的所有消息事件都会被这个监听器捕获。
修复方案
把Cogs的加载逻辑移到bot.run()(或bot.start())之前执行,确保Cogs在Bot登录前就完成加载,这样它们的on_ready监听器能在Bot触发on_ready事件时被正常调用。
修改后的main.py核心代码示例:
import os import discord from discord.ext import commands import asyncio intents = discord.Intents.all() intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) async def load(): print("Loading cogs:") for filename in os.listdir("./cogs"): if filename.endswith(".py"): print(filename) await bot.load_extension(f'cogs.{filename[:-3]}') async def main(): # 先加载所有Cogs await load() # 读取Token并启动Bot with open('token.txt', 'r') as file: bot_token = file.read().strip() await bot.start(bot_token) @bot.event async def on_ready(): print(f'Logged in as {bot.user.name}') # 保留sync、reload等命令代码... asyncio.run(main())
补充说明
如果你的Discord.py版本是v2.0+,也可以使用async with bot:的上下文管理器来确保Cogs在Bot启动前加载:
async def main(): async with bot: await load() with open('token.txt', 'r') as file: bot_token = file.read().strip() await bot.start(bot_token)
内容的提问来源于stack exchange,提问作者Gianpi
相关产品推荐
相关产品推荐

