EpyJojo
EpyJojo

Reputation: 3

Break Loop with Command

In my Python - Discord Bot, I wanted to create a command, which causes a loop to run. The loop should stop when I enter a second command. So roughly said:

@client.event
async def on_message(message):
    if message.content.startswith("!C1"):
        while True:
            if message.content.startswith("!C2"):
                break
            else:
                await client.send_message(client.get_channel(ID), "Loopstuff")
                await asyncio.sleep(10)

So it posts every 10 seconds "Loopstuff" in a Channel and stops, when I enter !C2

But I cant figure it out on my own .-.

Upvotes: 0

Views: 2201

Answers (2)

bezet
bezet

Reputation: 820

Inside your on_message function message content won't change. So another message will cause on_message to be called one more time. You need a synchronisation method ie. global variable or class member variable which will be changed when !C2 message arrives.

keepLooping = False

@client.event
async def on_message(message):
    global keepLooping
    if message.content.startswith("!C1"):
        keepLooping = True
        while keepLooping:
            await client.send_message(client.get_channel(ID), "Loopstuff")
            await asyncio.sleep(10)
    elif message.content.startswith("!C2"):
        keepLooping = False

As a side note it's good to provide a standalone example not just a single function.

Upvotes: 1

MasterChef
MasterChef

Reputation: 55

(Without trying for myself) Try:

while not message.content.startswith("!C2")

For the While clause, followed by the contents of your else clause.

Upvotes: 0

Related Questions