1
votes

I'm making a bot that, when it detects you are using a banned word, it will delete your message. Simple enough but, when I do that. The on_message function is repeating itself. I don't know why but I hope you can answer my question

@client.event
async def on_message(msg):
    contents = msg.content.split(" ")
    for word in contents:
        if word.lower() in chat_filter: #ChatFilter is a list of words that cannot be used
            try:
                await msg.delete()
                await msg.channel.send("**YOU ARE NOT ALLOWED TO USE THIS WORD!!!**")
            except discord.errors.NotFound:
                return
1
can you elaborate on what it means repeats itself ?user10417531
@reportgunner well, I was following a youtube video. For him when he did the code, it did it once for him. I copied his code and it keeps repeating itself. I think its the difference with the versions and stuffTheBigBro122
I asked since I have no idea if you mean "repeats itself" as in "runs in a loop indefinitely" or "messages are duplicated" (i.e. there are two responses for each message) or "messages multiply exponentially".user10417531
@reportgunner yes. The messages are repeating itself even though I don't want it to happen. Any solution? I'll give you the link to the video to show you what I mean youtube.com/watch?v=-2b1JUwEF3oTheBigBro122
Is one of the words in chat_filter also in the message? You can add a check to ignore your own messages: if msg.author == client.user: returnPatrick Haugh

1 Answers

1
votes

You're looping over each word of the message and sending a response for each of those words that are also in chat_filter. Instead, send a single message if any of the words are in the banned list:

@client.event
async def on_message(msg):
    contents = msg.content.split(" ")
    if any(word in chat_filter for word in contents):
        try:
            await msg.delete()
            await msg.channel.send("**YOU ARE NOT ALLOWED TO USE THIS WORD!!!**")
        except discord.errors.NotFound:
            return