Reputation: 45
I was wondering how I can make a time conversion for a reminder command so doing 1s converts to 1 second 1m converts to 1 minute and 1h converts to 1 hour
@client.command(aliases=["reminder"])
async def remind(ctx, remindertime, *, msg):
seconds=seconds % (24 * 3600)
hour=seconds // 3600
seconds %= 3600
minutes=seconds // 60
seconds %= 60
s=seconds
h=hour
m=minutes
await asyncio.sleep(remindertime)
await ctx.send(f"{ctx.author.mention} You were going to: {msg} and asked me to remind you.")
Upvotes: 0
Views: 489
Reputation: 1037
You can use regular expressions to check string is a time string:
import re
TIME_REGEX = re.compile("([0-9]+)(d|h|m|s)?")
MULTIPLER = {
"d": 86400,
"h": 3600,
"m": 60,
"s": 1,
"None": 1 #if they type "30", this will be 30 seconds"
}
match = TIME_REGEX.match(time_string)
if not match:
return await ctx.send("Please enter a valid time.")
seconds = int(match.groups()[0]) * MULTIPLER.get(str(match.groups()[1]))
Upvotes: 1
Reputation: 831
The way you are trying to do here is a difficult way. This would do nothing but consume time and confuse you.
The way it is done usually is extremely easy.
You create a dictionary and then add the time conversion values in there. Then create a variable which converts time as per the requirement. Don't Worry I would be explaining it just now. It would clear your doubt. :)
This would be the reminder function.
@client.command(aliases=["reminder"])
async def remind(ctx, time, *, msg):
This dictionary will play the major role in conversion of the time for the execution. The KEYS of this dictionary will be the time unit and the VALUES will be the number in seconds.
time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
This will be used to convert our time to seconds and use in the sleep() function.
This variable will be the time in seconds according to the value entered in the command.
remindertime = int(time[0]) * time_conversion[time[-1]]
This first takes the number value attached to the time input and multiply it with the integer VALUE from the dictionary.
Now when we use this time, our command would look like:
@client.command(aliases=["reminder"])
async def remind(ctx, time, *, msg):
time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
remindertime = int(time[0]) * time_conversion[time[-1]]
await asyncio.sleep(remindertime)
await ctx.send(f"{ctx.author.mention} You were going to: {msg} and asked me to remind you.")
So, this was the way you could actually use the time in the command.
I was glad to help. If you still have any difficulty in anything I explained, please free to ask me in the comments. :)
Thank You! :D
Upvotes: 0