woodburn-bot/tools.py

81 lines
2.6 KiB
Python
Raw Normal View History

2023-11-14 13:05:41 +11:00
import datetime
import re
2023-11-14 14:01:29 +11:00
import discord
2023-11-14 13:05:41 +11:00
2023-11-14 13:15:56 +11:00
REMINDERS_FILE_PATH = '/mnt/reminders.txt'
2023-11-14 13:05:41 +11:00
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
2023-11-14 13:15:56 +11:00
def read_reminders():
try:
with open(REMINDERS_FILE_PATH, 'r') as file:
reminders = [line.strip().split(',') for line in file.readlines()]
2023-11-14 13:26:24 +11:00
# Remove empty lines
reminders = [r for r in reminders if len(r) == 3]
if len(reminders) == 0:
return []
2023-11-14 13:33:59 +11:00
return [{
'user_id': r[0],
'time': r[1],
'text': r[2]
} for r in reminders]
2023-11-14 13:15:56 +11:00
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)
2023-11-14 14:01:29 +11:00
def embed(title, description):
embed = discord.Embed(
title=title,
description=description,
color=discord.Color.dark_purple()
)
# Set a footer for the embed
embed.set_footer(text='Powered by Nathan.Woodburn/')
return embed
2023-11-14 13:05:41 +11:00
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'))
2023-11-14 13:33:59 +11:00
print(parse_time('1m'))
print(read_reminders())
store_reminder(123, datetime.datetime.now(), 'test')
print(read_reminders())