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

discord.py中Cogs使用报错求助:加载扩展的异步问题

解决discord.py加载Cogs的报错问题

错误原因分析

  • 第一个RuntimeWarning:discord.py v2.0+版本中,Bot.load_extension已改为协程函数,必须使用await关键字调用,直接调用会导致协程未被执行的警告。
  • 第二个SyntaxError:await只能在**异步函数(用async def定义)**内部使用,你直接在全局代码中使用await违反了Python语法规则。

两种可行解决方案

方案1:使用官方推荐的setup_hook方法(优先选择)

setup_hook是Bot类提供的异步钩子,会在Bot启动前自动执行,适合用来加载Cogs:

import os
import discord
from discord.ext import commands

# 初始化Bot,根据需求配置前缀和Intents
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def load_all_cogs():
    # 遍历cogs目录下的py文件
    for file in os.listdir("./cogs"):
        if file.endswith(".py"):
            # 加载对应Cog模块
            await bot.load_extension(f"cogs.{file[:-3]}")

@bot.event
async def setup_hook():
    # 在启动前执行Cog加载
    await load_all_cogs()

# 启动Bot
bot.run("你的Bot令牌")

方案2:用异步主函数包裹加载逻辑

如果需要在全局代码中处理,可以将Cog加载和Bot启动逻辑放到异步主函数中,通过asyncio.run执行:

import os
import asyncio
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def load_all_cogs():
    for file in os.listdir("./cogs"):
        if file.endswith(".py"):
            await bot.load_extension(f"cogs.{file[:-3]}")

async def main():
    await load_all_cogs()
    await bot.start("你的Bot令牌")

# 运行异步主函数
asyncio.run(main())

额外注意事项

  • 确保cogs目录下存在空的__init__.py文件,让Python将该目录识别为合法模块。
  • 确认你的discord.py版本是v2.0及以上(可通过pip show discord.py查看版本),v1.x版本的load_extension是同步函数,无需await。
  • 配置正确的Bot Intents,否则加载Cog后可能出现命令无法触发的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:55:15