I’m trying to create a Discord bot that responds with a message each time someone posts in the channel. However, something is wrong with my code because the bot starts sending endless messages instead of just one response. Here’s what I have so far:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready to go")
await client.change_presence(status=discord.Status.online, activity=discord.Game('!help'))
@client.event
async def on_message(msg):
keep_going = True
while keep_going:
await msg.channel.send(f"some text here")
break
client.run("TOKEN_HIDDEN")
The bot connects fine but when I type anything, it goes into some kind of spam mode. What am I doing wrong here? I just want it to send one reply per message.
Your bot’s stuck in a feedback loop because it responds to its own messages. Here’s what happens: you send a message → bot sees it and replies → bot sees its own reply as a new message → replies again → infinite loop. I made this same mistake when I started with Discord.py. Just add if msg.author == client.user: return at the top of your on_message function so the bot ignores itself. And ditch that while loop - it’s doing nothing since on_message already runs once per message.
dude your while loop is completely unnecessary here. just remove the while keep_going: and break lines and keep only await msg.channel.send(f"some text here"). the on_message event already triggers once per message so no need for loops at all
Your bot’s stuck in an infinite loop because it’s responding to its own messages. Every time you use msg.channel.send(), it triggers the on_message event again, causing the bot to keep talking to itself. You can fix this by adding if msg.author.bot: return at the start of your on_message function to ignore messages from bots. Additionally, the while loop is unnecessary since you break immediately; simply remove it to streamline your code. The solution is to check if the author is a bot first, and then respond only to messages from actual users.