Reputation: 2415
wordfilter = ["badword", "badword", "badword", "badword", "badword", "badword", "badword"]```
@client.listen('on_message')
async def msgfilter(message, member: discord.Member = None):
global messageserver
messageserver += 1
for word in wordfilter:
if message.content.count(word) > 0:
await message.channel.purge(limit=1)
Is my code but I recently updated the filter to match derogative use of words in every language for my Discord bot. It has over 10000+ lines in a list like this:
wordfilter = ["badword", "badword", "badword", "badword", "badword", "badword", "badword"]
but for thousands or words from 105+ languages. I have tried to put this into my main python file as it is a custom bot for my server and I want members not be able to bypass the filter in anyway possible. Once I copied the list into a the same file python file, it crashed and makes the py document unresponsive and slow to save. It works well in a txt file but how can I get the python file to get the same achievement from accessing the words from another file and filtering the way I have done it. Please let me know soon! Thanks.
Upvotes: 0
Views: 149
Reputation: 24289
Your code is inefficient because you iterate on your list of badwords, and for each iteration again on the message (for count
), which makes it O(length of words list * length of message).
You should use sets: a set of your badwords
wordfilter = {"badword", "badword", "badword", "badword", "badword", "badword", "badword"}
and a set of the word in your message:
words = set(message.content.split())
Testing if the message contains a bad word is then just:
if not words.isdisjoint(wordfilter):
# there is a badword in your message
which will be much more efficient.
Another option would be to test if any word of the message is part of the set, with:
words = message.content.split()
if any(word in wordfilter for word in words):
# there is a badword in your message
Testing if an item is in a set is just O(1), and this would stop as soon as a bad word is found.
You should test and compare.
Upvotes: 1
Reputation: 764
Sample.txt
badword1
badword2
badword3
...
badwordn
Python Code:
with open("Sample.txt","r") as f:
bad_words=f.readlines()
print("length of all bad words are ",len(bad_words))
Upvotes: 1