filter out swear/curse words (abusive language) using an array

Viewed 313

I’m making a nextcord bot and I want to implement a filter for swear/curse words. I want all those words in an array which is assigned to a variable (i.E. badwords). My problem is that it says "invalid syntax". Can you help me with this?

@commands.Cog.listener()
async def on_message(self, message):
    if "https://discord" in message.content:
        embed = nextcord.Embed(title="**Tu n'as pas le droit d'envoyer des liens d'invitation**")
        log = self.bot.get_channel(916007109424984115)
        logembed = nextcord.Embed(title="Link", description="Quelqu'un a envoyé un lien discord")
        await message.delete()
        await log.send(embed=logembed)
        await message.channel.send(embed=embed)
    badwords = ["list of badwords"]
    elif badwords in message.content:
        log = self.bot.get_channel()
        await message.delete()
        await message.channel.send(embed=embed)

I didn’t do the embedding, neither the log-system for the swear/curse-words.

3 Answers

you have to iterate over the elements of your list. This can be done this way:

@commands.Cog.listener()
async def on_message(self, message):
    badwords = ["list of badwords"] #move list declaration over here
    if "https://discord" in message.content:
        embed = nextcord.Embed(title="**Tu n'as pas le droit d'envoyer des liens d'invitation**")
        log = self.bot.get_channel(916007109424984115)
        logembed = nextcord.Embed(title="Link", description="Quelqu'un a envoyé un lien discord")
        await message.delete()
        await log.send(embed=logembed)
        await message.channel.send(embed=embed)
    else:
        if any(badword in message.content for badword in badwords): # check if any badword in message.content 
            log = self.bot.get_channel()
            await message.delete()
            await message.channel.send(embed=embed)
            break # Exit the loop as we don't need to go further

you have 2 mistakes in your code

you are iterating a list over your message.content and you are declaring badwords before your elif statement which is causing if statement to break, so declare it before start of if statement

message = 'curse'

badwords = ['curse'] #declare badwords here
if False:
    pass
elif message in badwords: # iterate your message.content over the badwords list
    print(True)

enter image description here

is the invalid syntax caused by async def? in that case you might want to check your python version is >3.6

Related