Files
bot.py
config.yml
requirements.txt
Code
3 318
bot.py
import csv
import hmac
import io
import logging
import os
import re
import secrets
from datetime import datetime, timezone
import aiosqlite
import discord
import yaml
from aiohttp import web
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("license_bot")
class LicenseStore:
def __init__(self, database_path: str):
self.database_path = database_path
self.connection = None
self.lock = __import__("asyncio").Lock()
async def open(self):
self.connection = await aiosqlite.connect(self.database_path)
await self.connection.execute(
"""CREATE TABLE IF NOT EXISTS licenses (
license_key TEXT PRIMARY KEY,
product TEXT NOT NULL,
product_key TEXT NOT NULL,
created_at TEXT NOT NULL,
created_by TEXT NOT NULL,
revoked_at TEXT
)"""
)
await self.connection.commit()
async def create(self, product: str, amount: int, created_by: str) -> list[str]:
now = datetime.now(timezone.utc).isoformat()
keys = [f"LIC-{secrets.token_hex(24).upper()}" for _ in range(amount)]
async with self.lock:
await self.connection.executemany(
"INSERT INTO licenses (license_key, product, product_key, created_at, created_by) "
"VALUES (?, ?, ?, ?, ?)",
[(key, product, product.casefold(), now, created_by) for key in keys],
)
await self.connection.commit()
return keys
async def revoke(self, license_key: str) -> bool:
async with self.lock:
cursor = await self.connection.execute(
"UPDATE licenses SET revoked_at = ? WHERE license_key = ? AND revoked_at IS NULL",
(datetime.now(timezone.utc).isoformat(), license_key.strip().upper()),
)
await self.connection.commit()
return cursor.rowcount > 0
async def status(self, license_key: str):
async with self.lock:
async with self.connection.execute(
"SELECT product, revoked_at FROM licenses WHERE license_key = ?",
(license_key.strip().upper(),),
) as cursor:
row = await cursor.fetchone()
if row is None:
return None
return {"product": row[0], "active": row[1] is None}
async def validate(self, license_key: str, product: str) -> bool:
async with self.lock:
async with self.connection.execute(
"SELECT 1 FROM licenses WHERE license_key = ? AND product_key = ? AND revoked_at IS NULL",
(license_key.strip().upper(), product.strip().casefold()),
) as cursor:
return await cursor.fetchone() is not None
async def close(self):
if self.connection is not None:
await self.connection.close()
def load_settings():
token = os.getenv("DISCORD_TOKEN", "").strip()
api_secret = os.getenv("API_SECRET", "").strip()
admin_ids = os.getenv("ADMIN_USER_IDS", "").strip()
if not token:
raise RuntimeError("Set DISCORD_TOKEN in your .env file.")
if len(api_secret) < 32 or api_secret.lower().startswith("replace-"):
raise RuntimeError("Set API_SECRET to a random secret at least 32 characters long in .env.")
try:
admins = {int(value.strip()) for value in admin_ids.split(",") if value.strip()}
except ValueError as exc:
raise RuntimeError("ADMIN_USER_IDS must contain comma-separated Discord user IDs.") from exc
if not admins:
raise RuntimeError("Set at least one Discord user ID in ADMIN_USER_IDS in .env.")
try:
with open("config.yml", encoding="utf-8") as config_file:
config = yaml.safe_load(config_file) or {}
except (OSError, yaml.YAMLError) as exc:
raise RuntimeError("Could not load config.yml.") from exc
if not isinstance(config, dict):
raise RuntimeError("config.yml must contain a YAML mapping.")
configured_addons = config.get("addons")
if not isinstance(configured_addons, dict) or not configured_addons:
raise RuntimeError("Add at least one add-on under addons in config.yml.")
addons = {}
for name, settings in configured_addons.items():
if not isinstance(name, str) or not name.strip() or len(name.strip()) > 60:
raise RuntimeError("Add-on names in config.yml must be 1–60 characters.")
if not isinstance(settings, dict):
raise RuntimeError(f"Settings for add-on {name!r} must be a YAML mapping.")
enabled = settings.get("enabled", True)
max_licenses = settings.get("max_licenses", 300)
if not isinstance(enabled, bool):
raise RuntimeError(f"The enabled setting for {name!r} must be true or false.")
if isinstance(max_licenses, bool) or not isinstance(max_licenses, int) or not 1 <= max_licenses <= 300:
raise RuntimeError(f"max_licenses for {name!r} must be a number from 1 to 300.")
normalized_name = name.strip()
normalized_key = normalized_name.casefold()
if normalized_key in addons:
raise RuntimeError(f"Add-on name {normalized_name!r} is duplicated ignoring case.")
addons[normalized_key] = {
"name": normalized_name,
"enabled": enabled,
"max_licenses": max_licenses,
}
database_path = config.get("database_path", "licenses.sqlite3")
if not isinstance(database_path, str) or not database_path.strip():
raise RuntimeError("database_path in config.yml must be a non-empty path.")
return token, api_secret, admins, addons, database_path.strip()
TOKEN, API_SECRET, ADMIN_USER_IDS, ADDONS, DATABASE_PATH = load_settings()
store = LicenseStore(DATABASE_PATH)
license_group = app_commands.Group(name="license", description="Manage product license keys")
def is_admin(interaction: discord.Interaction) -> bool:
return interaction.user.id in ADMIN_USER_IDS
@license_group.command(name="create", description="Generate license keys for a product")
@app_commands.describe(product="Product name", amount="Number of keys to generate (1–300)")
async def create_licenses(
interaction: discord.Interaction,
product: str,
amount: app_commands.Range[int, 1, 300] = 1,
):
if not is_admin(interaction):
await interaction.response.send_message("You are not allowed to manage licenses.", ephemeral=True)
return
addon = ADDONS.get(product.strip().casefold())
if addon is None or not addon["enabled"]:
await interaction.response.send_message("Choose an enabled add-on listed in config.yml.", ephemeral=True)
return
product = addon["name"]
if amount > addon["max_licenses"]:
await interaction.response.send_message(
f"This add-on allows at most {addon['max_licenses']} licenses per batch (config.yml).",
ephemeral=True,
)
return
await interaction.response.defer(ephemeral=True)
keys = await store.create(product, amount, str(interaction.user.id))
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["product", "license_key"])
writer.writerows((product, key) for key in keys)
filename = re.sub(r"[^a-zA-Z0-9_-]+", "_", product).strip("_") or "licenses"
file = discord.File(io.BytesIO(output.getvalue().encode("utf-8")), filename=f"{filename}_licenses.csv")
await interaction.followup.send(f"Created {len(keys)} license key(s) for **{product}**.", file=file, ephemeral=True)
@create_licenses.autocomplete("product")
async def autocomplete_addons(interaction: discord.Interaction, current: str):
matches = [
app_commands.Choice(name=addon["name"], value=addon["name"])
for addon in ADDONS.values()
if addon["enabled"] and current.casefold() in addon["name"].casefold()
]
return matches[:25]
@license_group.command(name="addons", description="List configured license add-ons")
async def list_addons(interaction: discord.Interaction):
enabled_addons = [addon for addon in ADDONS.values() if addon["enabled"]]
if not enabled_addons:
message = "No enabled add-ons are configured in config.yml."
else: