Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 664
bot.py
from __future__ import annotations
import json
import logging
import os
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import timedelta
from pathlib import Path
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("sixz_guard")
DATA_PATH = Path("data/security.json")
WINDOW_SECONDS = 20.0
DEFAULT_THRESHOLDS = {
"join": 8,
"channel_create": 8,
"channel_delete": 3,
"role_create": 8,
"role_delete": 3,
"ban": 5,
"kick": 5,
"webhook_change": 5,
}
@dataclass
class GuildState:
log_channel_id: Optional[int] = None
quarantine_role_id: Optional[int] = None
lockdown: bool = False
event_windows: dict[str, deque[float]] = field(
default_factory=lambda: defaultdict(deque)
)
spam_windows: dict[int, deque[float]] = field(
default_factory=lambda: defaultdict(deque)
)
previous_overwrites: dict[int, discord.PermissionOverwrite] = field(
default_factory=dict
)
thresholds: dict[str, int] = field(
default_factory=lambda: DEFAULT_THRESHOLDS.copy()
)
intents = discord.Intents.default()
intents.guilds = True
intents.members = True
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
guild_states: dict[int, GuildState] = {}
stored_config: dict[str, dict] = {}
commands_synced = False
def load_config() -> None:
global stored_config
try:
stored_config = json.loads(DATA_PATH.read_text(encoding="utf-8"))
if not isinstance(stored_config, dict):
stored_config = {}
except FileNotFoundError:
stored_config = {}
except (OSError, json.JSONDecodeError):
logger.exception("Could not load %s; using empty configuration", DATA_PATH)
stored_config = {}
def save_config() -> None:
DATA_PATH.parent.mkdir(parents=True, exist_ok=True)
DATA_PATH.write_text(
json.dumps(stored_config, indent=2, sort_keys=True), encoding="utf-8"
)
def get_state(guild: discord.Guild) -> GuildState:
state = guild_states.get(guild.id)
if state is not None:
return state
saved = stored_config.get(str(guild.id), {})
state = GuildState(
log_channel_id=saved.get("log_channel_id"),
quarantine_role_id=saved.get("quarantine_role_id"),
thresholds={**DEFAULT_THRESHOLDS, **saved.get("thresholds", {})},
)
guild_states[guild.id] = state
return state
def remember_state(guild: discord.Guild, state: GuildState) -> None:
stored_config[str(guild.id)] = {
"log_channel_id": state.log_channel_id,
"quarantine_role_id": state.quarantine_role_id,
"thresholds": state.thresholds,
}
save_config()
async def security_log(
guild: discord.Guild,
title: str,
description: str,
colour: discord.Colour = discord.Colour.orange(),
) -> None:
state = get_state(guild)
channel = guild.get_channel(state.log_channel_id) if state.log_channel_id else None
if not isinstance(channel, discord.TextChannel):
logger.warning("%s: %s — %s", guild.name, title, description)
return
embed = discord.Embed(
title=title,
description=description,
colour=colour,
timestamp=discord.utils.utcnow(),
)
try:
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
except (discord.Forbidden, discord.HTTPException):
logger.exception("Could not write to the security log in %s", guild.name)
async def find_audit_actor(
guild: discord.Guild,
action: discord.AuditLogAction,
target_id: Optional[int] = None,
) -> Optional[discord.abc.User]:
try:
async for entry in guild.audit_logs(limit=8, action=action):
target = getattr(entry, "target", None)
if target_id is not None and getattr(target, "id", None) != target_id:
continue
if (discord.utils.utcnow() - entry.created_at).total_seconds() <= 15:
return entry.user
except (discord.Forbidden, discord.HTTPException):
logger.warning("Could not inspect audit logs in %s", guild.name)
return None
async def ensure_quarantine_role(guild: discord.Guild) -> Optional[discord.Role]:
state = get_state(guild)
if state.quarantine_role_id:
role = guild.get_role(state.quarantine_role_id)
if role is not None and not role.managed:
return role
existing = discord.utils.get(guild.roles, name="Quarantine")
if existing is not None and not existing.managed:
state.quarantine_role_id = existing.id
remember_state(guild, state)
return existing
me = guild.me
if me is None or not me.guild_permissions.manage_roles:
return None
try:
role = await guild.create_role(
name="Quarantine",
colour=discord.Colour.dark_red(),
permissions=discord.Permissions.none(),
reason="Create defensive quarantine role",
)
except (discord.Forbidden, discord.HTTPException):
logger.exception("Could not create a quarantine role in %s", guild.name)
return None
state.quarantine_role_id = role.id
remember_state(guild, state)
return role
async def quarantine_member(
guild: discord.Guild,
user: discord.abc.User,
reason: str,
) -> None:
if bot.user is not None and user.id == bot.user.id:
return
member = guild.get_member(user.id)
me = guild.me
if member is None or me is None: