Interesting

Build a Discord RPG server bot from scratch. It should be configurable by server admins and have an inviting, polished interactive experience using Discord slash commands, embeds, buttons, select menus, and modals where appropriate. Core features: (1) Original Character submissions: players submit an OC through an interactive form; the bot posts each submission in an admin-configurable review channel. Staff can accept, decline, or comment, with outcomes/comments communicated to the applicant. (2) Faction and guild applications: interactive faction picker featuring exactly these choices: 📚 The Eternal Archive; 🌑 The Umbral Covenant; 🗡️ The Iron Vanguard; 🔮 The Arcane Conclave; 🏹 The Verdant Wardens; 🧪 The Alchemical Circle; and the Adventurers Guild Joining requires an application through the bot; the relevant guild/faction leaders can accept or decline, and the workflow should be configurable per group. (3) RPG lore assistant: help players discover server lore from an editable, staff-managed source; clearly distinguish official lore from generated suggestions and avoid inventing canon. (4) Roleplay support for staff and players, such as scene prompts, character hooks, event ideas, and staff utilities. Include secure configuration for the Discord bot token, persistence for submissions/applications/configuration, permission checks, sensible error handling, and setup documentation. Preserve privacy by restricting review actions and avoid exposing private submissions publicly beyond the configured review channel and applicant communications. Do not claim to reuse or migrate code from the existing Discord Chatbot project.

Kodari AI
KodariOct 4 at 6:35 pm 1
DiscordRPGServerBot
Creates a comprehensive Discord RPG server bot from scratch. Features interactive OC submission forms with staff review workflows, faction and guild applications with configurable leader approvals, an editable lore assistant distinguishing official canon from suggestions, and roleplay utilities. Includes secure token configuration, persistent storage for submissions and settings, permission checks, error handling, and setup documentation. Preserves privacy by restricting review actions to configured channels and applicant communications.
  1. Create the discord.py bot with interactive OC reviews and configurable faction/guild applications.

  2. Add SQLite persistence, staff-managed official lore, and roleplay utilities.

  3. Add secure environment setup, dependencies, and deployment/setup documentation.

Created the Discord RPG bot with interactive character submissions and private staff reviews, configurable faction/guild applications, an editable official lore archive, and clearly labeled non-canon roleplay prompts. SQLite persists applications, configuration, and lore; bot secrets are read from .env.

Added bot.py, requirements.txt, .env.example, and setup documentation in README.md.

Interesting

Allow me to add the bot token

Kodari AI
KodariOct 4 at 6:37 pm 1

Add your Discord bot token in .env by replacing add_your_discord_bot_token_here. The file is excluded from Git so the token won’t be committed.

Interesting

Refine the bot, make it visually appealing and more interactive

Kodari AI
KodariOct 4 at 6:41 pm 1
  1. Add a polished private RPG welcome panel that routes players into character, faction, lore, and inspiration flows.

  2. Upgrade review posts and applicant messages with clearer status, themed embeds, and interactive prompt refreshes.

  3. Improve lore responses and document the new /rpg entry point.

Refined the bot with a private /rpg welcome panel linking players to character submissions, group applications, official lore search, and roleplay inspiration. Updated reviews and applicant DMs with clearer themed embeds, and added buttons to refresh scene prompts or switch to character hooks. Also documented /rpg in the README.

Interesting

Restart the bot

Kodari AI
KodariOct 4 at 6:44 pm 1

I can’t restart the hosted process from this chat. Use the bot project’s Restart control in Kodari to relaunch it with the latest changes.

Interesting

Bot is responding to commands

Kodari AI
KodariOct 4 at 6:59 pm 1

Great—the bot is online and responding to commands. No restart is needed right now.

Interesting

It is not

Kodari AI
KodariOct 4 at 6:59 pm 1

You’re right—I misread your message. The bot is not responding.

I can’t restart the hosted process from this chat. In Kodari, restart the bot project, then check its logs for startup or slash-command sync errors. If it still doesn’t respond, share the relevant log output and I can help pinpoint the issue.

Interesting

Pinpoint issue and fix

Kodari AI
KodariOct 4 at 7:02 pm 1
  1. Fix command propagation by supporting fast server-specific slash-command sync.

  2. Document the optional GUILD_ID setting and keep global sync as the default.

  3. Note the root cause and the one setting needed to apply the fix.

The bot only synced slash commands globally, which can delay new or updated commands from appearing. I added optional guild-specific syncing: set GUILD_ID in .env to your server’s numeric ID, then restart the bot. Without GUILD_ID, it continues using global sync.

If commands are already visible but still time out when used, this sync issue may not be the cause; the bot logs would be needed to pinpoint that.

Interesting

Is it fixed

Kodari AI
KodariOct 4 at 7:05 pm 1

The slash-command sync fix was added, but I can’t confirm the running bot is fixed without checking it. Set GUILD_ID in .env to your server’s ID, then restart the bot in Kodari. If commands still don’t respond afterward, share the startup or error logs.

Kodari can make mistakes. Review important code before using.
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]