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

Python Discord Bot报missing required argument 'name' 能否将cog管理函数放入cog内

报错根因

missing 1 required positional argument: 'name'报错是因为Discord.py命令框架无法从你发送的!unload指令中提取到需要传入的cog名称参数,传入函数的参数数量不匹配。

修复方案
  • 首先修正cog内命令的参数声明,cog内的命令第一个固定参数为self,第二个为上下文参数ctx,第三个声明需要接收的cog名称参数,示例代码如下:
from discord.ext import commands

class AdminCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    # 卸载命令
    @commands.command()
    @commands.is_owner() # 增加所有者校验,避免普通用户调用管理命令
    async def unload(self, ctx, name: str):
        # 路径和主程序加载cog的路径保持一致
        await self.bot.unload_extension(f"cogs.{name}")
        await ctx.send(f"已成功卸载cog:{name}")
    
    # 加载命令
    @commands.command()
    @commands.is_owner()
    async def load(self, ctx, name: str):
        await self.bot.load_extension(f"cogs.{name}")
        await ctx.send(f"已成功加载cog:{name}")
    
    # 重载命令
    @commands.command()
    @commands.is_owner()
    async def reload(self, ctx, name: str):
        await self.bot.reload_extension(f"cogs.{name}")
        await ctx.send(f"已成功重载cog:{name}")

async def setup(bot):
    await bot.add_cog(AdminCog(bot))
  • 如果希望不传入参数时默认卸载当前管理cog,给name参数增加默认值即可,示例:
    async def unload(self, ctx, name: str = "admin"): 其中admin替换为你管理cog的文件名。
  • 调用命令时需要携带cog名称参数,例如要卸载名为moderation的cog,发送指令格式为!unload moderation,仅发送!unload会触发参数缺失报错。
注意事项
  • 避免直接卸载当前正在执行命令的管理cog,否则会导致命令执行中断触发异常,建议将cog管理命令放到固定不卸载的核心cog中,或直接写在主程序内。
  • 确保你调用unload/load/reload时传入的cog路径,和主程序加载cog时的路径完全一致,否则会出现找不到cog的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:15:06