Files
bot.py
requirements.txt
Code
2 513
bot.py
#!/usr/bin/env python3
"""Questfy - a safe Discord entitlement and fulfilment queue bot.
This bot deliberately does not accept Discord user tokens, automate user
accounts, bypass CAPTCHAs, or call private Discord quest endpoints. It manages
licences, credits, and a fulfilment queue for an operator using an approved
provider or manual fulfilment process.
"""
from __future__ import annotations
import asyncio
import logging
import os
import secrets
import sqlite3
from datetime import datetime, timedelta, timezone
from typing import Any
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
DATABASE_PATH = os.getenv("DATABASE_PATH", "questfy.sqlite3")
GUILD_ID = int(os.getenv("GUILD_ID", "0") or 0)
OWNER_IDS = {
int(value.strip())
for value in os.getenv("OWNER_IDS", "691277710751826031").split(",")
if value.strip().isdigit()
}
PLAN_RULES: dict[str, dict[str, Any]] = {
"weekly": {"label": "Weekly", "credits": 3, "period_days": 7},
"monthly": {"label": "Monthly", "credits": 10, "period_days": 30},
"lifetime": {"label": "Lifetime", "credits": 3, "period_days": 7},
}
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def iso(value: datetime | None) -> str | None:
return value.isoformat() if value else None
def parse_iso(value: str | None) -> datetime | None:
if not value:
return None
return datetime.fromisoformat(value)
class Store:
"""Small SQLite persistence layer used by the single-file bot."""
def __init__(self, path: str) -> None:
self.connection = sqlite3.connect(path, check_same_thread=False)
self.connection.row_factory = sqlite3.Row
self.lock = asyncio.Lock()
self._initialize()
def _initialize(self) -> None:
self.connection.executescript(
"""
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS licences (
key TEXT PRIMARY KEY,
plan TEXT NOT NULL,
created_at TEXT NOT NULL,
redeemed_by INTEGER,
redeemed_at TEXT,
revoked INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS accounts (
discord_id INTEGER PRIMARY KEY,
plan TEXT NOT NULL,
started_at TEXT NOT NULL,
expires_at TEXT,
period_started_at TEXT NOT NULL,
credits INTEGER NOT NULL,
active INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS catalog (
slug TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS claims (
id INTEGER PRIMARY KEY AUTOINCREMENT,
discord_id INTEGER NOT NULL,
item_slug TEXT NOT NULL,
item_name TEXT NOT NULL,
created_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
handled_by INTEGER,
note TEXT
);
"""
)
self.connection.executemany(
"INSERT OR IGNORE INTO catalog (slug, name, description) VALUES (?, ?, ?)",
[
("cosmetic-basic", "Basic Cosmetic", "A starter cosmetic fulfilment."),
("cosmetic-premium", "Premium Cosmetic", "A premium cosmetic fulfilment."),
],
)
self.connection.commit()
def _refresh_account_locked(self, discord_id: int) -> sqlite3.Row | None:
row = self.connection.execute(
"SELECT * FROM accounts WHERE discord_id = ?", (discord_id,)
).fetchone()
if not row:
return None
now = utc_now()
expires_at = parse_iso(row["expires_at"])
if expires_at and now >= expires_at:
self.connection.execute(
"UPDATE accounts SET active = 0, credits = 0 WHERE discord_id = ?",
(discord_id,),
)
self.connection.commit()
return self.connection.execute(
"SELECT * FROM accounts WHERE discord_id = ?", (discord_id,)
).fetchone()
rule = PLAN_RULES[row["plan"]]
period_seconds = rule["period_days"] * 86400
period_started = parse_iso(row["period_started_at"]) or now
if now >= period_started + timedelta(seconds=period_seconds):
periods = int((now - period_started).total_seconds() // period_seconds)
new_period = period_started + timedelta(seconds=periods * period_seconds)
self.connection.execute(
"""UPDATE accounts
SET period_started_at = ?, credits = ?, active = 1
WHERE discord_id = ?""",
(iso(new_period), rule["credits"], discord_id),
)
self.connection.commit()
return self.connection.execute(
"SELECT * FROM accounts WHERE discord_id = ?", (discord_id,)
).fetchone()
async def create_licence(self, plan: str) -> str:
key = f"QFY-{plan[:3].upper()}-{secrets.token_urlsafe(12).upper()}"
async with self.lock:
self.connection.execute(
"INSERT INTO licences (key, plan, created_at) VALUES (?, ?, ?)",
(key, plan, iso(utc_now())),
)
self.connection.commit()
return key
async def redeem(self, key: str, discord_id: int) -> str:
key = key.strip().upper()
async with self.lock:
licence = self.connection.execute(
"SELECT * FROM licences WHERE key = ?", (key,)
).fetchone()
if not licence:
raise ValueError("That licence key does not exist.")
if licence["revoked"]:
raise ValueError("That licence key has been revoked.")
if licence["redeemed_by"] is not None:
raise ValueError("That licence key has already been redeemed.")
existing = self._refresh_account_locked(discord_id)
if existing and existing["active"]:
raise ValueError("You already have an active plan.")
plan = licence["plan"]
rule = PLAN_RULES[plan]
now = utc_now()
expires = None if plan == "lifetime" else now + timedelta(days=rule["period_days"])
self.connection.execute(
"""INSERT OR REPLACE INTO accounts
(discord_id, plan, started_at, expires_at, period_started_at, credits, active)
VALUES (?, ?, ?, ?, ?, ?, 1)""",
(discord_id, plan, iso(now), iso(expires), iso(now), rule["credits"]),
)
self.connection.execute(
"""UPDATE licences SET redeemed_by = ?, redeemed_at = ? WHERE key = ?""",
(discord_id, iso(now), key),
)
self.connection.commit()
return plan
async def account(self, discord_id: int) -> sqlite3.Row | None:
async with self.lock:
return self._refresh_account_locked(discord_id)
async def create_claim(self, discord_id: int, item_slug: str) -> int: