Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
reminder: flesh initial reminders
kaiowa/reminder.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/kaiowa/reminder.py b/kaiowa/reminder.py new file mode 100644 index 0000000000000000000000000000000000000000..81e828e7ecb549fad4792610abfd7d99873923a7 --- /dev/null +++ b/kaiowa/reminder.py @@ -0,0 +1,55 @@ +import json +import asyncio + +from collections import namedtuple +from datetime import datetime +from parsedatetime import Calendar +from pytz import timezone + +Reminder = namedtuple("Reminder", ["what", "when", "who"]) +UTC = timezone("UTC") +local = timezone("Brazil/East") + +async def want_reminder(redis, reminders, msg, what=None, when=None): + if not what or not when: + return + + cal = Calendar() + now = datetime.utcnow().replace(tzinfo=UTC).astimezone(local) + when, _ = cal.parseDT(datetimeString=when, sourceTime=now, tzinfo=local) + + reminder = Reminder(what=what, who=msg.sender.name, when=when) + reminders.append(reminder) + save_reminders(redis, reminders) + await msg.reply(f"Ok, vou te lembrar em {when}") + +def encode_reminder(reminder): + return { + "what": reminder.what, + "when": reminder.when.timestamp(), + "who": reminder.who + } + +def save_reminders(redis, reminders): + redis.set("reminders", json.dumps([encode_reminder(r) for r in reminders])) + +def decode_reminder(obj): + obj["when"] = datetime.fromtimestamp(obj["when"], tz=local) + return Reminder(**obj) + +def load_reminders(redis): + reminders = redis.get("reminders") + if not reminders: + return [] + + return [decode_reminder(r) for r in json.loads(reminders.decode())] + +async def check_due_reminders(redis, reminders, bot): + now = datetime.utcnow().replace(tzinfo=UTC).astimezone(local) + + for r in reminders: + if r.when <= now: + await bot.message("#eletrotupiniquim", f"{r.who}: Lembrete {r.what}") + reminders.remove(r) + + save_reminders(redis, reminders)