how can i fix this script for deleting bad words in chats

64 Views Asked by At
words_to_filter = ["badword1", "badword2", "badword3"]

@bot.event
async def on_message(message):
    print(f"on_message event triggered")  # Add this line
    if message.author == bot.user:
        return

    for word in words_to_filter:
        if word in message.content:
            print(f"Bad word found: {word}") # check on_message event
            await message.delete() #message delete
            await message.channel.send(f"{message.author.mention}, դուք օգտագործել եք արգելված բառ ձեր հաղրոդագրությունում") # after deleting message send message
            return
        else:
            print('Falseee') # if script not working print 'Falseee'
            return
        
    await bot.process_commands(message)

terminal output:

terminal output

I tried several options to check if all events are working

the function of the code is to remove bad words in the message after running the code, when I send any word in the text channel, the on_message event works, but the function itself is not executed

2

There are 2 best solutions below

0
Arunbh Yashaswi On

The return in for is not needed and letting your code exit once it check the first word in your list as its going into else block

words_to_filter = ["badword1", "badword2", "badword3"]

@bot.event
async def on_message(message):
    print(f"on_message event triggered")
    if message.author == bot.user:
        return

    for word in words_to_filter:
        if word in message.content:
            print(f"Bad word found: {word}")
            await message.delete()
            await message.channel.send(f"{message.author.mention}, դուք օգտագործել եք արգելված բառ ձեր հաղրոդագրությունում")
            return

    await bot.process_commands(message)
0
TheHungryCub On

The return statement inside the loop will terminate the loop after checking the first word.

Your code looks fine, just make one small change. Remove 'else' and 'return' from below snippet.

else:
            print('Falseee') # if script not working print 'Falseee'
            return
    await bot.process_commands(message)

Your code should be like :

    print('Falseee') # if script not working print 'Falseee'
    
await bot.process_commands(message)