Discord Python Rewrite自定义Help命令无效分类错误排查
问题根源与修复方案
嘿,这个问题我太熟悉了!你代码里的条件判断逻辑写错了,这才导致输入无效分类时总是跳转到Moderation的帮助内容。
为什么会出错?
你看这段代码:
if category == 'mod' or 'moderation' or 'Mod' or 'Moderation':
这里的or用法完全不对!Python里,'moderation'这种单独的字符串本身就是布尔真值,不管category是什么值,这个条件都会被判定为True,所以不管用户输入什么分类(哪怕是乱输的),都会直接进入Moderation的分支。
修复步骤
1. 优化条件判断逻辑
把每个比较都写完整,或者更简洁的方式:统一将输入的category转成小写,再判断是否在指定的列表里,这样还能忽略大小写的差异,用户输入MOD或者ModErAtIoN都能正确识别。
2. 添加无效分类的处理分支
在所有合法分类判断之后,加一个else分支,用来返回无效分类的提示Embed或者消息。
修复后的完整代码
@client.command() async def help(ctx, *, category = None): if category is not None: # 统一转小写,简化判断逻辑 lower_category = category.lower() if lower_category in ['mod', 'moderation']: modhelpembed = discord.Embed( title="Moderation Help", timestamp=datetime.datetime.now(), colour=discord.Color.green() ) modhelpembed.add_field(name='kick', value="Kicks a member from the server", inline=False) modhelpembed.add_field(name='ban', value='bans a member from the server', inline=False) modhelpembed.add_field(name='unban', value='unbans a member from the server', inline=False) modhelpembed.add_field(name="nuke", value="Nukes a channel :>", inline=False) modhelpembed.add_field(name='mute', value="Mute a member", inline=False) modhelpembed.add_field(name="purge", value='purges (deletes) a certain number of messages', inline=False) await ctx.send(f'{ctx.author.mention}') await ctx.send(embed=modhelpembed) elif lower_category in ['fun']: funembed = discord.Embed( title="Fun Help", timestamp=datetime.datetime.now(), colour=discord.Color.green() ) funembed.add_field(name='meme', value='shows a meme from r/memes', inline=False) funembed.add_field(name='waifu', value='shows a waifu (pic or link) from r/waifu', inline=False) funembed.add_field(name='anime', value='shows a anime (image or link) from r/anime', inline=False) funembed.add_field(name='spotify', value='Tells you the targeted user listening on', inline=False) funembed.add_field(name="song", value="Tells you the whats the targeted user listening in Spotify", inline=False) funembed.add_field(name="album", value="Tells you whats the targeted user album", inline=False) funembed.add_field(name="timer", value="Sets a Timer for you.", inline=False) await ctx.send(f'{ctx.author.mention}') await ctx.send(embed=funembed) else: # 处理无效分类的情况 error_embed = discord.Embed( title="Invalid Category!", description=f"Sorry, `{category}` is not a valid category.\nAvailable categories: `mod`, `fun`", colour=discord.Color.red() ) await ctx.send(f'{ctx.author.mention}', embed=error_embed) else: nonembed = discord.Embed( title="Help list", timestamp=datetime.datetime.now(), colour=discord.Color.green(), description='Category:\nmod\nfun' ) await ctx.send(f'{ctx.author.mention}') await ctx.send(embed=nonembed)
关键修改点
- 将
category转成小写后判断,避免大小写敏感的问题 - 用
in关键字判断是否在合法分类列表里,代码更简洁 - 添加了
else分支,专门处理无效分类,返回红色提示Embed
内容的提问来源于stack exchange,提问作者Raphiel
相关产品推荐
相关产品推荐

