from datetime import datetime from typing import Dict, List, Optional, Any, Type from mariadb import create_pool class BasicDatabase: def __init__(self, hostname: str, user: str, password: str, dbname: str): self.hostname = hostname self.user = user self.password = password self.dbname = dbname self.pool = create_pool(host=hostname, user=user, password=password, database=dbname, autocommit=True, dictionary=True, min_size=1, max_size=5) def get_bots(self) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM bots") return cursor.fetchall() def get_bot(self, bot_id: int) -> Optional[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM bots WHERE id = ?", (bot_id,)) return cursor.fetchone() def get_chats(self, bot_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM chats WHERE bot_id = ?", (bot_id,)) return cursor.fetchall() def get_chat(self, bot_id: int, chat_id: int) -> Optional[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM chats WHERE bot_id = ? AND chat_id = ?", (bot_id, chat_id)) return cursor.fetchone() def add_chat(self, bot_id: int, chat_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("INSERT INTO chats (bot_id, chat_id) VALUES (?, ?)", (bot_id, chat_id)) def chat_update(self, bot_id: int, chat_id: int, **kwargs): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("UPDATE chats SET " + ", ".join(f + " = ?" for f in kwargs) + " WHERE bot_id = ? AND chat_id = ?", list(kwargs.values()) + [bot_id, chat_id]) def chat_delete(self, bot_id: int, chat_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("DELETE FROM chats WHERE bot_id = ? AND chat_id = ?", (bot_id, chat_id)) def get_user(self, bot_id: int, chat_id: int, user_id: int) -> Optional[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM users WHERE bot_id = ? AND chat_id = ? AND user_id = ?", (bot_id, chat_id, user_id)) return cursor.fetchone() def get_users(self, bot_id: int, chat_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM users WHERE bot_id = ? AND chat_id = ?", (bot_id, chat_id)) return cursor.fetchall() def add_user(self, bot_id: int, chat_id: int, user_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("INSERT INTO users (bot_id, chat_id, user_id) VALUES (?, ?, ?)", (bot_id, chat_id, user_id)) def user_set_last_message(self, bot_id: int, chat_id: int, user_id: int, last_message: int): self.user_update(bot_id, chat_id, user_id, last_message=last_message) def user_increment_messages(self, bot_id: int, chat_id: int, user_id: int): self.user_increment(bot_id, chat_id, user_id, ['messages_today', 'messages_month']) def user_increment_warnings(self, bot_id: int, chat_id: int, user_id: int): self.user_increment(bot_id, chat_id, user_id, ['warnings']) def user_increment(self, bot_id: int, chat_id: int, user_id: int, fields: List[str]): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("UPDATE users SET " + ", ".join(f + " = " + f + " + 1" for f in fields) + " WHERE bot_id = ? AND chat_id = ? AND user_id = ?", (bot_id, chat_id, user_id)) def user_update(self, bot_id: int, chat_id: int, user_id: int, **kwargs): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("UPDATE users SET " + ", ".join(f + " = ?" for f in kwargs) + " WHERE bot_id = ? AND chat_id = ? AND user_id = ?", list(kwargs.values()) + [bot_id, chat_id, user_id]) def delete_user(self, bot_id: int, chat_id: int, user_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("DELETE FROM users WHERE bot_id = ? AND chat_id = ? AND user_id = ?", (bot_id, chat_id, user_id)) def get_top_messages_today(self, bot_id: int, chat_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute(""" SELECT user_id, messages_today AS value FROM users WHERE bot_id = ? AND chat_id = ? AND messages_today > 0 ORDER BY messages_today DESC """, (bot_id, chat_id)) return cursor.fetchall() def get_top_messages_month(self, bot_id: int, chat_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute(""" SELECT user_id, messages_month AS value FROM users WHERE bot_id = ? AND chat_id = ? AND messages_month > 0 ORDER BY messages_month DESC """, (bot_id, chat_id)) return cursor.fetchall() def get_top_silent(self, bot_id: int, chat_id: int, threshold_days: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: current_time = int(datetime.now().timestamp()) threshold = current_time - threshold_days * 86400 cursor.execute(""" SELECT user_id, (? - last_message) DIV 86400 as value FROM users WHERE bot_id = ? AND chat_id = ? AND last_message <= ? ORDER BY last_message ASC """, (current_time, bot_id, chat_id, threshold)) result = cursor.fetchall() for row in result: if row['value'] > 3650: row['value'] = 'никогда' return result def get_top_warnings(self, bot_id: int, chat_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute(""" SELECT user_id, warnings AS value FROM users WHERE bot_id = ? AND chat_id = ? AND warnings > 0 ORDER BY warnings DESC """, (bot_id, chat_id)) return cursor.fetchall() def reset_messages_today(self, bot_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("UPDATE users SET messages_today = 0 WHERE bot_id = ?", (bot_id,)) def reset_messages_month(self, bot_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("UPDATE users SET messages_month = 0 WHERE bot_id = ?", (bot_id,)) def context_get_messages(self, bot_id: int, chat_id: int) -> List[Dict[str, Any]]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute(""" SELECT role, text, image FROM contexts WHERE bot_id = ? AND chat_id = ? ORDER BY id """, (bot_id, chat_id)) return cursor.fetchall() def context_get_count(self, bot_id: int, chat_id: int) -> int: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM contexts WHERE bot_id = ? AND chat_id = ?", (bot_id, chat_id)) return _to_val(int, cursor.fetchone()) def context_get_last_assistant_message_id(self, bot_id: int, chat_id: int) -> Optional[int]: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute(""" SELECT message_id FROM contexts WHERE bot_id = ? AND chat_id = ? AND role = 'assistant' ORDER BY id DESC LIMIT 1 """, (bot_id, chat_id)) return _to_val(int, cursor.fetchone()) def context_add_message(self, bot_id: int, chat_id: int, role: str, text: Optional[str], image: Optional[bytes], message_id: Optional[int], max_messages: int): assert (text or image) self._context_trim(bot_id, chat_id, max_messages) # Подготовка данных для вставки data = { "bot_id": bot_id, "chat_id": chat_id, "message_id": message_id, "role": role, "text": text, "image": image } # Формирование SQL-запроса и параметров вставки columns = [k for k, v in data.items() if v is not None] placeholders = ', '.join(['?' for _ in columns]) values = tuple(data[k] for k in columns) with self.pool.acquire() as conn: with conn.cursor() as cursor: query = f"INSERT INTO contexts ({', '.join(columns)}) VALUES ({placeholders})" cursor.execute(query, values) def context_set_last_message_id(self, bot_id: int, chat_id: int, message_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute( "UPDATE contexts SET message_id = ? WHERE bot_id = ? AND chat_id = ? AND message_id IS NULL", (message_id, bot_id, chat_id)) def _context_trim(self, bot_id: int, chat_id: int, max_messages: int): current_count = self.context_get_count(bot_id, chat_id) while current_count >= max_messages: with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute( "SELECT id FROM contexts WHERE bot_id = ? AND chat_id = ? ORDER BY id LIMIT 1", (bot_id, chat_id)) oldest_message_id = _to_val(int, cursor.fetchone()) if oldest_message_id: cursor.execute("DELETE FROM contexts WHERE id = ?", oldest_message_id) current_count -= 1 else: break def context_clear(self, bot_id: int, chat_id: int): with self.pool.acquire() as conn: with conn.cursor() as cursor: cursor.execute("DELETE FROM contexts WHERE bot_id = ? AND chat_id = ?", (bot_id, chat_id)) def create_chat_if_not_exists(self, bot_id: int, chat_id: int) -> Dict[str, Any]: chat = self.get_chat(bot_id, chat_id) if chat is None: self.add_chat(bot_id, chat_id) chat = self.get_chat(bot_id, chat_id) assert (chat is not None) return chat def create_user_if_not_exists(self, bot_id: int, chat_id: int, user_id: int) -> Dict[str, Any]: user = self.get_user(bot_id, chat_id, user_id) if user is None: self.add_user(bot_id, chat_id, user_id) user = self.get_user(bot_id, chat_id, user_id) assert (user is not None) return user def _to_val[T](_: Type[T], arg: Any) -> T: return next(iter(arg.values())) if arg is not None else None