Files
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
5 587
bot.py
import json
import logging
import os
import sqlite3
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import discord
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("token-bot")
TOKEN_TYPES = {
"discord_bot": "Discord bot",
"ai_video": "AI video generator bot",
}
DEFAULT_CONFIG: dict[str, Any] = {
"database_path": "data/tokens.sqlite3",
"token_limits": {
"discord_bot": 3,
"ai_video": 3,
},
"verification": {
"enabled": True,
"min_account_age_days": 7,
"require_verified_role": False,
"verified_role_id": 0,
},
"logging": {
"channel_id": 0,
},
"documentation": [
{
"name": "discord.py documentation",
"url": "https://discordpy.readthedocs.io/en/stable/",
},
{
"name": "Discord developer documentation",
"url": "https://discord.com/developers/docs/intro",
},
{
"name": "AI video bot resources",
"url": "https://platform.openai.com/docs/overview",
},
],
}
def merge_config(defaults: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]:
result = defaults.copy()
for key, value in values.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = merge_config(result[key], value)
else:
result[key] = value
return result
def load_config() -> dict[str, Any]:
config_path = Path(os.getenv("CONFIG_PATH", "config.json"))
if not config_path.exists():
return DEFAULT_CONFIG.copy()
with config_path.open("r", encoding="utf-8") as config_file:
return merge_config(DEFAULT_CONFIG, json.load(config_file))
class TokenStore:
def __init__(self, database_path: str) -> None:
database = Path(database_path)
database.parent.mkdir(parents=True, exist_ok=True)
self.connection = sqlite3.connect(database)
self.connection.row_factory = sqlite3.Row
self.connection.execute("PRAGMA foreign_keys = ON")
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS users (
discord_id INTEGER PRIMARY KEY,
verified INTEGER NOT NULL DEFAULT 0,
verified_at TEXT,
discord_bot_claimed INTEGER NOT NULL DEFAULT 0,
ai_video_claimed INTEGER NOT NULL DEFAULT 0,
custom_discord_bot_limit INTEGER,
custom_ai_video_limit INTEGER
);
CREATE TABLE IF NOT EXISTS token_transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
discord_id INTEGER NOT NULL,
token_type TEXT NOT NULL,
amount INTEGER NOT NULL,
action TEXT NOT NULL,
actor_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (discord_id) REFERENCES users(discord_id)
);
"""
)
self.connection.commit()
def close(self) -> None:
self.connection.close()
def ensure_user(self, discord_id: int) -> None:
self.connection.execute(
"INSERT OR IGNORE INTO users (discord_id) VALUES (?)",
(discord_id,),
)
self.connection.commit()
def get_user(self, discord_id: int) -> sqlite3.Row:
self.ensure_user(discord_id)
row = self.connection.execute(
"SELECT * FROM users WHERE discord_id = ?", (discord_id,)
).fetchone()
if row is None:
raise RuntimeError("Unable to load the user record")
return row
def set_verified(self, discord_id: int) -> None:
self.ensure_user(discord_id)
self.connection.execute(
"UPDATE users SET verified = 1, verified_at = ? WHERE discord_id = ?",
(datetime.now(timezone.utc).isoformat(), discord_id),
)
self.connection.commit()
def set_limit(self, discord_id: int, token_type: str, limit: int) -> None:
self.ensure_user(discord_id)
column = {
"discord_bot": "custom_discord_bot_limit",
"ai_video": "custom_ai_video_limit",
}[token_type]
self.connection.execute(
f"UPDATE users SET {column} = ? WHERE discord_id = ?",
(limit, discord_id),
)
self.connection.commit()
def claim(
self,
discord_id: int,
token_type: str,
amount: int,
default_limit: int,
) -> tuple[int, int]:
self.ensure_user(discord_id)
claimed_column = {
"discord_bot": "discord_bot_claimed",
"ai_video": "ai_video_claimed",
}[token_type]
custom_limit_column = {
"discord_bot": "custom_discord_bot_limit",
"ai_video": "custom_ai_video_limit",
}[token_type]
row = self.connection.execute(
f"SELECT {claimed_column}, {custom_limit_column} FROM users WHERE discord_id = ?",
(discord_id,),
).fetchone()
if row is None:
raise RuntimeError("Unable to load the user record")
already_claimed = int(row[claimed_column])
limit = (
int(row[custom_limit_column])
if row[custom_limit_column] is not None
else default_limit
)
if already_claimed + amount > limit:
raise ValueError(
f"Only {max(0, limit - already_claimed)} {TOKEN_TYPES[token_type]} token(s) remain."
)
new_total = already_claimed + amount
with self.connection:
self.connection.execute(
f"UPDATE users SET {claimed_column} = ? WHERE discord_id = ?",
(new_total, discord_id),
)
self.connection.execute(
"""
INSERT INTO token_transactions
(discord_id, token_type, amount, action, actor_id, created_at)
VALUES (?, ?, ?, 'claim', ?, ?)
""",
(
discord_id,
token_type,
amount,