[英]How to use a case insensitive function in if statement python
我目前正在使用 discord.py 库编写 discord 机器人,我希望我的机器人在检测到消息中的单词而不检查大写字母时做出特定反应。
为了做到这一点,我已经找到了一个 class,但是由于未知的原因,当我使用这个 class 时,机器人没有检测到消息内部的字符串,他只有在它是单独的消息时才检测到它......
这是我发现的 class:
class CaseInsensitively(object):
def __init__(self, s):
self.__s = s.lower()
def __hash__(self):
return hash(self.__s)
def __eq__(self, other):
try:
other = other.__s
except (TypeError, AttributeError):
try:
other = other.lower()
except:
pass
return self.__s == other
这是 class 的用法:
@client.event
async def on_message(message):
test = "Test"
if CaseInsensitively(test) in {CaseInsensitively(message.clean_content)}:
await discord.Message.add_reaction(message, "🇧")
await client.process_commands(message)
我在 ubuntu 16.04 上使用 python 3.7.1。
问题是这些额外的大括号
{CaseInsensitively(message.clean_content)}
这不再是一个字符串,它是一个set
。 因此,它正在检查您的确切字符串是否包含在该集合中,它不再进行 substring 检查
>>> 'foo' in 'foobar' # substring check
True
>>> 'foo' in {'foobar'} # set containment
False
>>> 'foo' in {'foo'} # set containment
True
在我看来,无论如何都不需要 class ,这应该足够了
if test.lower() in message.clean_content.lower():
我同意您收到的评论。 您添加的不区分大小写有点矫枉过正。 .lower()
就足够了:
if "test" in message.content.lower():
此外,当您添加反应时,您需要发送的消息 object,而不仅仅是一些“空”的任意消息 object:
@client.event
async def on_message(message):
if "test" in message.content.lower():
await message.add_reaction("🇧")
await client.process_commands(message) # in the same way here you've referenced message
discord.Message
只是基础 class,当您可以引用已经存在的实例时,您不需要创建它的新实例; message
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.