Удаление пользователя из БД при его исключении из беседы.

This commit is contained in:
Kirill Kirilenko 2025-09-21 18:41:52 +03:00
parent cfb02cfd2b
commit 7ac6cd9bd1
3 changed files with 50 additions and 3 deletions

View file

@ -50,6 +50,10 @@ class Database:
f" WHERE id = {chat_id}", kwargs) f" WHERE id = {chat_id}", kwargs)
self.conn.commit() self.conn.commit()
def chat_delete(self, chat_id: int):
self.cursor.execute("DELETE FROM chats WHERE id = ?", (chat_id,))
self.conn.commit()
def get_user(self, chat_id: int, user_id: int): def get_user(self, chat_id: int, user_id: int):
self.cursor.execute("SELECT * FROM users WHERE chat_id = ? AND user_id = ?", (chat_id, user_id)) self.cursor.execute("SELECT * FROM users WHERE chat_id = ? AND user_id = ?", (chat_id, user_id))
return self.cursor.fetchone() return self.cursor.fetchone()
@ -85,6 +89,10 @@ class Database:
f" WHERE chat_id = {chat_id} AND user_id = {user_id}", kwargs) f" WHERE chat_id = {chat_id} AND user_id = {user_id}", kwargs)
self.conn.commit() self.conn.commit()
def delete_user(self, chat_id: int, user_id: int):
self.cursor.execute("DELETE FROM users WHERE chat_id = ? AND user_id = ?", (chat_id, user_id))
self.conn.commit()
def get_top_messages_today(self, chat_id: int): def get_top_messages_today(self, chat_id: int):
self.cursor.execute(""" self.cursor.execute("""
SELECT user_id, messages_today AS value FROM users SELECT user_id, messages_today AS value FROM users
@ -123,6 +131,10 @@ class Database:
""", (chat_id,)) """, (chat_id,))
return self.cursor.fetchall() return self.cursor.fetchall()
def delete_users(self, chat_id: int):
self.cursor.execute("DELETE FROM users WHERE chat_id = ?", (chat_id,))
self.conn.commit()
def reset_messages_today(self): def reset_messages_today(self):
self.cursor.execute("UPDATE users SET messages_today = 0") self.cursor.execute("UPDATE users SET messages_today = 0")
self.conn.commit() self.conn.commit()

View file

@ -20,11 +20,11 @@ async def user_join_handler(message: Message):
user_id = message.action.member_id user_id = message.action.member_id
first_join = (user_id != message.from_id) first_join = (user_id != message.from_id)
user_info = (await message.ctx_api.users.get(user_ids=[user_id]))[0]
if user_id < 0: if user_id < 0:
return return
user_info = (await message.ctx_api.users.get(user_ids=[user_id]))[0]
if first_join: if first_join:
response = chat['greeting_join'] or MESSAGE_DEFAULT_GREETING_JOIN response = chat['greeting_join'] or MESSAGE_DEFAULT_GREETING_JOIN
else: else:
@ -32,3 +32,15 @@ async def user_join_handler(message: Message):
response = response.format(name=f'@id{user_id} ({user_info.first_name})') response = response.format(name=f'@id{user_id} ({user_info.first_name})')
await message.answer(response) await message.answer(response)
@labeler.chat_message(action=['chat_kick_user'])
async def user_leave_handler(message: Message):
chat_id = message.peer_id
chat = database.create_chat_if_not_exists(chat_id)
if chat['active'] == 0:
return
user_id = message.action.member_id
if user_id != message.from_id:
database.DB.delete_user(chat_id, user_id)

View file

@ -2,7 +2,7 @@ import datetime
import traceback import traceback
from asyncio import sleep from asyncio import sleep
from vkbottle import API, bold from vkbottle import API, bold, VKAPIError
import database import database
from handlers.user import format_rating from handlers.user import format_rating
@ -99,6 +99,29 @@ async def daily_maintenance_task(api: API):
target_datetime = target_datetime + datetime.timedelta(days=1) target_datetime = target_datetime + datetime.timedelta(days=1)
async def cleanup_users(api: API):
for chat in database.DB.get_chats():
chat_id = chat['id']
try:
members = await api.messages.get_conversation_members(peer_id=chat_id, extended=False)
except VKAPIError as e:
continue
for user in database.DB.get_users(chat_id):
user_id = user['user_id']
found = False
for profile in members.profiles:
if profile.id == user_id:
found = True
break
if not found:
database.DB.delete_user(chat_id, user_id)
print(f'Удален пользователь id={user_id}')
async def startup_task(api: API): async def startup_task(api: API):
me = (await api.groups.get_by_id()).groups[0] me = (await api.groups.get_by_id()).groups[0]
print(f"Бот '{me.name}' (id={me.id}) запущен.") print(f"Бот '{me.name}' (id={me.id}) запущен.")
await cleanup_users(api)