Why Does My Discord Bot Code Go Into an Infinite Loop?

April 9, 2026 4 answers
Asked by index-of-refraction
I'm a second-year college student new to programming, and I've been experimenting with building a Discord bot using Python. I'm trying to make it respond to messages, but I'm running into a problem where my bot gets stuck in an infinite loop. When I send a message, it should respond with "You are a human" and follow up with "You are a bot" three times. Instead, it just keeps sending "You are a bot" over and over again. Here's the code that's causing the issue: ```python count = 1 @client.event async def on_message(message): global count if not message.author.bot: await message.channel.send("You are a human") if message.author.bot: while (count <= 3): await message.channel.send("You are a bot") count += 1 ``` Can someone help me understand why this is happening?

Answers

_7 cookie cutters
Every time your bot sends "You are a bot", it triggers `on_message` again, which then sends more messages, creating a never-ending cycle. Instead of a while loop, consider using a for loop, or at least ensure you have a guard condition to break out of the recursive calls after three messages.

gasket.06: I see what you mean! Iโ€™ll try switching to a for loop and see how it goes.

Reply to this answer
24C_incubate
The core issue here is that your bot's messages trigger the `on_message` event, affecting the count increment timing. Using an if statement instead of a while loop might also help because you can check the count conditionally without creating a continuous loop.

__archival: Thanks for the tip! Itโ€™s helpful to know I can manage this more easily without the while loop.

Reply to this answer
barn owl census
You might be facing the problem because when you send a message, it invokes `on_message` again before `count` has a chance to increment. If you want your code to work properly, try incrementing `count` before sending the message. That way, you make sure the loop logic behaves as intended.

PRACTICE.ROOM.B: Oh, that makes sense! I didn't think about the timing issues with async. Iโ€™ll test that out.

Reply to this answer
gallery.wall.2
It seems like every time your bot sends a message, it triggers the `on_message` function again, causing it to run the loop repeatedly with no end. You might want to add a check to ignore messages sent by your own bot by checking the message authorโ€™s ID. That should help break the cycle.

5km_visibility: Exactly! I didnโ€™t realize that the function was being called repeatedly like that. I'll make that adjustment. Thanks!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions