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

discord.py实现$clear批量删消息时参数获取问题求解

解决方案

现有代码问题

  • 拆分消息得到的数字内容没有赋值给变量,执行完split后的结果直接被丢弃
  • 拆分得到的是字符串格式,需要转为整数才能传入purge方法的limit参数
  • 当前代码给limit传了固定列表[1],完全没有用到用户输入的数值

修复后可直接使用的代码

if message.content.startswith('$clear '):
    # 提取指令后的数字并去除首尾空格
    count_input = message.content.split('$clear ', 1)[1].strip()
    try:
        delete_num = int(count_input)
        # 可根据需求调整删除数量上下限,Discord API单次最多支持删除100条14天内的消息
        if not 1 <= delete_num <= 100:
            await message.channel.send("请输入1-100之间的有效数字")
            return
        # limit+1是为了把用户发的$clear指令本身也删掉
        await message.channel.purge(limit=delete_num + 1)
        # 操作提示3秒后自动删除
        await message.channel.send(f"已删除{delete_num}条消息", delete_after=3)
    except ValueError:
        await message.channel.send("参数格式错误,正确用法示例:`$clear 10`")

可选优化点

如果你的bot使用了discord.py的命令框架(commands.Bot),可以直接用装饰器注册指令,不用手动拆分消息,写法更简洁:

@bot.command()
async def clear(ctx, num: int):
    if not 1 <= num <=100:
        await ctx.send("请输入1-100之间的有效数字")
        return
    await ctx.channel.purge(limit=num+1)
    await ctx.send(f"已删除{num}条消息", delete_after=3)

# 非数字参数报错处理
@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("参数格式错误,正确用法示例:`$clear 10`")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:15:06