Benjamin Jones
Benjamin Jones

Reputation: 103

How to stop multiple countdowns running at once in Python Discord Bot?

Here is my code:

import discord
import asyncio

async def ex(args, message, client, invoke):

  await client.send_message(message.channel, "5 Minutes")
  await asyncio.sleep(60)
  await client.send_message(message.channel, "4 Minutes")
  await asyncio.sleep(60)
  await client.send_message(message.channel, "3 Minutes")
  await asyncio.sleep(60)
  await client.send_message(message.channel, "2 Minutes")
  await asyncio.sleep(60)
  await client.send_message(message.channel, "1 Minutes")
  await asyncio.sleep(30)
  await client.send_message(message.channel, "30 Seconds")
  await asyncio.sleep(15)
  await client.send_message(message.channel, "15 Seconds")
  await asyncio.sleep(10)
  await client.send_message(message.channel, "5 Seconds")


#Already Running Message
#await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description="Countdown already running, please try again later!"))

I want to make it so the countdown can only be running one at a time. Right now you can have as many countdowns as you want on the go.

Upvotes: 2

Views: 108

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60954

You could have a global variable the tracks whether or not a counter is in progress. Something like:

counter_channel = None

async def ex(args, message, client, invoke):
    global counter_channel
    if counter_channel is not None:
        await client.send_message(message.channel, "There is a counter in {}".format(counter_channel.mention))
        return
    counter_channel = message.channel

    await client.send_message(message.channel, "5 Minutes")
    await asyncio.sleep(60)
    ...
    await client.send_message(message.channel, "5 Seconds")
    await asyncio.sleep(5)

    counter_channel = None

You can also have them on a per server or per channel basis by maintaining a global set of channel or server ids.

Upvotes: 1

Related Questions