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
相关产品推荐
相关产品推荐

