Files
DiscordQuestBot
Code
3 224
DiscordQuestBot/database.py
import sqlite3
import aiosqlite
from datetime import datetime, timedelta
from typing import Optional
import config
DB_PATH = "data/questbot.db"
async def init_db():
import aiosqlite
import os
os.makedirs("data", exist_ok=True)
db = await aiosqlite.connect(DB_PATH)
db.row_factory = aiosqlite.Row
await db.executescript("""
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
xp INTEGER DEFAULT 0,
level INTEGER DEFAULT 1,
currency INTEGER DEFAULT 100,
total_quests_completed INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS quests (
quest_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL,
quest_type TEXT NOT NULL CHECK(quest_type IN ('daily','weekly','one_time','story')),
objective_type TEXT NOT NULL CHECK(objective_type IN ('messages','voice_minutes','reactions','invites','custom')),
objective_target INTEGER NOT NULL,
xp_reward INTEGER NOT NULL,
currency_reward INTEGER DEFAULT 0,
role_reward_id INTEGER,
active INTEGER DEFAULT 1,
created_at TEXT DEFAULT (datetime('now')),
created_by INTEGER
);
CREATE TABLE IF NOT EXISTS user_quests (
user_id INTEGER NOT NULL,
quest_id INTEGER NOT NULL,
progress INTEGER DEFAULT 0,
completed INTEGER DEFAULT 0,
claimed INTEGER DEFAULT 0,
started_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_id, quest_id)
);
CREATE TABLE IF NOT EXISTS quest_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
quest_id INTEGER,
action TEXT NOT NULL,
timestamp TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_user_quests_progress ON user_quests(user_id, quest_id);
CREATE INDEX IF NOT EXISTS idx_quests_type ON quests(quest_type, active);
""")
await db.commit()
await db.close()
class Database:
def __init__(self):
self.db_path = DB_PATH
async def _connect(self):
db = await aiosqlite.connect(self.db_path)
db.row_factory = aiosqlite.Row
return db
# --- Users ---
async def get_or_create_user(self, user_id: int):
db = await self._connect()
cursor = await db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
row = await cursor.fetchone()
if row:
await db.close()
return dict(row)
await db.execute(
"INSERT INTO users (user_id, xp, level, currency) VALUES (?, ?, ?, ?)",
(user_id, config.STARTING_XP, 1, config.STARTING_CURRENCY),
)
await db.commit()
await db.close()
return {"user_id": user_id, "xp": config.STARTING_XP, "level": 1, "currency": config.STARTING_CURRENCY, "total_quests_completed": 0}
async def add_xp(self, user_id: int, amount: int):
db = await self._connect()
await db.execute("UPDATE users SET xp = xp + ? WHERE user_id = ?", (amount, user_id))
await db.commit()
cursor = await db.execute("SELECT xp, level FROM users WHERE user_id = ?", (user_id,))
row = await cursor.fetchone()
await db.close()
new_level = (row["xp"] // config.XP_PER_LEVEL) + 1
leveled_up = new_level > row["level"]
if leveled_up:
db2 = await self._connect()
await db2.execute("UPDATE users SET level = ? WHERE user_id = ?", (new_level, user_id))
await db2.commit()
await db2.close()
return {"xp": row["xp"] + amount, "level": new_level if leveled_up else row["level"], "leveled_up": leveled_up}
async def add_currency(self, user_id: int, amount: int):
db = await self._connect()
await db.execute("UPDATE users SET currency = currency + ? WHERE user_id = ?", (amount, user_id))
await db.commit()
await db.close()
async def get_leaderboard(self, sort_by="xp", limit=10):
db = await self._connect()
column = "xp" if sort_by == "xp" else "currency"
cursor = await db.execute(f"SELECT * FROM users ORDER BY {column} DESC LIMIT ?", (limit,))
rows = await cursor.fetchall()
await db.close()
return [dict(r) for r in rows]
# --- Quests ---
async def create_quest(self, name: str, description: str, quest_type: str, objective_type: str,
objective_target: int, xp_reward: int, currency_reward: int = 0,
role_reward_id: Optional[int] = None, created_by: Optional[int] = None) -> int:
db = await self._connect()
cursor = await db.execute(
"""INSERT INTO quests (name, description, quest_type, objective_type, objective_target,
xp_reward, currency_reward, role_reward_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(name, description, quest_type, objective_type, objective_target,
xp_reward, currency_reward, role_reward_id, created_by),
)
await db.commit()
quest_id = cursor.lastrowid
await db.close()
return quest_id
async def get_active_quests(self, quest_type: Optional[str] = None):
db = await self._connect()
if quest_type:
cursor = await db.execute(
"SELECT * FROM quests WHERE active = 1 AND quest_type = ? ORDER BY quest_id DESC", (quest_type,))
else:
cursor = await db.execute("SELECT * FROM quests WHERE active = 1 ORDER BY quest_type, quest_id")
rows = await cursor.fetchall()
await db.close()
return [dict(r) for r in rows]
async def get_quest(self, quest_id: int):
db = await self._connect()
cursor = await db.execute("SELECT * FROM quests WHERE quest_id = ?", (quest_id,))
row = await cursor.fetchone()
await db.close()
return dict(row) if row else None
async def toggle_quest_active(self, quest_id: int, active: bool):
db = await self._connect()
await db.execute("UPDATE quests SET active = ? WHERE quest_id = ?", (1 if active else 0, quest_id))
await db.commit()
await db.close()
async def delete_quest(self, quest_id: int):
db = await self._connect()
await db.execute("DELETE FROM quests WHERE quest_id = ?", (quest_id,))
await db.commit()
await db.close()
# --- User-Quests ---
async def start_quest(self, user_id: int, quest_id: int):
db = await self._connect()
await db.execute(
"INSERT OR IGNORE INTO user_quests (user_id, quest_id) VALUES (?, ?)",
(user_id, quest_id),
)
await db.commit()
await db.close()
async def get_user_quest(self, user_id: int, quest_id: int):
db = await self._connect()
cursor = await db.execute(
"SELECT * FROM user_quests WHERE user_id = ? AND quest_id = ?", (user_id, quest_id))
row = await cursor.fetchone()
await db.close()
return dict(row) if row else None
async def get_user_quests(self, user_id: int, only_active=True):
db = await self._connect()
if only_active:
cursor = await db