Why Does My Discord Bot Code Go Into an Infinite Loop?
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
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.
Reply to this answer
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
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
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.
gasket.06: I see what you mean! Iโll try switching to a for loop and see how it goes.