Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.py swear word filter

I'm making a discord.py bot with rewrite. I want to make an anti-swear word filter so that if someone swears in a message it will delete the message and send a message. I have a swear word file with all the words that I need.

This is the code that I have so far, but it doesn't work:

@client.event
async def on_message(ctx, message):
    msg = message.content
    with open('badWords.txt') as BadWords:
        if msg in BadWords.read():
            await message.delete()
            await ctx.send("Dont use that word!")
        else:
            await ctx.process_commands(message)

All help is appreciated!

like image 408
MaxTheMinerBoy Avatar asked Oct 27 '25 12:10

MaxTheMinerBoy


1 Answers

Let's assume that BadWords.txt is formatted like this:

Word1 Word2 Word3

Note that every word is separated by a space.

So, we need to open the file, outside the on_message() function. If it's inside the function, then we would open it all the time, every time. That can be hard on the bot. So, at the top, below the import statements:

with open('BadWords.txt', 'r') as f:
    words = f.read()
    badwords = words.split()

Now, you have all the words, in an array named badwords. Go into your on_message() function, and add this:

@client.event
async def on_message(ctx, message):
    msg = message.content
    for word in badwords:
        if word in msg:
            await message.delete()
            await ctx.send("Dont use that word!")
    await ctx.process_message(message)
like image 173
IPSDSILVA Avatar answered Oct 30 '25 01:10

IPSDSILVA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!