import logging from datetime import datetime import pytz from bson import json_util from libbot.pyrogram.classes import PyroClient from classes.enums import GarbageType from classes.location import Location from classes.pyrouser import PyroUser from modules.database import col_users from modules.database_api import col_entries logger = logging.getLogger(__name__) async def remind(app: PyroClient) -> None: utcnow = datetime.now(pytz.utc) logger.debug("Performing reminder lookup for %s (UTCNOW)", utcnow) users = await col_users.find( {"time_hour": utcnow.hour, "time_minute": utcnow.minute} ).to_list() logger.debug( "Found following reminders for %s (UTC NOW): %s", utcnow, json_util.dumps(users, indent=None), ) for user_db in users: logger.debug("Processing user %s...", json_util.dumps(user_db, indent=None)) user = await PyroUser.from_dict(**user_db) if not user.enabled or user.location is None: continue try: location: Location = await app.get_location(user.location.id) # type: ignore except ValueError: logger.warning("Skipping reminder for %s due to invalid location", user.id) continue user_date = user.get_reminder_date().replace(tzinfo=None) entries = await col_entries.find( { "locations": location.id, "date": user_date, } ).to_list() logger.info("Entries of %s for %s: %s", user.id, user_date, entries) for entry in entries: logger.debug( "Sending %s notification about %s", user.id, json_util.dumps(entry, indent=None), ) try: garbage_type = app._( str(GarbageType(entry["garbage_type"]).value), "garbage_types", locale=user.locale, ) garbage_date = datetime.strftime( entry["date"], app._("date", "formats", locale=user.locale) ) await app.send_message( user.id, app._("reminder", "messages", locale=user.locale).format( type=garbage_type, date=garbage_date ), ) except Exception as exc: logger.warning( "Could not send a notification to %s due to %s", user.id, exc ) continue