import aiosqlite DB_NAME = "luna_bot.db" async def init_db(): async with aiosqlite.connect(DB_NAME) as db: # Таблица пользователей await db.execute(""" CREATE TABLE IF NOT EXISTS users ( user_id INTEGER PRIMARY KEY, username TEXT, birthday TEXT ) """) # Таблица заявок await db.execute(""" CREATE TABLE IF NOT EXISTS suggestions ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, type TEXT, -- 'youtube' или 'idea' content TEXT, status TEXT DEFAULT 'на рассмотрении', reason TEXT DEFAULT '' ) """) await db.commit() async def add_user(user_id, username): async with aiosqlite.connect(DB_NAME) as db: await db.execute("INSERT OR IGNORE INTO users (user_id, username) VALUES (?, ?)", (user_id, username)) await db.commit() async def get_user(user_id): async with aiosqlite.connect(DB_NAME) as db: async with db.execute("SELECT username FROM users WHERE user_id = ?", (user_id,)) as cursor: return await cursor.fetchone() async def set_birthday(user_id, birthday): async with aiosqlite.connect(DB_NAME) as db: await db.execute("UPDATE users SET birthday = ? WHERE user_id = ?", (birthday, user_id)) await db.commit() async def get_birthdays(date_str): async with aiosqlite.connect(DB_NAME) as db: async with db.execute("SELECT username FROM users WHERE birthday = ?", (date_str,)) as cursor: return await cursor.fetchall() async def get_all_birthdays(): async with aiosqlite.connect(DB_NAME) as db: async with db.execute("SELECT username, birthday FROM users WHERE birthday IS NOT NULL") as cursor: return await cursor.fetchall() async def add_suggestion(user_id, s_type, content): async with aiosqlite.connect(DB_NAME) as db: await db.execute("INSERT INTO suggestions (user_id, type, content) VALUES (?, ?, ?)", (user_id, s_type, content)) await db.commit() async def get_user_suggestions(user_id): async with aiosqlite.connect(DB_NAME) as db: async with db.execute("SELECT type, content, status, reason FROM suggestions WHERE user_id = ?", (user_id,)) as cursor: return await cursor.fetchall() # Берем только ОДНУ самую старую нерассмотренную заявку и присоединяем никнейм автора async def get_first_pending_suggestion(s_type): async with aiosqlite.connect(DB_NAME) as db: query = """ SELECT s.id, s.content, u.username FROM suggestions s JOIN users u ON s.user_id = u.user_id WHERE s.type = ? AND s.status = 'на рассмотрении' ORDER BY s.id ASC LIMIT 1 """ async with db.execute(query, (s_type,)) as cursor: return await cursor.fetchone() # Узнаем тип заявки (чтобы после ответа выдать следующую того же типа) async def get_suggestion_type(s_id): async with aiosqlite.connect(DB_NAME) as db: async with db.execute("SELECT type FROM suggestions WHERE id = ?", (s_id,)) as cursor: row = await cursor.fetchone() return row[0] if row else None async def update_suggestion_status(s_id, status, reason=""): async with aiosqlite.connect(DB_NAME) as db: await db.execute("UPDATE suggestions SET status = ?, reason = ? WHERE id = ?", (status, reason, s_id)) await db.commit()