Удаление ушедших пользователей из БД через 14 дней.

This commit is contained in:
Kirill Kirilenko 2026-01-08 22:10:49 +03:00
parent 50c984cfd7
commit aea6782a8c
2 changed files with 47 additions and 0 deletions

View file

@ -3,6 +3,8 @@ import traceback
from asyncio import sleep
from aiogram import Bot
from aiogram.exceptions import TelegramBadRequest
from aiogram.types import ChatMemberBanned, ChatMemberLeft
from aiogram.utils.formatting import Bold
from messages import *
@ -10,6 +12,28 @@ import tg.tg_database as database
from tg.handlers.user import format_rating
async def cleanup_users(bot: Bot):
for chat in database.DB.get_chats():
if chat['active'] == 0:
continue
chat_id = chat['id']
for user in database.DB.get_top_silent(chat_id=chat_id, threshold_days=14):
user_id = user['user_id']
found = False
try:
info = await bot.get_chat_member(chat_id, user_id)
if not isinstance(info, ChatMemberLeft) and not isinstance(info, ChatMemberBanned):
found = True
except TelegramBadRequest:
pass
if not found:
database.DB.delete_user(chat_id, user_id)
print(f'Из чата (id={chat_id}) удален пользователь (id={user_id})')
async def reset_counters(reset_month: bool, bot: Bot):
database.DB.reset_messages_today()
print('Дневные счетчики сброшены.')
@ -55,6 +79,7 @@ async def daily_maintenance_task(bot: Bot):
await wait_until(target_datetime)
try:
await cleanup_users(bot)
await reset_counters(target_datetime.day == 1, bot)
except Exception:
print(traceback.format_exc())

View file

@ -9,6 +9,27 @@ import vk.vk_database as database
from vk.handlers.user import format_rating
async def cleanup_users(api: API):
for chat in database.DB.get_chats():
if chat['active'] == 0:
continue
chat_id = chat['id']
members = await api.messages.get_conversation_members(peer_id=chat_id, extended=False)
for user in database.DB.get_top_silent(chat_id=chat_id, threshold_days=14):
user_id = user['user_id']
found = False
for item in members.items:
if item.member_id == user_id:
found = True
break
if not found:
database.DB.delete_user(chat_id, user_id)
print(f'Из чата (id={chat_id}) удален пользователь (id={user_id})')
async def reset_counters(reset_month: bool, api: API):
database.DB.reset_messages_today()
print('Дневные счетчики сброшены.')
@ -91,6 +112,7 @@ async def daily_maintenance_task(api: API):
await wait_until(target_datetime)
try:
await cleanup_users(api)
await reset_counters(target_datetime.day == 1, api)
await check_birthdays(api)
except Exception: