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

Discord Bot导入Cog模块失败及命令调用错误求助

Discord Bot Cog加载与Ban命令问题解决方案

问题分析

你遇到了两个核心问题:

  1. 早期版本中main.py存在重复的ban命令,调用时错误传递参数导致类型错误
  2. Discord.py v2+版本中load_extension改为异步方法,未使用await导致RuntimeWarning,进而Cog未正确加载

修复步骤

1. 修正main.py中的Cog加载逻辑

将异步加载逻辑正确执行,移除手动加载的冗余代码:

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

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

async def load_cogs():
    for filename in os.listdir('./cogs'):
        if filename.endswith(".py"):
            cog_name = filename[:-3]
            cog_path = f'cogs.{cog_name}'
            try:
                await bot.load_extension(cog_path)  # 必须使用await
                print(f"Loaded extension: {cog_name}")
            except commands.ExtensionAlreadyLoaded:
                print(f"Extension {cog_name} is already loaded.")
            except commands.ExtensionNotFound:
                print(f"Extension {cog_name} not found.")

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.dnd, activity=discord.Game('Playing Call of Duty: Modern Warfare 3'))
    print("--------------------------------------------")
    print("Bot is ready")
    print("--------------------------------------------")

@bot.command()
async def hello(ctx):
    await ctx.send(f"Hello there, {ctx.author.mention}!")

async def main():
    async with bot:
        await load_cogs()
        with open("token.txt") as file:
            token = file.read().strip()  # 去除多余空格和换行符
        await bot.start(token)

asyncio.run(main())

2. 确保无重复命令

删除main.py中任何直接定义的ban命令(错误日志显示你之前存在该重复定义),Cog中的ban命令会在加载后自动注册。

3. 验证Ban Cog文件

你的Ban Cog代码本身是正确的,只需确保:

  • 文件名为ban.py且放置在cogs文件夹中(与main.py同级)
  • setup函数正确添加Cog到Bot实例

修复原理

  • 异步加载修正:Discord.py v2+中load_extension改为异步方法,必须使用await才能正确执行加载操作
  • 生命周期管理:使用async with bot和asyncio.run(main())确保Cog在Bot启动前完成加载
  • 重复命令移除:避免命令名称冲突,确保只有Cog中的ban命令被注册

测试方法

  1. 运行更新后的main.py,控制台应输出Loaded extension: ban
  2. 使用!ban @目标用户命令测试(需拥有ban成员权限),命令应正常执行并发送提示消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:34:56