From 11c84eae82d24bb02594ff1aab640eba8623f97e Mon Sep 17 00:00:00 2001 From: Vladless Date: Sun, 1 Dec 2024 22:24:00 +0300 Subject: [PATCH] notification inactive users --- database.py | 33 +++++++++++++-------------------- handlers/notifications.py | 11 ++++------- 2 files changed, 17 insertions(+), 27 deletions(-) diff --git a/database.py b/database.py index 1585824f..43708f2f 100644 --- a/database.py +++ b/database.py @@ -1133,38 +1133,27 @@ async def check_notification_time(tg_id: int, notification_type: str, hours: int Raises: Exception: В случае ошибки при проверке времени уведомления """ + conn = None try: - # Если сессия не передана, создаем новое подключение - if session is None: - conn = await asyncpg.connect(DATABASE_URL) - else: - conn = session + conn = session if session is not None else await asyncpg.connect(DATABASE_URL) - result = await conn.fetchrow( + result = await conn.fetchval( """ SELECT CASE - WHEN last_notification_time IS NULL THEN TRUE - WHEN NOW() - last_notification_time > INTERVAL '$1 hours' THEN TRUE + WHEN MAX(last_notification_time) IS NULL THEN TRUE + WHEN NOW() - MAX(last_notification_time) > ($1 * INTERVAL '1 hour') THEN TRUE ELSE FALSE - END as can_notify + END AS can_notify FROM notifications WHERE tg_id = $2 AND notification_type = $3 """, - hours, # Убираем преобразование в строку + hours, tg_id, notification_type, ) - # Если сессия не была передана, закрываем подключение - if session is None and conn: - await conn.close() - - # Если записи нет, значит уведомление можно отправить - if result is None: - return True - - can_notify = result['can_notify'] + can_notify = result if result is not None else True logger.info( f"Проверка уведомления типа {notification_type} для пользователя {tg_id}: {'можно отправить' if can_notify else 'слишком рано'}" @@ -1174,4 +1163,8 @@ async def check_notification_time(tg_id: int, notification_type: str, hours: int except Exception as e: logger.error(f"Ошибка при проверке времени уведомления для пользователя {tg_id}: {e}") - return True # По умолчанию разрешаем отправку уведомления + return False + + finally: + if conn is not None and session is None: + await conn.close() diff --git a/handlers/notifications.py b/handlers/notifications.py index 6a8e564d..80f58de4 100644 --- a/handlers/notifications.py +++ b/handlers/notifications.py @@ -34,9 +34,8 @@ async def notify_expiring_keys(bot: Bot): logger.info("Начало обработки уведомлений.") - # TODO - # await notify_inactive_trial_users(bot, conn) - # await asyncio.sleep(1) + await notify_inactive_trial_users(bot, conn) + await asyncio.sleep(1) await check_online_users() await asyncio.sleep(1) await notify_10h_keys(bot, conn, current_time, threshold_time_10h) @@ -229,9 +228,8 @@ async def notify_inactive_trial_users(bot: Bot, conn: asyncpg.Connection): username = user.get('username', 'Пользователь') try: - # Проверяем, можно ли отправить уведомление can_notify = await check_notification_time( - tg_id, 'inactive_trial', hours=24, session=conn # Уведомление не чаще, чем раз в 24 часа + tg_id, 'inactive_trial', hours=24, session=conn ) if can_notify and not await is_bot_blocked(bot, tg_id): @@ -252,13 +250,12 @@ async def notify_inactive_trial_users(bot: Bot, conn: asyncpg.Connection): await bot.send_message(tg_id, message, reply_markup=keyboard) logger.info(f"Отправлено уведомление неактивному пользователю {tg_id}.") - # Добавляем запись о notification await add_notification(tg_id, 'inactive_trial', session=conn) except Exception as e: logger.error(f"Ошибка при отправке уведомления неактивному пользователю {tg_id}: {e}") - await asyncio.sleep(1) # Небольшая задержка между отправками + await asyncio.sleep(1) async def handle_expired_keys(bot: Bot, conn: asyncpg.Connection, current_time: float):