01. The 3,000-line bot syndrome

Nearly every Discord bot project starts the same way: you open a main.py file, import discord.py, add four @bot.command() decorators and everything seems to be going smoothly. The trouble arrives two months later, when moderation, tickets, economy, welcome messages and levels all live in that same file.

At that point you have a 3,000-line monster. Touch something trivial in the economy's Russian roulette command, slip in a syntax error and the whole bot goes down, leaving every server it's in without moderation. Want to find where mute warnings were stored? Enjoy half an hour of scrolling through tangled functions.

The golden rule of the entry point
The main.py file should do only three things: start the client with strictly the intents it needs, open the database connection and load the modules. No command logic, no hand-written embeds and no mile-long handlers in there.

Dabot currently has 90+ cogs loaded at the same time and over 100,000 lines of Python. Keeping something like that running without losing your mind is only possible if every part of the bot is a sealed compartment that doesn't know (or care) what its neighbour is doing.

02. Cog architecture: isolate so you don't go down

A cog in discord.py is basically a class that groups commands, event listeners and background tasks under one topic. The key is physically separating them into folders:

Dabot's actual repository layout
├── main.py                 # Punto de entrada mínimo, intents y carga dinámica
├── cogs/                   # 90+ cogs, one per domain
│   ├── moderation.py       # Bans, kicks, mutes, cuarentena
│   ├── tickets.py          # Transcripts HTML, botones y feedback
│   ├── economy.py          # Monedas, transferencias, tienda
│   ├── antiraid.py         # Detección de joins masivos por segundo
│   └── ...
├── utils/                  # Helpers compartidos (base de datos, wrappers de API)
│   ├── db.py               # Conexiones SQLite y helpers WAL
│   └── i18n.py             # Diccionarios de idioma
└── dashboard_server.py     # API FastAPI que comparte la misma base de datos

Fault-tolerant loading in setup_hook

A serious mistake I see all the time is calling await bot.load_extension() blindly inside a loop. If module number 14 has an import error or is missing a key in the .env file, the exception stops execution and the next 50 modules never load.

In Dabot I wrote a fault-tolerant loading routine inside setup_hook. Each file is loaded in isolation inside a try/except block. If one fails, the traceback goes to the log and the bot keeps loading the rest without blinking:

main.py // modular loading with exception isolation
async def setup_hook(self):
    # Conexión asíncrona al pool de base de datos
    await self.init_db()

    # Carga dinámica de todos los cogs en cogs/*.py
    cogs_dir = pathlib.Path("cogs")
    for file in sorted(cogs_dir.glob("*.py")):
        if file.name.startswith("_") or file.name == "tts.py":
            continue  # Módulos deshabilitados a propósito

        ext_name = f"cogs.{file.stem}"
        try:
            await self.load_extension(ext_name)
            logger.info(f"[+] Cargado módulo: {ext_name}")
        except Exception as exc:
            logger.error(f"[!] Fallo crítico en {ext_name}: {exc}", exc_info=True)
            # El bot sigue vivo y carga los demás

The biggest advantage? You can run await bot.reload_extension("cogs.economy") while the bot is live. If you've just fixed a bug in the economy system, you upload the file to the VPS, run the reload command and the module is updated in memory in 15 milliseconds without dropping the Discord WebSocket or restarting the process.

03. The Postgres myth: SQLite in WAL mode

Almost every bot tutorial tells you to spin up a PostgreSQL container, another one for Redis caching and a queue in RabbitMQ or Celery. If you're running a bot in 200,000 servers with sharding across ten physical machines, fair enough. But for a private, community or mid-sized bot on a single VPS, that stack is shooting yourself in the foot.

In my case, Dabot shares its data between the Discord bot process and the FastAPI admin dashboard. Both use the same SQLite database. People tend to think SQLite locks up as soon as two processes write at once (the dreaded database is locked), but that only happens with the default settings from 15 years ago.

The 3 magic SQLite pragmas
When you initialise the database in Python, running these three pragmas is enough:
1. PRAGMA journal_mode = WAL; (Write-Ahead Logging: readers never block writers and writers never block readers).
2. PRAGMA synchronous = NORMAL; (Excellent performance on SSD / NVMe drives while keeping transactional integrity across OS restarts).
3. PRAGMA busy_timeout = 5000; (If one process is writing, the other politely waits up to 5 seconds instead of throwing an exception straight away).
utils/db.py // optimised SQLite WAL setup
import aiosqlite

async def get_db_connection(db_path: str = "dabot.db") -> aiosqlite.Connection:
    conn = await aiosqlite.connect(db_path)
    # Habilitar modo WAL y tiempos de espera concurrentes
    await conn.execute("PRAGMA journal_mode = WAL;")
    await conn.execute("PRAGMA synchronous = NORMAL;")
    await conn.execute("PRAGMA busy_timeout = 5000;")
    await conn.execute("PRAGMA foreign_keys = ON;")
    conn.row_factory = aiosqlite.Row
    return conn

With this setup I have around 170 tables in the same dabot.db file: moderation records, user economy, ticket logs and server configs. The bot answers commands instantly, the FastAPI dashboard reads and writes settings in real time, and the database adds literally zero megabytes of RAM overhead because it runs embedded in the process itself.

04. Common mistakes when writing async code

Programming with asyncio looks easy until you realise the bot has suddenly gone deaf and isn't answering anyone. These are the stumbles I've seen (and made) most often:

1. Blocking the main thread with synchronous functions

The discord.py engine runs on a single thread with an event loop. If an async command makes a call that takes 3 seconds and blocks the thread, the whole bot freezes for those 3 seconds. It doesn't handle messages, doesn't answer Gateway pings, and Discord assumes the bot is dead and forces a timeout disconnect.

Typical code you should never run directly:

  • requests.get() or urllib ➔ always use aiohttp.ClientSession().
  • time.sleep(5) ➔ always use await asyncio.sleep(5).
  • Generating images with Pillow or decoding large avatars ➔ send that heavy work to a worker thread with await asyncio.to_thread(heavy_function) or loop.run_in_executor().

2. Forgetting to defer slash command responses

Discord gives you exactly 3 seconds to respond to a slash command (/) interaction. If your database takes a little longer or you're calling a laggy external API, Discord shows the user the error: "The application did not respond".

The fix is immediate: if you know an operation might take more than 200 milliseconds, put await interaction.response.defer() on the first line. That tells Discord "I'm thinking, give me a moment" and extends your window to 15 minutes to edit the message with followup.send().

3. Memory leaks from uncontrolled caching

By default, discord.py caches up to 1,000 messages per text channel. If the bot is in several active servers, the in-memory message list keeps growing and eats your RAM.

When you initialise the client, tune the flags so it only caches what you actually need:

Sensible memory settings for the client
bot = commands.Bot(
    command_prefix="!",
    intents=intents,
    max_messages=100,  # En lugar de 1000, suficiente para borrados y logs
    chunk_guilds_at_startup=False  # No descargues todos los miembros si no hace falta
)

05. From idea to code: how to filter features

When you have your own bot, the biggest danger isn't bugs: it's runaway enthusiasm. An idea hits you at two in the morning and you start hammering out code for minigames, AI, a voice synthesiser and a Twitter clone. Three weeks later you have 20 half-finished commands that nobody uses and that need constant maintenance.

Over time I learned to apply a very strict filter so the project doesn't fill up with junk:

  1. Prototype in a temporary cog: I create an isolated file (for example cogs/experimental_game.py) without touching the main database or the stable modules.
  2. Test on a lab server: I try it on my own and with a couple of friends. If the feature lags, is boring or complicates permissions, the file gets deleted and nothing happened.
  3. Prune without mercy: Dabot once had an entire music playback module built on yt-dlp. The problem? Every week YouTube changed its extraction tokens or blocked the VPS's IPs, so I was constantly patching dependencies. I decided to cut my losses, remove the music module and focus on what a Discord bot should really do: relentless moderation, tools for staff and community dynamics. If you want local music done properly, that's why I built Davusic for the desktop.

06. Running 24/7 in Docker with a real heartbeat

Running the bot locally in a terminal window with python main.py is fine while you're coding, but in production on the VPS it has to start on its own when the server reboots and restart the container if something freezes.

My setup uses Docker Compose with two separate services that share the same volume and the same image:

  • dabot-bot: runs the Discord process.
  • dabot-api: runs the FastAPI web server with Uvicorn for the dashboard.

The witness-file healthcheck trick

Many people write a Docker healthcheck that checks whether the Python process is alive with pgrep python. That's misleading: a Python process can be running perfectly well while its asyncio loop is completely stuck in a deadlock.

To fix this, Dabot has a periodic task that writes the current timestamp to a temporary file every 30 seconds:

Internal heartbeat task and Docker check
# En main.py: Tarea en segundo plano en el loop de Discord
@tasks.loop(seconds=30)
async def heartbeat_file():
    try:
        pathlib.Path("/tmp/bot_alive").write_text(str(time.time()))
    except Exception:
        pass

# En docker-compose.yml:
healthcheck:
  test: ["CMD-SHELL", "test $(($(date +%s) - $(stat -c %Y /tmp/bot_alive))) -lt 60"]
  interval: 40s
  timeout: 10s
  retries: 3

If the event loop hangs for any unexpected reason, the task can't run, the /tmp/bot_alive file stops updating, Docker sees that the timestamp is more than 60 seconds old and restarts the container automatically, so you don't have to get up at midnight to see what happened.

07. Conclusions and a practical mindset

Building software that runs 24/7 on the internet isn't about using the most complex technology you can find on Hacker News or stacking 50 layers of infrastructure you don't need. It's about understanding exactly what each line of code does, where the bottlenecks are, and designing things so they're easy to debug when something breaks.

Splitting the code into independent modules (cogs), making the most of SQLite in WAL mode and never blocking the async loop are the three pillars that have let me run Dabot with 90+ cogs in production, rock solid and using barely 50 MB of memory on the server.

The three-line summary
1. Split by domain into cogs/ with isolated loading and hot reloading.
2. Don't add Postgres if SQLite in WAL mode gives you instant concurrent reads at no RAM cost.
3. Anything that takes longer than 50 ms goes to a worker thread with asyncio.to_thread.