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

如何创建Discord Cogs?排查我的机器人代码加载异常问题

Discord Cogs 创建与加载异常排查

第一种加载方式的问题

你的main.py加载Cog的代码存在语法错误:

client.load_extension(f'cogs. {filename[:-3]}')

cogs.后多了一个空格,导致生成的模块路径为cogs. greetings而非正确的cogs.greetings。这会让Bot无法找到对应Cog模块,虽然代码打印了加载成功的提示,但实际加载操作已失败,因此Cog内的命令无法生效。

修正代码:

client.load_extension(f'cogs.{filename[:-3]}')

第二种加载方式的问题

你遇到的RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited,是因为使用了discord.py v2.x版本——该版本中load_extension已改为异步函数,必须通过await关键字调用,且需放在异步上下文(如on_ready事件)中执行。

修正后的完整代码示例:

import discord
from discord.ext import commands
import os
from secret import TOKEN

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix='$', intents=intents, case_insensitive=True, owner_id=262215934322671616)

initial_extensions = []

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')
    print("At Your Service, Sir")
    print("------------------")
    await client.change_presence(activity=discord.Game(name=f'Hi, my name is {client.user.name}. Currently in development, but come back later!'))
    # 在异步事件中加载所有Cog
    for extension in initial_extensions:
        await client.load_extension(extension)
        print(f'Loaded {extension}')

# 收集Cog模块路径
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append(f"cogs.{filename[:-3]}")

client.run(TOKEN)

额外必查项

  • 确认目录结构正确:
    项目根目录/
      main.py
      secret.py
      cogs/
        __init__.py  # 必须存在空文件,将cogs标记为Python包
        greetings.py
    
  • 检查discord.py版本:v1.x版本中load_extension为同步函数,v2.x需异步调用,可通过pip show discord.py查看版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:20:28