Skip to content
Advertisement

Discord.py read list

I have a file with a list called wbanned.txt which contains forbidden words. I want every message sent to be read and if it contains one of the forbidden words in the txt list (Every word is on a new line from list) to be deleted.

I tried something but all it does is delete it only if it contains the last word in the list.

The code:

@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

The list:

word
banned
kick

So the program must accept this sentence: “This is example 1” But if you type: “This a banned member” this sentence need to be deleted.

Advertisement

Answer

.readlines() includes the trailing newlines, so you need to .strip() them.

Code(with some cleanup for best practices):

@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

(Directly iterating over a file iterates line by line the same way .readlines() does, but without creating an unnecessary list)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement