CELLSecret
CELLSecret

Reputation: 141

How to set a timer in discord.py while enabling other codes?

I want to set a time for, say 30 seconds, but having other commands available during the timer period. I cannot do time.sleep(30) since that will disable the ability for the bot to respond to other commands. Is there a way for a bot to receive a message and respond after 30 seconds while the bot is able to receive and perform other commands? A possible chat log may be below:

user: !timer 30
bot:  Timer set for 30 seconds
user: Hello
bot:  Hi
bot:  Your timer of 30 seconds has ended. (after 30 seconds are up)

Upvotes: 0

Views: 1327

Answers (2)

NikoX
NikoX

Reputation: 127

You can simply use asyncio library. asyncio.sleep() works in background and doesn't block other functions. Learn more about coroutines.

@client.command()
async def timer(ctx, seconds):
    try:
        seconds= int(seconds)
    except ValueError:
        await ctx.send("Please provide a valid time")
        return
    await ctx.send(f"Your timer has started for {seconds} seconds.")
    await asyncio.sleep(seconds) # This is the sleep method.
    await ctx.send("Your timer ended!")
    return

Upvotes: 1

ahmed
ahmed

Reputation: 98

You can use timer objects in python, example:

import threading
def do_something():
    print("do something")
    #or tell the user that his time ended

timer = threading.Timer(30, do_something)
timer.start() #you would probably want to start the timer whenever the user types the command

you can find some reference here

Upvotes: 1

Related Questions