Ziepo Ziepo - 4 months ago 77
Python Question

Discord Bot written in Python minigame while loop not working

This piece of code i wrote for a Discord Bot is not working and i would like to find out why and how to make it work and maybe different methods.

def russian_roulette(author, message):
game_active = True
client.send_message(message.channel, "Russian Roulette game started.6 chambers. 1 loaded.\nType $spin to spin the chamber.\nType $pull to pull the trigger.")
while game_active == True:
if message.content.startswith('$spin'):
chamber = randint(1,6)
client.send_message(message.channel, "%s spins the chambers." % author)
if message.content.startswith('$pull'):
if chamber == 1:
client.send_message(message.channel, "%s pulled the trigger and was not lucky. R.I.P." % author)
game_active = False
else:
client.send_message(message.channel, "%s pulled the trigger and nothing happened." % author)

Answer

I'm assuming that you're using this API wrapper for discord.

In that case, what you'll need to do is create a function with the decorator client.event so that it responds to messages properly. Like so:

@client.event
async def on_message(message):
    if message.content.startswith('$spin'):
            chamber = randint(1,6)
            client.send_message(message.channel, "%s spins the chambers." % author)
    if message.content.startswith('$pull'):
        if chamber == 1:
            client.send_message(message.channel, "%s pulled the trigger and was not lucky. R.I.P." % message.author)
            game_active = False
        else:
            client.send_message(message.channel, "%s pulled the trigger and nothing happened." % message.author)

This function will be called every time your bot receives a new message, rather than in your code in which the function will only be called once.

Note that I've never used this API before and am simply reading the documentation and examples - this could be incorrect.

Comments