Files
weather_bot/database.py
2026-03-26 12:42:59 +03:00

51 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import aiosqlite
import os
# База будет храниться в папке data
DB_PATH = "data/users.db"
async def init_db():
"""Создает таблицу, если она еще не существует."""
os.makedirs("data", exist_ok=True)
async with aiosqlite.connect(DB_PATH) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
lat REAL,
lon REAL,
time TEXT
)
''')
await db.commit()
async def get_user(user_id: int):
"""Возвращает данные пользователя по его ID."""
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row # Чтобы обращаться к колонкам по именам (как к словарю)
async with db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,)) as cursor:
return await cursor.fetchone()
async def save_user_location(user_id: int, lat: float, lon: float):
"""Сохраняет или обновляет только координаты пользователя."""
async with aiosqlite.connect(DB_PATH) as db:
await db.execute('''
INSERT INTO users (user_id, lat, lon)
VALUES (?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
lat=excluded.lat,
lon=excluded.lon
''', (user_id, lat, lon))
await db.commit()
async def update_user_time(user_id: int, time: str):
"""Обновляет время отправки для пользователя."""
async with aiosqlite.connect(DB_PATH) as db:
await db.execute("UPDATE users SET time = ? WHERE user_id = ?", (time, user_id))
await db.commit()
async def get_all_users_with_time():
"""Получает всех пользователей, у которых настроено время (для восстановления после перезапуска)."""
async with aiosqlite.connect(DB_PATH) as db:
db.row_factory = aiosqlite.Row
async with db.execute("SELECT * FROM users WHERE time IS NOT NULL") as cursor:
return await cursor.fetchall()