【问题标题】:Discord.py read listDiscord.py 阅读列表
【发布时间】:2021-05-23 16:18:12
【问题描述】:

我有一个文件,其中包含一个名为 wbanned.txt 的列表,其中包含禁用词。 我希望阅读发送的每条消息,如果它包含 txt 列表中的一个禁止单词(每个单词都在列表中的新行上),则将其删除。

我尝试了一些方法,但只有当它包含列表中的最后一个单词时才将其删除。

代码:

@commands.Cog.listener()
async def on_message(self, message):
    try:
        file = open('./resources/wbanned.txt')
        all_lines = file.readlines()
        for x in range(len(all_lines)):
            if all_lines[x] in message.content:
                await message.delete()

    except Forbidden:
        pass

名单:

word
banned
kick

所以程序必须接受这句话:“This is example 1” 但是如果你输入:“This a被禁止的成员”这句话需要删除。

【问题讨论】:

    标签: python list discord discord.py


    【解决方案1】:

    .readlines() 包含尾随换行符,因此您需要 .strip() 它们。

    代码(为最佳实践做了一些清理):

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            with open('./resources/wbanned.txt') as file:
                for line in file:
                    if line.strip() in message.content:
                        await message.delete()
    
        except Forbidden:
            pass
    

    (直接迭代文件会像.readlines()一样逐行迭代,但不会创建不必要的列表)

    【讨论】:

    • 您不应该在每条消息上都打开文件...理想情况是在启动时加载文件并将单词列表作为变量传递...
    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多