Raphiel
Raphiel

Reputation: 388

Discord Python Rewrite Question - asyncio.sleep()

Is it possible to make the

asyncio.sleep()

sleeps for 60seconds if the inputed time is 1m or 60min if the inputted time is 1h or if the inputted time is 24hour and it will sleep for 1day, if it is, i will need a example because i need it for my giveaway code.

Upvotes: 0

Views: 192

Answers (2)

Jawad
Jawad

Reputation: 2041

asyncio.sleep() will only take seconds, you can write a function for this that converts inputted time into seconds.

import re
from datetime import timedelta


time_units = {'s': 'seconds', 'm': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'}


def to_seconds(s):
    return int(timedelta(**{
        time_units.get(m.group('unit').lower(), 'seconds'): int(m.group('val'))
        for m in re.finditer(r'(?P<val>\d+)(?P<unit>[smhdw]?)', s, flags=re.I)
    }).total_seconds())


@client.command()
async def giveaway(ctx, *, time):
    print(f"{ctx.message.content} --> {to_seconds(time)}")

Output:

>giveaway 1w --> 604800
>giveaway 30s --> 30
>giveaway 1d --> 86400
>giveaway 1h 25m --> 5100
>giveaway 5m 30s --> 330

Upvotes: 1

blami
blami

Reputation: 7411

asyncio.sleep() always takes delay in seconds - see documentation. You can easily write a function that will take any amount time in any unit and converts it to seconds. Then you just pass that number to asyncio.sleep().

Upvotes: 0

Related Questions