如何让Discord.py命令支持大小写不敏感?拆分到Cog后怎么适配?
解决Discord.py拆分Cog后命令大小写不敏感的问题
之前单文件里用on_message把消息内容转小写的方法确实能实现命令大小写不敏感,但它有个明显的缺点——会把消息里的所有内容(包括命令参数)都转成小写,可能会影响需要区分大小写参数的命令。而且拆分到Cog后如果出现失效,大概率是因为某个Cog里的on_message事件没有正确调用await bot.process_commands(message),或者多个on_message事件的执行顺序导致处理逻辑冲突。
更优雅且全局生效的解决方案是直接在创建Bot实例时开启命令大小写不敏感,这样不管是主文件里的命令还是Cog里的命令,都会自动支持大小写匹配,还不会改动消息的原始内容。
具体实现步骤
1. 主文件全局配置
在创建commands.Bot实例时,添加command_attrs={'case_insensitive': True}参数:
import discord from discord.ext import commands # 全局启用所有命令的大小写不敏感 bot = commands.Bot( command_prefix='!', # 你的命令前缀 command_attrs={'case_insensitive': True} ) # 加载所有需要的Cog bot.load_extension('cogs.ping_cog') # bot.load_extension('cogs.other_cog') # 其他Cog文件 @bot.event async def on_ready(): print(f"已登录为 {bot.user.name}") bot.run("你的机器人Token")
2. Cog文件无需额外修改
以你的ping命令为例,Cog里的命令不需要做任何特殊配置,正常写就行:
from discord.ext import commands class PingCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def ping(self, ctx): msg = f'Pong {ctx.author.mention}' await ctx.send(msg) def setup(bot): bot.add_cog(PingCog(bot))
这样不管用户输入!ping、!Ping、!PING甚至!PiNg,都能正常触发命令。
可选:单独为某个命令设置大小写不敏感
如果你不想全局开启,只想让特定命令支持大小写不敏感,可以在命令装饰器里单独设置:
@commands.command(case_insensitive=True) async def ping(self, ctx): # 命令逻辑
为什么不推荐原来的on_message方法?
- 会修改消息的原始内容,导致命令参数也被转小写,比如用户输入
!search DiscordPY会变成!search discordpy,如果你的命令需要区分参数大小写,就会出问题。 - 当多个Cog都定义了
on_message事件时,如果某个Cog的事件没有调用await bot.process_commands(message),会导致主文件的处理逻辑失效。
内容的提问来源于stack exchange,提问作者Demotry
相关产品推荐
相关产品推荐

