I’m working on a Discord bot in Python and trying to create a simple gambling game. The problem is that my while loop doesn’t seem to be responding to user commands properly. The bot sends the initial message but then doesn’t react when users type the commands.
def luck_game(player, msg):
running = True
bot.send_message(msg.channel, "Luck Game initiated! 6 slots available, 1 is dangerous.\nUse $rotate to shuffle slots.\nUse $trigger to test your luck.")
while running:
if msg.content.startswith('$rotate'):
slot = randint(1,6)
bot.send_message(msg.channel, "%s rotates the cylinder." % player)
if msg.content.startswith('$trigger'):
if slot == 1:
bot.send_message(msg.channel, "%s pressed the button and lost! Game over." % player)
running = False
else:
bot.send_message(msg.channel, "%s pressed the button safely." % player)
Can anyone help me understand why this isn’t working and suggest better approaches?
You’re treating Discord bot interactions like console input, but they’re event-driven. Your while loop blocks the bot from processing new messages. When you get a message event, that message object is static - it won’t change its content while you’re looping through it. Set up your bot to maintain game sessions between message events instead. Use a global dictionary to track active games by user ID, then handle each command as a separate message event. When someone uses $rotate or $trigger, check if they’ve got an active game session and update the state. This keeps the bot responsive to all users while managing individual game states.
You’re stuck in an infinite loop checking the same message over and over. Once a message comes in, it doesn’t change - so your while loop either runs the same command forever or sits there doing nothing. Discord bots don’t work that way. They listen for new messages asynchronously, not loop through old ones. Set up a game state system instead. When someone starts the game, save their game state in a dictionary or class. Then handle $rotate and $trigger commands in your main message handler by checking if that user has an active game. Each new message gets processed individually - no loops needed. The bot framework already handles listening for messages, so just respond to commands as they come in.
yeah, the problem is ur msg object doesn’t change in the loop. discord.py doesn’t work like that - ditch the while loop entirely and use event decorators like @bot.event or @bot.command instead. handle commands in separate functions that trigger when new messages come in.