You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Bot无法加载子文件夹命令(VS Code运行报错求助)

Discord Bot加载子文件夹命令失败的解决办法

问题情况

  • Bot在VS Code能正常启动,但Commands子文件夹里的命令加载不出来
  • 运行时弹出警告:

    RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
    bot.load_extension(f'Commands.{filename[:-3]}')
    RuntimeWarning: Enable tracemalloc to get the object allocation traceback

  • 输入=help只能看到「Non Category」里的命令

出问题的代码片段

用来加载命令的代码:

for filename in os.listdir('./Commands'):
    if filename.endswith('.py'):
        bot.load_extension(f'Commands.{filename[:-3]}')

token = '(my bot token)'
bot.run(token)

问题原因和解决办法

1. 异步函数没加await

bot.load_extension是异步协程函数,必须用await调用,不然就会触发警告,还加载不了扩展。而且这段代码得放在异步函数里执行,比如用setup_hook或者自己写个异步初始化函数。

改好的加载代码示例:

用自定义异步启动函数的写法:

import asyncio

async def load_commands():
    for filename in os.listdir('./Commands'):
        if filename.endswith('.py'):
            await bot.load_extension(f'Commands.{filename[:-3]}')

async def main():
    await load_commands()
    await bot.start(token)

asyncio.run(main())

如果用discord.py v2.x版本,更推荐用setup_hook生命周期函数:

async def setup_hook():
    for filename in os.listdir('./Commands'):
        if filename.endswith('.py'):
            await bot.load_extension(f'Commands.{filename[:-3]}')

bot.setup_hook = setup_hook
bot.run(token)

2. 把Commands文件夹变成Python包

在Commands文件夹里新建一个空的__init__.py文件,让Python把这个目录当成合法的包,不然没法用Commands.xxx的方式导入模块。

3. 解决命令分类不显示的问题

如果改完上面的,=help里还是看不到分类,得确保每个命令文件里正确设置了category属性:

from discord.ext import commands

# 命令组的写法
@commands.group(name="命令组名称", description="命令组说明", category="你的分类名")
async def my_group(ctx):
    pass

# 单个命令的写法
@commands.command(name="命令名称", category="你的分类名")
async def my_command(ctx):
    pass

内容的提问来源于stack exchange,提问作者fciccioend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 02:45:05