Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 790
bot.py
import json
import logging
import os
import random
import re
import sqlite3
import uuid
from pathlib import Path
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",
)
log = logging.getLogger("rpg_bot")
GROUPS = {
"archive": "📚 The Eternal Archive",
"covenant": "🌑 The Umbral Covenant",
"vanguard": "🗡️ The Iron Vanguard",
"conclave": "🔮 The Arcane Conclave",
"wardens": "🏹 The Verdant Wardens",
"circle": "🧪 The Alchemical Circle",
"adventurers": "The Adventurers Guild",
}
PROMPTS = [
"A sealed letter arrives addressed to your character in handwriting they recognize—but cannot place.",
"The party finds a fresh set of footprints leading into a room with no other entrance.",
"A local celebration is interrupted when every bell in town rings thirteen times.",
"Your character is offered a favor in exchange for keeping a harmless-sounding secret.",
"An old rival asks for help, insisting there is no time to explain what happened.",
]
HOOKS = [
"Your character keeps a small object from a place they claim never to have visited.",
"Someone has been sending your character anonymous thank-you notes for a deed they deny doing.",
"Your character knows a lullaby that no one else seems to remember.",
"A personal promise your character made is about to conflict with their current goal.",
"Your character has been mistaken for a person with a very different reputation.",
]
EVENTS = [
"A night market where every stall trades in unusual services instead of coin.",
"A friendly inter-faction competition with cooperative and improvisational challenges.",
"A community expedition to map a newly accessible ruin; its contents are for staff to decide.",
"A seasonal gathering built around storytelling, games, and character introductions.",
"A missing courier mystery with several possible leads for players to investigate.",
]
class Database:
def __init__(self, path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self.connection = sqlite3.connect(self.path)
self.connection.row_factory = sqlite3.Row
self.connection.execute("PRAGMA foreign_keys = ON")
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id INTEGER PRIMARY KEY,
review_channel_id INTEGER
);
CREATE TABLE IF NOT EXISTS group_configs (
guild_id INTEGER NOT NULL,
group_key TEXT NOT NULL,
review_channel_id INTEGER,
leader_role_id INTEGER,
member_role_id INTEGER,
PRIMARY KEY (guild_id, group_key)
);
CREATE TABLE IF NOT EXISTS records (
id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
guild_id INTEGER NOT NULL,
applicant_id INTEGER NOT NULL,
group_key TEXT,
payload TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
reviewer_id INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
review_channel_id INTEGER,
message_id INTEGER
);
CREATE INDEX IF NOT EXISTS records_pending_idx
ON records(status, guild_id);
CREATE TABLE IF NOT EXISTS review_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
record_id TEXT NOT NULL REFERENCES records(id),
reviewer_id INTEGER NOT NULL,
comment TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS lore_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
author_id INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
)
self.connection.commit()
def execute(self, sql, values=()):
cursor = self.connection.execute(sql, values)
self.connection.commit()
return cursor
def one(self, sql, values=()):
return self.connection.execute(sql, values).fetchone()
def all(self, sql, values=()):
return self.connection.execute(sql, values).fetchall()
def create_record(self, record_id, kind, guild_id, applicant_id, group_key, payload, channel_id):
self.execute(
"INSERT INTO records (id, kind, guild_id, applicant_id, group_key, payload, review_channel_id) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(record_id, kind, guild_id, applicant_id, group_key, json.dumps(payload), channel_id),
)
class RPGModal(discord.ui.Modal):
def __init__(self, bot, kind, group_key=None):
self.bot = bot
self.kind = kind
self.group_key = group_key
if kind == "character":
super().__init__(title="Submit an Original Character")
self.name = discord.ui.TextInput(label="Character name", max_length=100)
self.summary = discord.ui.TextInput(
label="Concept and background", style=discord.TextStyle.paragraph, max_length=1500
)
self.personality = discord.ui.TextInput(
label="Personality, goals, or hooks", style=discord.TextStyle.paragraph,
required=False, max_length=1000,
)
for item in (self.name, self.summary, self.personality):
self.add_item(item)
else:
super().__init__(title=f"Apply to {GROUPS[group_key]}")
self.character = discord.ui.TextInput(label="Character name", max_length=100)
self.reason = discord.ui.TextInput(
label="Why do they want to join?", style=discord.TextStyle.paragraph, max_length=1200
)
self.details = discord.ui.TextInput(
label="Relevant experience or anything else", style=discord.TextStyle.paragraph,
required=False, max_length=800,
)
for item in (self.character, self.reason, self.details):
self.add_item(item)
async def on_submit(self, interaction: discord.Interaction):
if interaction.guild is None:
await interaction.response.send_message("Submissions are only available in a server.", ephemeral=True)
return
if self.kind == "character":
settings = self.bot.db.one(
"SELECT review_channel_id FROM guild_settings WHERE guild_id = ?", (interaction.guild_id,)
)
channel_id = settings["review_channel_id"] if settings else None
payload = {
"Character name": self.name.value,
"Concept and background": self.summary.value,
"Personality, goals, or hooks": self.personality.value or "Not provided",
}
else:
config = self.bot.db.one(
"SELECT review_channel_id FROM group_configs WHERE guild_id = ? AND group_key = ?",
(interaction.guild_id, self.group_key),
)
channel_id = config["review_channel_id"] if config and config["review_channel_id"] else None
if channel_id is None:
settings = self.bot.db.one(
"SELECT review_channel_id FROM guild_settings WHERE guild_id = ?", (interaction.guild_id,)
)
channel_id = settings["review_channel_id"] if settings else None
payload = {
"Character name": self.character.value,
"Why they want to join": self.reason.value,
"Additional details": self.details.value or "Not provided",
}
channel = interaction.guild.get_channel(channel_id) if channel_id else None
if channel is None or not isinstance(channel, discord.TextChannel):
await interaction.response.send_message(
"Applications are not accepting submissions right now. Please ask a server admin to configure the review channel.",
ephemeral=True,
)
return
record_id = uuid.uuid4().hex[:12]