You need to enable JavaScript to run this app. Python开发Discord bot的clear命令触发MissingRequiredArgument错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Discord bot的clear命令触发MissingRequiredArgument错误如何解决

问题修复方案

错误原因

discord.ext.commands.errors.MissingRequiredArgument: number is a required argument that is missing 报错的核心原因是你定义clear命令时要求必须传入number参数,但用户调用命令时没有携带该参数。同时你的代码还存在逻辑问题:你强制把number硬编码为999,完全忽略了用户传入的参数值,参数定义形同虚设。

修复步骤

  • 给number参数添加默认值,用户不传参数时也可以正常执行命令,避免缺失参数报错
  • 删除硬编码的number = int(999)行,让用户传入的参数生效
  • 建议替换旧版废弃接口为discord.py官方推荐的purge方法,简化代码同时规避版本兼容问题

修复后完整代码

@client.command()
@commands.has_permissions(administrator=True)
async def clear(ctx, number: int = 10):
    # 适配Discord API单次最多删除100条消息的限制,可按需调整
    if number > 100:
        await ctx.send("单次清理消息数量不能超过100条")
        return
    if number < 1:
        await ctx.send("清理数量不能小于1")
        return
    # 多删1条是把用户发送的clear命令本身也清理掉
    deleted_count = await ctx.channel.purge(limit=number + 1)
    # 操作提示3秒后自动删除,不残留垃圾消息
    await ctx.send(f"已成功清理{len(deleted_count)-1}条消息", delete_after=3)

调用示例

  • 直接发送!clear:默认清理10条消息
  • 发送!clear 50:指定清理50条消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 23:39:04