Discord机器人Cogs加载异常求助:on_ready无输出、命令失效
Discord机器人Cogs加载失败问题解决
核心问题
你的代码存在执行顺序错误:bot.run()是同步阻塞调用,执行后会持续占用主线程,导致后续的asyncio.run(main())完全无法运行——这意味着你写的load_cogs()函数根本没被执行,Cogs自然没加载,所以Cog内的on_ready事件和命令都不会生效。
修正方案
调整代码结构,将Cogs加载和机器人启动放在同一个异步流程中,用await bot.start()替代bot.run()(bot.run()内部封装了异步循环,但会阻断后续代码执行)。
修正后的bot.py代码:
import discord import os import asyncio from discord.ext import commands intents = discord.Intents.all() intents.members = True bot = commands.Bot(command_prefix=".", intents=intents, help_command=None) async def load_cogs(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): try: await bot.load_extension(f'cogs.{filename[:-3]}') print(f"Cog '{filename[:-3]}' loaded successfully.") except Exception as e: print(f"Error loading cog '{filename[:-3]}': {type(e).__name__} - {e}") async def main(): await load_cogs() await bot.start("你的机器人令牌") # 替换为实际的机器人令牌 asyncio.run(main())
额外检查项
- 确保
cogs文件夹与bot.py在同一目录下,且文件夹内的main.py文件名正确(注意大小写,部分系统区分文件名大小写)。 - 确认Discord开发者平台中,机器人的所有必要权限和Intents已开启(你代码中用了
Intents.all(),需在平台对应页面勾选)。
运行修正后的代码后,你应该能看到Cog 'main' loaded successfully.和ready的输出,说明Cog加载正常,事件和命令可以正常触发。
内容的提问来源于stack exchange,提问作者nenail nenail
相关产品推荐
相关产品推荐

