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:
JavaScript
x
12
12
1
@commands.Cog.listener()
2
async def on_message(self, message):
3
try:
4
file = open('./resources/wbanned.txt')
5
all_lines = file.readlines()
6
for x in range(len(all_lines)):
7
if all_lines[x] in message.content:
8
await message.delete()
9
10
except Forbidden:
11
pass
12
The list:
JavaScript
1
4
1
word
2
banned
3
kick
4
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):
JavaScript
1
11
11
1
@commands.Cog.listener()
2
async def on_message(self, message):
3
try:
4
with open('./resources/wbanned.txt') as file:
5
for line in file:
6
if line.strip() in message.content:
7
await message.delete()
8
9
except Forbidden:
10
pass
11
(Directly iterating over a file iterates line by line the same way .readlines()
does, but without creating an unnecessary list)