此函数的目的是检查某个值(message.guild.id)是否位于字典中的另一个值内,如果是,则返回另一个值,即字符串单词列表。然后,检查 message.content 中的单词是否位于返回的单词字符串列表中。
代码:
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
bwl = GetWF(message.guild.id) #get banned words for given server if they exist
print(type(bwl))
print(bwl)
if bwl is not None:
xxx = " ".join(str(i) for i in bwl)
xxx2 = xxx.replace('[', '').replace(']', '')
print(xxx2)
#print(type(xxx))
try:
for word in ' '.join(x for x in xxx2): #for words in banned list
if word in message.content:
await message.delete()
await message.channel.send(f"`HEY {message.author.name}!\nThat word is banned!`")
else:
return
except Exception as e:
return
else:
print("bw not found")
pass
await client.process_commands(message)
几乎达到了我想要的效果。 但是,假设返回的列表是:“cat”、“dog”、“mouse” 如果我说“老鼠”,它就不起作用,如果我说“狗”,它就起作用。但即使我说的单词不在列表中,它仍然有效。 例如: “dog”将被检测并删除 但 即使“noob”不在字典中,“noob”也会被检测到并删除。 我如何让它完全按照我想要的方式做,即查看单词是否在字典中,如果是,则删除单词。
尝试了代码,我期望得到正确的结果,但是可惜,没有
像这样进行检查,这将解决您的问题:
if any(word in bwl for word in message.content.split()):
#try:
await message.delete()
await message.channel.send(f"`HEY {message.author.name}!\nThat word is banned!`")
#except Exception as e:
# pass
通常你不想盲目地忽略和隐藏任何异常,所以我注释掉了那部分。如果您确定需要它,请取消注释。
其工作原理如下:
bwl
是字符串列表。message.content
是一个字符串。message.content.split()
是一个字符串列表,我们通过在空格上分割来从 message.content
获得。any(word in bwl for word in message.content.split())
。为了获得更好(更宽松)的匹配,您可能需要进行一些预处理:
bwl = set(word.replace('[', '').replace(']', '').lower()
for word in bwl)
,匹配时也将
message.content
转为小写:
if any(word in bwl for word in message.content.lower().split()):
请注意,你的检查还是太严格了,例如如果用户说
mouse!
(带感叹号),那么就不会匹配。此外,单词 mice
也不会被匹配。此外,单词 dogs
也不会被匹配。此外,单词 tomcat
也不会被匹配。您可能还想在 StackOverflow.com 上提出单独的问题以获得这些匹配。
请注意,您的函数看起来非常慢并且浪费网络带宽,因为它为每条消息从服务器检索
bwl
。要解决此问题,请在此函数之外初始化 bwl
。