feat: Store reminders persistently
All checks were successful
Build Docker / Build Docker (push) Successful in 17s

This commit is contained in:
Nathan Woodburn 2023-11-14 13:15:56 +11:00
parent b67f35a6ae
commit 7085f1ac1a
Signed by: nathanwoodburn
GPG Key ID: 203B000478AD0EF1
2 changed files with 45 additions and 5 deletions

25
bot.py
View File

@ -14,7 +14,7 @@ from cryptography.hazmat.backends import default_backend
import datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
import chatai import chatai
from timeparser import parse_time from timeparser import parse_time, read_reminders, store_reminder, write_reminders
import asyncio import asyncio
@ -456,18 +456,32 @@ async def ai(ctx, message: str):
await ctx.response.send_message(chatai.chat(prompt)) await ctx.response.send_message(chatai.chat(prompt))
@tree.command(name="remindme", description="Remind me") @tree.command(name="remindme", description="Remind me")
async def remindme(ctx, when: str, message: str): async def remindme(ctx, when: str, reminder: str):
time_delta = parse_time(when) time_delta = parse_time(when)
if time_delta is not None: if time_delta is not None:
# Schedule the reminder # Schedule the reminder
await ctx.response.send_message("Reminding you in " + when + " to " + message,ephemeral=True) reminder_time = datetime.datetime.now() + time_delta
await asyncio.sleep(time_delta.total_seconds()) store_reminder(ctx.author.id, reminder_time, reminder)
await ctx.user.send("Reminder: " + message) await ctx.response.send_message("I've set a reminder for you in " + when + ".\n" + reminder,ephemeral=True)
else: else:
await ctx.response.send_message("Invalid time format. Please use something like `1d 3h` or `4hr`.",ephemeral=True) await ctx.response.send_message("Invalid time format. Please use something like `1d 3h` or `4hr`.",ephemeral=True)
async def check_reminders():
now = datetime.datetime.now()
reminders = read_reminders()
for reminder in reminders[:]:
reminder_time = datetime.datetime.strptime(reminder['time'], "%Y-%m-%d %H:%M:%S")
if reminder_time <= now:
user = await client.fetch_user(int(reminder['user_id']))
await user.send("G'day,\nI need to remind you of:\n" + reminder['text'])
reminders.remove(reminder)
write_reminders(reminders)
# When the bot is ready # When the bot is ready
@client.event @client.event
async def on_ready(): async def on_ready():
@ -481,6 +495,7 @@ async def on_ready():
# Every 12 hours check for SSL expiry # Every 12 hours check for SSL expiry
scheduler = AsyncIOScheduler() scheduler = AsyncIOScheduler()
scheduler.add_job(checkForSSLExpiry, 'interval', hours=12) scheduler.add_job(checkForSSLExpiry, 'interval', hours=12)
scheduler.add_job(check_reminders, 'interval', seconds=30)
scheduler.start() scheduler.start()
client.run(TOKEN) client.run(TOKEN)

View File

@ -1,6 +1,8 @@
import datetime import datetime
import re import re
REMINDERS_FILE_PATH = '/mnt/reminders.txt'
def parse_time(time_str): def parse_time(time_str):
# Parse the time string and return a timedelta # Parse the time string and return a timedelta
try: try:
@ -20,6 +22,29 @@ def parse_time(time_str):
except ValueError: except ValueError:
return None return None
def read_reminders():
try:
with open(REMINDERS_FILE_PATH, 'r') as file:
reminders = [line.strip().split(',') for line in file.readlines()]
return [{'user_id': r[0], 'time': r[2], 'text': r[3]} for r in reminders]
except FileNotFoundError:
return []
def write_reminders(reminders):
with open(REMINDERS_FILE_PATH, 'w') as file:
for reminder in reminders:
file.write(f"{reminder['user_id']},{reminder['time']},{reminder['text']}\n")
def store_reminder(user_id, reminder_time, reminder_text):
reminders = read_reminders()
reminders.append({
'user_id': str(user_id),
'time': reminder_time.strftime("%Y-%m-%d %H:%M:%S"),
'text': reminder_text
})
write_reminders(reminders)
if __name__ == '__main__': if __name__ == '__main__':
print(parse_time('1d 2h 3m 4s')) print(parse_time('1d 2h 3m 4s'))
print(parse_time('1d2h3m4s')) print(parse_time('1d2h3m4s'))