From b67f35a6aecdaaed5a77cff3f7c03bcc8ff822e5 Mon Sep 17 00:00:00 2001 From: Nathan Woodburn Date: Tue, 14 Nov 2023 13:05:41 +1100 Subject: [PATCH] feat: Add reminders --- .gitignore | 2 ++ bot.py | 15 +++++++++++++++ timeparser.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 timeparser.py diff --git a/.gitignore b/.gitignore index 963a057..9a6d587 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .env + +__pycache__/ diff --git a/bot.py b/bot.py index a577af7..a5d659d 100644 --- a/bot.py +++ b/bot.py @@ -14,6 +14,8 @@ from cryptography.hazmat.backends import default_backend import datetime from apscheduler.schedulers.asyncio import AsyncIOScheduler import chatai +from timeparser import parse_time +import asyncio @@ -453,6 +455,19 @@ async def ai(ctx, message: str): prompt = prompt + "Message: " + message + "\n" await ctx.response.send_message(chatai.chat(prompt)) +@tree.command(name="remindme", description="Remind me") +async def remindme(ctx, when: str, message: str): + + time_delta = parse_time(when) + + if time_delta is not None: + # Schedule the reminder + await ctx.response.send_message("Reminding you in " + when + " to " + message,ephemeral=True) + await asyncio.sleep(time_delta.total_seconds()) + await ctx.user.send("Reminder: " + message) + else: + await ctx.response.send_message("Invalid time format. Please use something like `1d 3h` or `4hr`.",ephemeral=True) + # When the bot is ready @client.event async def on_ready(): diff --git a/timeparser.py b/timeparser.py new file mode 100644 index 0000000..52246bd --- /dev/null +++ b/timeparser.py @@ -0,0 +1,33 @@ +import datetime +import re + +def parse_time(time_str): + # Parse the time string and return a timedelta + try: + time_components = re.findall(r'(\d+)\s*([dDhHrRmMsS]?)', time_str) + total_seconds = 0 + for value, unit in time_components: + value = int(value) + if unit.lower() in ('d', 'day', 'days'): + total_seconds += value * 86400 # seconds in a day + elif unit.lower() in ('h', 'hr', 'hour', 'hours'): + total_seconds += value * 3600 # seconds in an hour + elif unit.lower() in ('m', 'min', 'minute', 'minutes'): + total_seconds += value * 60 # seconds in a minute + elif unit.lower() in ('s', 'sec', 'second', 'seconds'): + total_seconds += value + return datetime.timedelta(seconds=total_seconds) + except ValueError: + return None + +if __name__ == '__main__': + print(parse_time('1d 2h 3m 4s')) + print(parse_time('1d2h3m4s')) + print(parse_time('1d 2h 3m')) + print(parse_time('1d 2h')) + print(parse_time('1d')) + print(parse_time('1h 2m 3s')) + print(parse_time('1h 2m')) + print(parse_time('1h')) + print(parse_time('1m 2s')) + print(parse_time('1m')) \ No newline at end of file