Spaces:
Running
Running
| # database.py | |
| import os | |
| import sqlite3 | |
| import requests | |
| from huggingface_hub import HfApi, create_repo, repo_exists | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| if not HF_TOKEN: | |
| print("[DB] ❌ НЕТ HF_TOKEN В ПЕРЕМЕННЫХ ОКРУЖЕНИЯ!") | |
| print("[DB] Установи: export HF_TOKEN='твой_токен'") | |
| raise SystemExit("[DB] НЕТ HF_TOKEN!") | |
| REPO_ID = "RomanJordansky/Manlix_Manager-database" | |
| DB_PATH_IN_REPO = "bot_database.db" | |
| HF_URL = f"https://huggingface.co/{REPO_ID}/resolve/main/{DB_PATH_IN_REPO}" | |
| DATA_DIR = "bot_data" | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| DB_PATH = os.path.join(DATA_DIR, "bot_database.db") | |
| print(f"[DB] База данных: {DB_PATH}") | |
| def create_repo_if_not_exists(): | |
| try: | |
| if repo_exists(repo_id=REPO_ID, token=HF_TOKEN): | |
| print(f"[DB] ✅ Репозиторий {REPO_ID} уже существует") | |
| return True | |
| create_repo(repo_id=REPO_ID, token=HF_TOKEN, repo_type="model", private=False, exist_ok=True) | |
| print(f"[DB] ✅ Репозиторий {REPO_ID} создан как MODEL!") | |
| return True | |
| except Exception as e: | |
| print(f"[DB] ❌ Ошибка создания репозитория: {e}") | |
| return False | |
| def download_db(): | |
| print("[DB] Попытка загрузить базу данных...") | |
| try: | |
| headers = {"User-Agent": "Mozilla/5.0", "Authorization": f"Bearer {HF_TOKEN}"} | |
| response = requests.get(HF_URL, headers=headers, timeout=30) | |
| if response.status_code == 200: | |
| with open(DB_PATH, 'wb') as f: | |
| f.write(response.content) | |
| print(f"[DB] ✅ База данных загружена! Размер: {os.path.getsize(DB_PATH)} байт") | |
| return True | |
| else: | |
| print(f"[DB] БД не найдена (код {response.status_code})") | |
| return False | |
| except Exception as e: | |
| print(f"[DB] Ошибка загрузки: {e}") | |
| return False | |
| def upload_db(): | |
| try: | |
| api = HfApi(token=HF_TOKEN) | |
| api.upload_file(path_or_fileobj=DB_PATH, path_in_repo=DB_PATH_IN_REPO, repo_id=REPO_ID, repo_type="model") | |
| print(f"[DB] ✅ БД сохранена на HF! Размер: {os.path.getsize(DB_PATH)} байт") | |
| return True | |
| except Exception as e: | |
| print(f"[DB] ❌ Ошибка сохранения: {e}") | |
| return False | |
| create_repo_if_not_exists() | |
| db_loaded = download_db() | |
| if not db_loaded: | |
| print("[DB] БД НЕ НАЙДЕНА! СОЗДАЮ НОВУЮ...") | |
| conn = sqlite3.connect(DB_PATH, check_same_thread=False) | |
| cursor = conn.cursor() | |
| def create_tables(): | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS chats ( | |
| chat_id INTEGER PRIMARY KEY, | |
| chat_type TEXT DEFAULT 'def', | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| user_id INTEGER, | |
| chat_id INTEGER NULL, | |
| nick TEXT, | |
| role TEXT DEFAULT 'Участник', | |
| level INTEGER DEFAULT 0, | |
| PRIMARY KEY (user_id, chat_id) | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS blocks ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| user_id INTEGER, | |
| chat_id INTEGER, | |
| moderator_id INTEGER, | |
| reason TEXT, | |
| time TEXT, | |
| block_type TEXT DEFAULT 'ban' | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS warns ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| user_id INTEGER, | |
| chat_id INTEGER, | |
| reason TEXT, | |
| time TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS mutes ( | |
| user_id INTEGER, | |
| chat_id INTEGER, | |
| muted INTEGER DEFAULT 1, | |
| until_time TEXT, | |
| reason TEXT, | |
| PRIMARY KEY (user_id, chat_id) | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS messages ( | |
| user_id INTEGER, | |
| chat_id INTEGER, | |
| count INTEGER DEFAULT 0, | |
| last_time TEXT, | |
| PRIMARY KEY (user_id, chat_id) | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS global_nicks ( | |
| user_id INTEGER PRIMARY KEY, | |
| nick TEXT, | |
| set_by INTEGER, | |
| set_at TEXT | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS tech_reports ( | |
| chat_id INTEGER PRIMARY KEY, | |
| active INTEGER DEFAULT 1 | |
| ) | |
| """) | |
| # Миграции | |
| try: | |
| cursor.execute("ALTER TABLE chats ADD COLUMN chat_type TEXT DEFAULT 'def'") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE messages ADD COLUMN count INTEGER DEFAULT 0") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE messages ADD COLUMN last_time TEXT") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE mutes ADD COLUMN until_time TEXT") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE mutes ADD COLUMN reason TEXT") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE blocks ADD COLUMN moderator_id INTEGER") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE blocks ADD COLUMN reason TEXT") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE blocks ADD COLUMN time TEXT") | |
| except: | |
| pass | |
| try: | |
| cursor.execute("ALTER TABLE blocks ADD COLUMN block_type TEXT DEFAULT 'ban'") | |
| except: | |
| pass | |
| conn.commit() | |
| print("[DB] ✅ Таблицы созданы/проверены") | |
| create_tables() | |
| if not db_loaded: | |
| upload_db() | |
| print("[DB] ✅ Новая БД создана и загружена на HF") |