首页 > 解决方案 > 如何从列表中检测句子中的单词?

问题描述

所以我正在创建一个不和谐的机器人,我希望它在有人发送消息时删除消息,并且它包含一个特定的词,在这种情况下是一个坏词。

f = open("filter_words.txt", 'r')
list = f.read()
f.close()

msg = message.content
msg = msg.lower()

if msg in list:
    await message.delete()
    await message.channel.send(f"{message.author.mention}'s message was deleted")

filter_words.txt包含一个坏词列表{'word', 'another'}。此处代码仅在有人仅键入单词时才删除消息。如果单词在句子中的任何位置,我希望它删除消息。我希望我正确地解释了这一点。

标签: pythondiscord.py

解决方案


def check_bad_word(msg, list):
    ''' Detect bad word.'''
    # Loop over all bad word
    for word in list:
        # bad word found ('in' can make wrong detection)
        if word in msg:
             return True
    return False

if check_bad_word(msg, list)
    await message.delete()
    await message.channel.send(f"{message.author.mention}'s message was deleted")

推荐阅读