Skip to content
This repository was archived by the owner on Nov 13, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
cd6be59
fix: scope unban to the user's active ban cases
rnxm Nov 12, 2026
dec009b
refactor: move case lifecycle behind a CaseStore in cogs/mod/cases.py
rnxm Nov 12, 2026
606879f
refactor: resolve the response locale in one place
rnxm Nov 12, 2026
14a867d
fix: scope unban to the user's active ban cases (#111)
rnxm Nov 12, 2026
5d3fa27
refactor: move case lifecycle behind a CaseStore (#112)
rnxm Nov 12, 2026
6abcd88
refactor: resolve the response locale in one place (#113)
rnxm Nov 12, 2026
46c46cf
refactor: move case lifecycle behind a CaseStore (land #112 on dev) (…
rnxm Nov 12, 2026
16d12c3
refactor: add GuildSettings and move prefix, locale and retention ont…
rnxm Nov 12, 2026
d093f08
refactor: add GuildSettings; move prefix, locale and retention onto i…
rnxm Nov 12, 2026
1f2c36b
refactor: move log configuration onto GuildSettings
rnxm Nov 12, 2026
f629fc9
refactor: move log configuration onto GuildSettings (#116)
rnxm Nov 12, 2026
6dd54a7
refactor: move AutoMod, join/leave and level config onto GuildSettings
rnxm Nov 12, 2026
5bbf0b6
refactor: move AutoMod, join/leave and level config onto GuildSetting…
rnxm Nov 12, 2026
576cea1
fix: honour ephemeral from localization keys; drop dead invoke hooks
rnxm Nov 12, 2026
70136bd
fix: honour ephemeral from localization keys; drop dead invoke hooks …
rnxm Nov 12, 2026
5525ad2
refactor: route every economy balance change through a Ledger
rnxm Nov 12, 2026
cda403d
refactor: route every economy balance change through a Ledger (#119)
rnxm Nov 12, 2026
5c1e608
refactor: let localization own list layouts and the debt notice
rnxm Nov 12, 2026
dd210cd
refactor: let localization own list layouts and the debt notice (#120)
rnxm Nov 12, 2026
d9290e9
refactor: give every slash command its own localization keys
rnxm Nov 12, 2026
e46a905
refactor: give every slash command its own localization keys (#121)
rnxm Nov 12, 2026
df50903
test: check that every literal message key exists in en
rnxm Nov 12, 2026
74296b8
refactor: move ticket config and the giveaway's level check onto Guil…
rnxm Nov 12, 2026
06e1f7d
fix: report fallback level_config writes from the config commands
rnxm Nov 12, 2026
4748118
refactor: localize audit-log reasons and the remaining user-facing st…
rnxm Nov 12, 2026
cd74c43
perf: resolve case users once per listing instead of once per case
rnxm Nov 12, 2026
b72c661
test: cover info, setup, admin, voice, snapshot and log event delivery
rnxm Nov 12, 2026
0064cc1
fix: defer slash commands that can outlast Discord's 3-second window
rnxm Nov 12, 2026
b9fbdfc
test: check that every literal message key exists in en (#122)
rnxm Nov 12, 2026
f7ecdfa
refactor: localize audit-log reasons and the remaining user-facing st…
rnxm Nov 12, 2026
6a201bf
perf: resolve case users once per listing instead of once per case (#…
rnxm Nov 12, 2026
358b89d
test: cover info, setup, admin, voice, snapshot and log event deliver…
rnxm Nov 12, 2026
8722059
fix: defer slash commands that can outlast Discord's 3-second window …
rnxm Nov 12, 2026
af5e5cb
refactor: move ticket config and the giveaway's level check onto Guil…
rnxm Nov 12, 2026
8b6b57d
test: give the info cog test context an async defer
rnxm Nov 12, 2026
479e716
test: give the info cog test context an async defer (#128)
rnxm Nov 12, 2026
0eb8d0d
chore(deps): bump asyncpg from 0.31.0 to 0.32.0 (#103)
dependabot[bot] Nov 12, 2026
3aee885
chore(deps): bump ty from 0.0.95 to 0.0.99 (#106)
dependabot[bot] Nov 12, 2026
c9a3f40
chore(deps): bump sentry-sdk from 2.73.0 to 2.74.0 (#107)
dependabot[bot] Nov 12, 2026
80c1f29
feat: deploy behind a gateway proxy instead of reconnecting shards
rnxm Nov 13, 2026
e4cc1e5
refactor: keep strict SHARD_COUNT parsing and shorten deploy recipe docs
rnxm Nov 13, 2026
3049761
feat: deploy releases instead of main, restore required SHARD_COUNT
rnxm Nov 13, 2026
3c73798
feat: deploy behind a gateway proxy instead of reconnecting shards (#…
rnxm Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ SENTRY_DSN=sentry_sdk_dsn
# It's not recommended to mess with these values when self-hosting.
BOT_MODE=standalone # or "clustered"
# If you use BOT_MODE=standalone, settings below will be ignored.
SHARD_COUNT=64 # A shard usually contains 1000 servers
# SHARD_COUNT=64 # A shard usually contains 1000 servers; required with DISCORD_GATEWAY_URL
SHARDS_PER_CLUSTER=16 # One cluster (process) will manage up to 16 shards
# CLUSTER_ID=cluster-0 # Leave unset for automatic cluster ID assignment per replica
REDIS_URL=redis://redis:6379/0
REDIS_MSG_URL=redis://redis:6379/1
# DISCORD_PROXY_URL=http://twilight-proxy:3000/api/v10

# Gateway proxy - for production deployments that restart without reconnecting to Discord.
# Leave unset to connect to Discord directly (self-hosting, debug bot).
# COMPOSE_PROFILES=gateway-proxy
# DISCORD_GATEWAY_URL=ws://gateway-proxy:7878
# MIGRATE_ON_START=false # `just deploy` migrates before restarting the bot
2 changes: 2 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@ jobs:

- name: Run pytest
run: uv run pytest -v
env:
REQUIRE_DB_TESTS: "1"
12 changes: 7 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ This document defines architectural standards, technical conventions, and operat
- `slash_localization.py` (`SlashCommandLocalizer`): Subclasses `app_commands.Translator` to dynamically translate slash command names and descriptions from `slash_localization/`.
- `argument.py` & `command.py`: Serialization helpers converting Discord contexts/commands for formatted messages.
- `config.py` (`Config`): Runtime configuration parser loading `config.yml`.
- `clustering/`: Shard coordination (`ShardCoordinator`), session resumption (`SessionPersister`), distributed state (`StateStore`), event pub/sub (`EventBus`), and audit log buffers (`MessageBuffer`).
- `settings.py` (`GuildSettings`, `GuildSetting`): Cached per-guild settings with cross-instance invalidation. Register feature settings here instead of keeping a cog-level cache.
- `locale.py` (`resolve_locale`): The single rule for which locale a response uses.
- `clustering/`: Shard coordination (`ShardCoordinator`), gateway proxy connection (`gateway_proxy.py`), distributed state (`StateStore`), event pub/sub (`EventBus`), and audit log buffers (`MessageBuffer`).

#### `args/` (Safe String Formatting Wrappers)

Expand Down Expand Up @@ -78,12 +80,12 @@ Dataclasses decorated with `@dataclass(slots=True)` that wrap Discord objects (e
- `info.py`: Server, user, role, and bot diagnostic inspection commands.
- `join_leave.py`: Welcome/leave announcement handlers and autorole assignment.
- `level.py`: Message XP awarding, rank card generator (`?!level`), leaderboards (`?!levels`), and level role rewards.
- `log.py`: Server event audit logger (message edits/deletions, member changes, channel updates).
- `mod.py`: Moderation command suite (`ban`, `kick`, `mute`, `warn`, `clear`, case database logging).
- `log.py`: Server event audit logger (message edits/deletions, member changes, channel updates). `LogSettings` is the log configuration guild setting; the config commands use it too.
- `mod/`: Moderation command suite (`ban`, `kick`, `mute`, `warn`, `case`). `mod/cases.py` is the Case module: `CaseStore` owns every query on `cases`, retention, and expiry.
- `say.py`: Echo and Minecraft achievement message generators.
- `setup.py`: Interactive first-time server setup helper.
- `snapshot.py`: Guild structural backup and restoration system.
- `state_sync.py`: Distributed cluster sync listeners (invalidating prefix/log caches across instances).
- `state_sync.py`: Mirrors guild, channel and role data into the cluster `StateStore`. (Setting caches are invalidated by `core/settings.py`, not here.)
- `status.py`: Presence and bot activity status cycler.
- `ticket.py`: Interactive support ticket system with components, modals, and transcript export.
- `voice.py`: Lavalink v4 music playback controls via Wavelink.
Expand Down Expand Up @@ -185,4 +187,4 @@ Reuses existing repo labels where possible (`question`, `help wanted`, `wontfix`

### Domain docs

Single-context: root `GLOSSARY.md` + `docs/adr/`. See `docs/agents/domain.md`.
Single-context: root `GLOSSARY.md` holds both the domain terms and the settled decisions (no `docs/adr/`). See `docs/agents/domain.md`.
43 changes: 43 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Glossary

The words this codebase uses for its own concepts, and the decisions that shape it. Use these terms in code, issues and PRs.

## Terms

**Case**: one moderation action against a user in a guild: a warn, mute, kick or ban. Stored as a row in `cases`, identified by `case_id` (the ID of the message that triggered it). Represented by `Case` and its subclasses `Warn`, `Mute`, `Kick` and `Ban` in `cogs/mod/cases.py`.

**Active case**: a case that is still in force (`cases.active = true`). Closing a case makes it inactive or deletes it, depending on retention. An active case past its `expires` is *expired* until the scheduler closes it.

**Opening a case**: recording a new case and performing its Discord effect (timeout, kick, ban, DM). If the effect fails, the case is removed again.

**Closing a case**: ending an active case, either by hand (`unmute`, `unban`, `case remove`) or when it expires. Undoes the Discord effect (lifts the timeout or ban) and DMs the user. Closing an already inactive case has no side effects.

**Retention**: a guild's choice of what closing a case does: `keep` (mark it inactive, the default) or `delete` (remove the row). Stored in `mod_config.case_retention`. `case delete` always deletes, regardless of retention.

**Case store**: `CaseStore` in `cogs/mod/cases.py`, the only code that reads or writes `cases`. Commands and AutoMod open, close, edit and look up cases through it.

**Guild setting**: a per-guild configuration value (prefix, locale override, case retention, ...) behind a `GuildSetting` in `core/settings.py`. Read with `get` (or `cache` on hot synchronous paths), write with `set`; code that writes with targeted SQL calls `changed` afterwards instead. Writing persists it and announces an `INVALIDATE_SETTING` event so other bot instances reload it; callers never touch caches or the event bus. Settings with a meaningful default row (prefix, retention) create it from the column defaults on first load; feature settings (log, AutoMod, join/leave, leveling) treat a missing row as "not configured".

**Preloaded setting**: a guild setting whose values for every guild are loaded at startup (prefix, locale override), so synchronous code can read `cache`. Other settings load on first use.

**Locale override**: a guild's chosen bot language (`guild_locale_overrides`), set with `?!config locale`. It takes precedence over the user's Discord client locale and the guild's preferred locale; see `core/locale.py`.

**Log configuration**: a guild's event logging setup (`log` table, `LogConfig`, `LogSettings` in `cogs/log.py`): on/off, default channel, per-event channels, webhook and enabled modules. `modules = {'*'}` (the column default) means every module, including ones added later.

**Message buffering**: the bot keeps recent message content for guilds whose log configuration has message deletion or edit logging on (`Bot.message_logging_guilds`), so deleted and edited messages can be logged. Maintained automatically from the log configuration.

**Ledger**: `Ledger` in `cogs/economy.py`, the only code that changes `economy` balances. Each operation (`credit`, `debit`, `move`, `transfer`) is one transaction over row-locked accounts. Cash never goes negative; the bank goes negative only as **debt** (admin removals), and money credited while in debt pays it off first. A **Balance** is a member's `cash` and `bank` in one guild.

**List message**: a localized embed rendered with `CustomResponse.get_list`. Its first field is the **row template** (repeated per row), the remaining fields are the **empty state**, and `{page}`/`{pages}` work in the title, description and footer. Cogs pass rows, never edit rendered embeds. Optional parts of a message use a placeholder that is `None` when absent: the formatter drops that line, and a field left empty is dropped.

**Command key (`l10n_key`)**: the base under which a command's slash localization lives in `slash_localization/*.l10n.json`: `<key>-name`, `<key>-desc`, `<key>-usage`, `<key>-fallback` (a group's own callback, run as a subcommand) and `<key>-args-<param>-name|desc|<choice>`. It defaults to the command's name, and every subcommand has its own key, so subcommands with the same name are translated separately. The exception is `GroupCog` group names (`admin`, `economy`, `mod`, `voice`): discord.py builds those groups, so they use a top-level string. Built by `command_key` and read with `lookup` in `core/slash_localization.py`. `tests/test_slash_keys.py` fails when a key is missing. Groups need no description, because Discord never shows it.

## Decisions

**Config commands are temporary.** The `?!config` command tree (`cogs/config_subcommands/`) exists only until the web dashboard replaces it, after which the bot, backend, website and dashboard move into one monorepo. Fix bugs there and let it reuse shared modules when that costs nothing, but don't put architecture work into it (localizing its strings, restructuring, new tests).

**Cache invalidation uses Redis pub/sub.** Instances tell each other about changed guild settings over the existing Redis event bus (`core/clustering/`). Postgres `LISTEN/NOTIFY` triggers were considered, so outside writers such as the dashboard backend would invalidate caches automatically, and rejected until the monorepo move.

**Deploys restart the bot behind a gateway proxy.** Production runs [gateway-proxy](https://github.com/Gelbpunkt/gateway-proxy) (upstream image, pinned by digest, no fork for now), which keeps the shard connections open and replays a synthetic `READY` and `GUILD_CREATE`s from its cache when the bot connects, so a deploy sends no IDENTIFY. Resuming the old sessions from a fresh process was rejected: Discord sends no `READY` or `GUILD_CREATE` after a RESUME, so the new process starts with an empty cache. nirn-proxy was rejected because it only proxies REST. Voice sessions are not carried across restarts. Deploys stop the old bot before starting the new one; a blue-green handover would make both answer while they overlap, because the proxy sends every event to every client of a shard. Self-hosters connect to Discord directly.

**Message visibility is configured per message, not in code.** Whether a response is ephemeral (and whether it deletes itself) comes from its localization key, which the dashboard will make editable per message. Commands don't hard-code `ephemeral`, and the bot doesn't defer slash commands automatically (a deferred response's visibility can't be changed afterwards). Commands that can take longer than Discord's 3-second window (rank card, snapshots, `voice play`, `info ip`, `info template`) call `ctx.defer()` themselves, so their replies are public. Revisit deferring when the dashboard work starts.
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Then edit it:
docker compose up -d --build
```

Database migrations are applied automatically on every bot start.
Database migrations are applied automatically on every bot start (unless `MIGRATE_ON_START=false`).

Check that it's running:

Expand All @@ -84,6 +84,33 @@ docker compose logs -f bot
> [!WARNING]
> `docker compose down -v` / `just destroy` permanently deletes the database volume. Only use it in debug environments!

### Gateway proxy (production)

Production runs a [gateway proxy](https://github.com/Gelbpunkt/gateway-proxy) that holds the shard connections to
Discord. The bot connects to the proxy instead, so restarting it replays the guild state from the proxy's cache instead
of identifying every shard again (Discord allows one IDENTIFY per 5 seconds). Self-hosters don't need it: leave
`DISCORD_GATEWAY_URL` unset and the bot connects to Discord directly.

To enable it, set in `.env`:

```bash
COMPOSE_PROFILES=gateway-proxy
DISCORD_GATEWAY_URL=ws://gateway-proxy:7878
SHARD_COUNT=32 # must match the proxy; the bot refuses to start otherwise
MIGRATE_ON_START=false # `just deploy` runs migrations itself
```

The proxy's shard count comes from Discord's recommendation; `curl localhost:7878/shard-count` prints it. Its intents
in `gateway-proxy.json` must match the bot's (`discord.Intents.all()`), since the bot's own IDENTIFY never reaches
Discord.

- `just deploy` checks out the latest release, then rebuilds and restarts only the bot; the proxy keeps the shards
connected. `just deploy v0.9.0` deploys (or rolls back to) a given release, and `just deploy main` the testing branch.
- `just deploy-proxy` recreates the proxy, which reconnects every shard. Use it for proxy upgrades and shard count
changes only, and update `SHARD_COUNT` first when the count changes.

Voice sessions don't survive a bot restart: players that were playing stop and have to be started again.

### Debug mode

Set `debug: true` in `config.yml` and provide `DEBUG_TOKEN` in `.env`. The bot will log in with the debug token and
Expand Down
154 changes: 83 additions & 71 deletions cogs/automod.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
from helpers.regex import DISCORD_INVITE, URL_REGEX

if TYPE_CHECKING:
import asyncpg
from core import Bot
from core.settings import GuildSetting

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -94,46 +96,40 @@ def get_action(self, feature: str) -> dict[str, Any]:
return default_action


async def _load_automod(db: asyncpg.Pool, guild_id: int) -> AutoModConfig:
row = await db.fetchrow("SELECT guild_id, is_on, settings FROM automod_config WHERE guild_id = $1", guild_id)
return AutoModConfig.from_row(dict(row) if row else None, guild_id)


async def _save_automod(db: asyncpg.Pool, guild_id: int, config: AutoModConfig) -> None:
await db.execute(
"""
INSERT INTO automod_config (guild_id, is_on, settings)
VALUES ($1, $2, $3)
ON CONFLICT (guild_id) DO UPDATE SET is_on = EXCLUDED.is_on, settings = EXCLUDED.settings
""",
guild_id,
config.is_on,
config.settings,
)


class AutoMod(commands.Cog, name="AutoMod"):
"""Auto-moderation system managing filters, spam detection, and bypasses."""

def __init__(self, client: Bot) -> None:
self.client = client
self._config_cache: dict[int, AutoModConfig] = {}
self.config: GuildSetting[AutoModConfig] = client.settings.add("automod", _load_automod, _save_automod)
self._spam_tracker: dict[tuple[int, int], collections.deque[float]] = {}
self._last_prune: float = time.monotonic()

def invalidate_cache(self, guild_id: int) -> None:
"""Clear the config cache for a given guild."""
self._config_cache.pop(guild_id, None)

async def get_config(self, guild_id: int) -> AutoModConfig:
"""Fetch configuration for a guild, reading from cache or database."""
if guild_id in self._config_cache:
return self._config_cache[guild_id]

row = await self.client.db.fetchrow(
"SELECT guild_id, is_on, settings FROM automod_config WHERE guild_id = $1", guild_id
)
cfg = AutoModConfig.from_row(dict(row) if row else None, guild_id)
self._config_cache[guild_id] = cfg
return cfg
"""The guild's AutoMod configuration (disabled defaults if it has none)."""
return await self.config.get(guild_id)

async def save_config(self, config: AutoModConfig) -> None:
"""Persist configuration to the database and update cache."""
self._config_cache[config.guild_id] = config
await self.client.db.execute(
"""
INSERT INTO automod_config (guild_id, is_on, settings)
VALUES ($1, $2, $3::jsonb)
ON CONFLICT (guild_id) DO UPDATE SET
is_on = $2,
settings = $3::jsonb
""",
config.guild_id,
config.is_on,
json.dumps(config.settings),
)
"""Persist the configuration and tell other instances about it."""
await self.config.set(config.guild_id, config)

def is_bypassed(
self,
Expand Down Expand Up @@ -327,48 +323,8 @@ async def handle_violation(
logger.warning(f"Failed to delete automod violating message {message.id}: {e}")

case_type = action.get("case")
if case_type in ("warn", "mute") and isinstance(message.author, (discord.Member, discord.User)):
moderator: Any = self.client.user or guild.me
if not moderator:
return
reason = f"[AutoMod] {feature.title()} rule violation"
try:
if case_type == "warn":
from cogs.mod import Warn

warn_case = Warn(
_id=message.id,
bot=self.client,
guild=guild,
user=message.author,
moderator=moderator, # type: ignore[arg-type]
reason=reason,
message=message.content[:500] if message.content else None,
)
await warn_case.create(self.client.db)
elif case_type == "mute":
from cogs.mod import Mute

raw_duration = action.get("mute_duration", "5m")
try:
duration_sec = text_to_seconds(raw_duration) if raw_duration else 300
except (ValueError, TypeError):
duration_sec = 300

expires = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(seconds=duration_sec)
mute_case = Mute(
_id=message.id,
bot=self.client,
guild=guild,
user=message.author,
moderator=moderator, # type: ignore[arg-type]
expires=expires,
reason=reason,
message=message.content[:500] if message.content else None,
)
await mute_case.create(self.client.db)
except Exception:
logger.exception(f"Failed to create automod case for {message.author.id}")
if case_type in ("warn", "mute"):
await self._open_case(message, guild, feature, case_type, action)

if action.get("notify", True):
duration = int(action.get("notify_duration", 5))
Expand All @@ -386,6 +342,62 @@ async def handle_violation(
except Exception as e: # noqa: BLE001
logger.warning(f"Failed to send automod notification in channel {message.channel.id}: {e}")

async def _open_case(
self,
message: discord.Message,
guild: discord.Guild,
feature: str,
case_type: str,
action: dict[str, Any],
) -> None:
"""Open a warn or mute case for the author of a violating message through the Moderation cog."""
if not isinstance(message.author, (discord.Member, discord.User)):
return
moderator: Any = self.client.user or guild.me
if not moderator:
return
localized = await self.client.custom_response.get_message(f"automod.reasons.{feature}", guild)
reason = localized if isinstance(localized, str) else None
from cogs.mod import Moderation, Mute, Warn

mod_cog = self.client.get_cog("Moderation")
if not isinstance(mod_cog, Moderation):
logger.warning("AutoMod could not open a case: the Moderation cog is not loaded")
return
try:
case: Warn | Mute
if case_type == "warn":
case = Warn(
_id=message.id,
bot=self.client,
guild=guild,
user=message.author,
moderator=moderator, # type: ignore[arg-type]
reason=reason,
message=message.content[:500] if message.content else None,
)
else:
raw_duration = action.get("mute_duration", "5m")
try:
duration_sec = text_to_seconds(raw_duration) if raw_duration else 300
except (ValueError, TypeError):
duration_sec = 300

expires = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(seconds=duration_sec)
case = Mute(
_id=message.id,
bot=self.client,
guild=guild,
user=message.author,
moderator=moderator, # type: ignore[arg-type]
expires=expires,
reason=reason,
message=message.content[:500] if message.content else None,
)
await mod_cog.cases.open(case)
except Exception:
logger.exception(f"Failed to create automod case for {message.author.id}")

async def inspect_message(self, message: discord.Message, *, skip_spam: bool = False) -> None:
"""Inspect a message and apply active automod rules in priority sequence."""
if message.author.bot or message.webhook_id is not None or not message.guild:
Expand Down
Loading
Loading