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?
4 Answers
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.
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.
Oh, that makes sense! I didn't think about the timing issues with async. I’ll test that out.
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.
Thanks for the tip! It’s helpful to know I can manage this more easily without the while loop.
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.
I see what you mean! I’ll try switching to a for loop and see how it goes.

Exactly! I didn’t realize that the function was being called repeatedly like that. I'll make that adjustment. Thanks!