Discord.py:如何用if语句检测空参数?代码未触发错误提示
解决Discord机器人slow命令未传参数无响应的问题
当用户未传入参数时,你的slow函数因为arg是必填参数,discord.py会直接抛出MissingRequiredArgument异常,根本不会进入函数内部执行你写的arg == None判断逻辑,所以机器人不会发送错误消息。以下是两种可行的修复方案:
方法一:给参数设置默认值并提前判断
修改代码,给arg设置默认值None,在函数开头就判断是否缺参数,同时修复字符串比较和类型转换的问题:
@bot.command(pass_context=True, aliases=['sl']) async def slow(ctx, arg: str = None): # 先判断是否未传参数 if arg is None: await ctx.send(f"Error 00: Please specify slowmode time. e.g: !slow 2") return # 转换为整数并验证有效性 try: delay = int(arg) except ValueError: await ctx.send("Error 01: Please enter a valid number.") return # 限制最大时长 if delay > 21600: await ctx.send("You are restricted to ``21600 seconds``") else: await ctx.channel.edit(slowmode_delay=delay) await ctx.send(f"Slowmode set to ``{delay}`` seconds.")
方法二:使用命令错误处理器
保留必填参数,通过专门的错误处理器捕获缺参数异常,同时修复类型问题:
@bot.command(pass_context=True, aliases=['sl']) async def slow(ctx, arg: str): try: delay = int(arg) if delay > 21600: await ctx.send("You are restricted to ``21600 seconds``") else: await ctx.channel.edit(slowmode_delay=delay) await ctx.send(f"Slowmode set to ``{delay}`` seconds.") except ValueError: await ctx.send("Error 01: Please enter a valid number.") # 针对slow命令的错误处理函数 @slow.error async def slow_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(f"Error 00: Please specify slowmode time. e.g: !slow 2")
关键修复点说明
- 原代码中直接用字符串比较
arg > '21600'逻辑错误(比如字符串'9999'会被判定为大于'21600'),必须转换为整数后比较。 slowmode_delay参数要求整数类型,直接传入字符串会引发错误,所以必须添加类型转换和异常捕获。- 缺参数的情况要么通过默认值让函数能执行判断,要么通过错误处理器捕获框架抛出的异常。
内容的提问来源于stack exchange,提问作者tehnitro
相关产品推荐
相关产品推荐

