如何让Discord Bot同时支持大小写不敏感与提及触发?附报错排查
解决Discord Bot命令前缀与提及响应的报错问题
你碰到的这个TypeError: 'function' object is not subscriptable错误很典型——你把commands.when_mentioned_or当成列表用了方括号[],但它本质是个函数,必须用圆括号()来调用并传入前缀参数。
错误原因分析
你的原代码:
client = commands.Bot(command_prefix=commands.when_mentioned_or['S!', 's!'], case_insensitive=True)
这里commands.when_mentioned_or是discord.py提供的辅助函数,用来生成同时支持「提及Bot」和「指定前缀」的命令前缀处理器,它需要通过函数调用的方式传入前缀,而不是下标访问。
修正后的代码
client = commands.Bot(command_prefix=commands.when_mentioned_or('S!'), case_insensitive=True)
另外,因为你已经设置了case_insensitive=True,这个参数会让前缀和命令都忽略大小写,所以只需要传入'S!'就足够匹配S!和s!两种前缀了,不用重复传两个。
效果说明
- 开启
case_insensitive=True后,S!help、s!HELP、S!HELP这些写法都会被Bot识别为有效命令 commands.when_mentioned_or('S!')让Bot同时响应两种触发方式:- 被@提及(比如
@你的Bot help) - 使用指定前缀(比如
S!help)
- 被@提及(比如
原报错信息回顾
Traceback (most recent call last):
File "main.py", line 28, in
client = commands.Bot(command_prefix=commands.when_mentioned_or['S!', 's!'], case_insensitive=True)
TypeError: 'function' object is not subscriptable
KeyboardInterrupt
内容的提问来源于stack exchange,提问作者Fat Craft
相关产品推荐
相关产品推荐

