Why does my Discord.py Bot spam (and add numbers) in the chat?

Question:

I am writing a discord bot which job is simply adding, subtracting and suming up numbers. Everything works fine exept when you type "-1" (to subtract a number from the sum) it will spam "-1 was subtracted from your apples. You got (never ending numbers) apples." So it will say that It’s subtracting -1 but at the same time it spams it and also adds numbers to it.

Thanks a lot in advance!


intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

@client.event 
async def on_ready():
    print(f"{client.user} is connected to Discord!")

sum = 0

@client.event
async def on_message(message):
    global sum
    if message.content.startswith("+1"):
        num = int(message.content.split(" ")[0])
        sum += num
        await message.channel.send(f"{num} was added to your apples, you got {sum} apples.")
    elif message.content.startswith("-1"):
        num = int(message.content.split(" ")[0])
        sum -= num
        await message.channel.send(f"{num} was subtracted from your apples, you got {sum} apples.")
    elif message.content.startswith("apples"):
        await message.channel.send(f"You have {sum} apples.")

client.run('token')``
`
Asked By: wtfluciana

||

Answers:

As Samwise pointed out, your bot is responding to itself. You need to add the following to your on_message function to prevent it triggering for itself. From the quickstart docs.

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # rest of your on_message function
Answered By: ESloman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.