(discord.py)检查消息是否包含列表中元素的正确方法是什么?

时间:2020-07-17 12:09:24

标签: python python-3.x discord discord.py discord.py-rewrite

我正在尝试为我的机器人制作亵渎过滤器。我允许服务器管理员自己列出我的机器人在其服务器上使用的坏词列表。在on_message函数中,我使用以下代码检查用户消息中是否包含来自过滤器的单词:

file = open(f"configs/antiswearvalues/customantiswear/{message.guild.id}.txt")

res = [ele for ele in file.read() if (ele in message.content)]

if bool(res):
    await message.channel.send("you did a bad. time for the boot.")

问题在于,即使消息中包含元素的片段而不是整个元素,该机器人仍会说you did a bad. time for the boot.

因此,如果列表为['omg', 'crap', 'hell'],则漫游器仍会警告用户,如果他们的消息包含hcr,因为hellcrap包含

我的问题是:如何使我的漫游器正确检查用户的消息中是否包含列表中的元素?

1 个答案:

答案 0 :(得分:2)

您应该考虑使用json。比不使用任何库来解析txt文件更容易获得单词黑名单:

您的json文件(例如blacklist.json):

['omg', 'crap', 'hell']

您的python代码:

from json import loads

@client.event
async def on_message(message):
    with open("blacklist.json", "r"):
        data = loads(file.read())
    for word in data:
        if word in message.content:
            await message.channel.send("you did a bad. time for the boot.")
    return

您的代码无法正常运行,因为您没有解析文件数据,而是在浏览字符串,而不是列表。