Backend-only Discord anti-nuke protection SDK
Project description
๐ก๏ธ SecureX SDK - Discord Server Protection Made Easy
Protect your Discord server from attacks in just 5 lines of code!
๐ค What is this?
SecureX is a Python library that protects your Discord server from people who try to destroy it.
Imagine someone gets admin powers and starts:
- ๐๏ธ Deleting all channels
- ๐ฅ Kicking everyone
- ๐ซ Banning members
- ๐ค Adding spam bots
SecureX stops them in milliseconds (0.005 seconds!) and fixes everything automatically!
โจ Features
- โก Instant Threat Response - Triple-worker architecture for microsecond-level detection
- ๐ก๏ธ Comprehensive Protection - Guards channels, roles, members, bots, webhooks, and guild settings
- ๐ Smart Backup & Restore - Automatic structural backups with intelligent restoration
- ๐ Vanity URL Protection (Coming Soon) - Restore and protect your server's custom invite URL
- ๐ Vanity URL Protection (Coming Soon) - Restore and protect your server's custom invite URL (Coming Soon)
- ๐พ SQLite Storage with WAL - Fast, reliable storage with Write-Ahead Logging for concurrent access
- ๐๏ธ Multiple Storage Backends - Choose between SQLite (default) or PostgreSQL
- ๐ฅ Flexible Whitelisting - Per-guild trusted user management
- โ๏ธ Customizable Punishments - Configure responses (ban/kick/none) per action type
- ๐ Event Callbacks - Hook into threat detection, backups, and restorations
- โ 90% Test Coverage - Comprehensive test suite with 100% coverage on critical paths
- ๐ Production Ready - Built with asyncio, type hints, and comprehensive error handling
๐ Requirements
Python & Dependencies
Required:
- โ Python 3.8 or higher
- โ discord.py 2.0.0 or higher (auto-installed)
- โ aiofiles 23.0.0 or higher (auto-installed)
Installation
Basic Installation (SQLite)
pip install dc-securex
With PostgreSQL Support
pip install dc-securex[postgres]
This automatically installs all required dependencies!
Discord Bot Permissions
REQUIRED Permissions (Bot won't work without these):
| Permission | Why Needed | Priority |
|---|---|---|
View Audit Log |
See who did what (CRITICAL!) | ๐ด MUST HAVE |
Manage Channels |
Restore deleted channels | ๐ด MUST HAVE |
Manage Roles |
Restore deleted roles | ๐ด MUST HAVE |
Ban Members |
Ban attackers | ๐ก For bans |
Kick Members |
Kick attackers | ๐ก For kicks |
Moderate Members |
Timeout attackers | ๐ก For timeouts |
Manage Webhooks |
Delete spam webhooks | ๐ข Optional |
Easy Invite Link:
https://discord.com/api/oauth2/authorize?client_id=YOUR_BOT_ID&permissions=8&scope=bot
Using permissions=8 gives Administrator (easiest for testing).
Discord Bot Intents
REQUIRED Intents (Enable in Developer Portal AND code):
In Discord Developer Portal:
- Go to your app โ Bot โ Privileged Gateway Intents
- Enable:
- โ SERVER MEMBERS INTENT
- โ MESSAGE CONTENT INTENT (if using commands)
In Your Code:
import discord
intents = discord.Intents.all()
Or specific intents:
intents = discord.Intents.default()
intents.guilds = True
intents.members = True
intents.bans = True
intents.webhooks = True
Bot Role Position
โ ๏ธ IMPORTANT: Your bot's role must be higher than roles it manages!
โ
CORRECT:
1. Owner
2. SecureBot โ Bot here
3. Admin
4. Moderator
โ WRONG:
1. Owner
2. Admin
3. SecureBot โ Bot too low!
4. Moderator
System Requirements
- OS: Windows, Linux, macOS (any OS with Python 3.8+)
- RAM: 512MB minimum (1GB recommended)
- Disk: 100MB for SDK + backups
- Network: Stable internet connection
- Discord: Bot must have access to audit logs
Optional (Recommended)
- Git - For version control
- Virtual Environment - Keep dependencies isolated
python -m venv venv source venv/bin/activate pip install dc-securex
๐ Before You Start
Step 1: Create a Discord Bot
- Go to Discord Developer Portal
- Click "New Application"
- Give it a name (like "SecureBot")
- Go to "Bot" tab โ Click "Add Bot"
- Important: Enable these switches:
- โ SERVER MEMBERS INTENT
- โ MESSAGE CONTENT INTENT
- Click "Reset Token" โ Copy your bot token (you'll need this!)
Step 2: Invite Bot to Your Server
Use this link (replace YOUR_BOT_ID with your bot's ID from Developer Portal):
https://discord.com/api/oauth2/authorize?client_id=YOUR_BOT_ID&permissions=8&scope=bot
Permission value 8 = Administrator (easiest for beginners)
Step 3: Install Python & Libraries
Check if Python is installed:
python --version
Requirements:
- โ Python 3.8 or newer (Python 3.10+ recommended)
- โ pip (comes with Python)
If you don't have Python:
- Download from python.org
- During installation, check "Add Python to PATH"
Install SecureX SDK:
pip install dc-securex
What gets installed automatically:
discord.py >= 2.0.0- Discord API wrapperaiofiles >= 23.0.0- Async file operations
Optional: Use Virtual Environment (Recommended)
python -m venv venv
source venv/bin/activate
pip install dc-securex
Verify installation:
pip show dc-securex
You should see version 2.15.3 or higher!
๐ Quick Start
Using SQLite (Default)
import discord
from securex import SecureX
bot = discord.Client(intents=discord.Intents.all())
sx = SecureX(bot) # SQLite storage automatically configured
@bot.event
async def on_ready():
await sx.enable(
guild_id=YOUR_GUILD_ID,
whitelist=[ADMIN_USER_ID_1, ADMIN_USER_ID_2],
auto_backup=True
)
print(f"โ
SecureX enabled for {bot.guilds[0].name}")
print(f"๐พ Using SQLite storage with WAL mode")
bot.run("YOUR_BOT_TOKEN")
Using PostgreSQL
import discord
from securex import SecureX
bot = discord.Client(intents=discord.Intents.all())
sx = SecureX(
bot,
storage_backend="postgres",
postgres_url="postgresql://user:password@localhost:5432/securex_db",
postgres_pool_size=10
)
@bot.event
async def on_ready():
await sx.enable(
guild_id=YOUR_GUILD_ID,
whitelist=[ADMIN_USER_ID],
auto_backup=True
)
print(f"โ
SecureX enabled with PostgreSQL storage")
bot.run("YOUR_BOT_TOKEN")
Step 3: Add Your Bot Token
Replace "YOUR_BOT_TOKEN_HERE" with the token you copied from Discord Developer Portal.
โ ๏ธ KEEP YOUR TOKEN SECRET! Never share it or post it online!
Step 4: Run Your Bot
python bot.py
You should see: โ
YourBotName is online and protected!
Step 5: Test It!
Your server is now protected! If someone tries to delete a channel or kick members without permission, SecureX will:
- Ban them instantly (in 0.005 seconds!)
- Restore what they deleted (channels, roles, etc.)
- Log the attack (so you know what happened)
๐ฏ Understanding the Code
Let's break down what each part does:
from securex import SecureX
This imports the SecureX library.
sx = SecureX(bot)
This connects SecureX to your bot.
await sx.enable(punishments={...})
This turns on protection and sets punishments:
"ban"= Ban the attacker"kick"= Kick them out"timeout"= Mute them for 10 minutes"none"= Just restore, don't punish
๐ง What Can You Protect?
Here are ALL the things you can protect:
| Type | What it stops | Available Punishments |
|---|---|---|
channel_delete |
Deleting channels | "none", "warn", "timeout", "kick", "ban" |
channel_create |
Creating too many channels (spam) | "none", "warn", "timeout", "kick", "ban" |
role_delete |
Deleting roles | "none", "warn", "timeout", "kick", "ban" |
role_create |
Creating too many roles (spam) | "none", "warn", "timeout", "kick", "ban" |
member_kick |
Kicking members | "none", "warn", "timeout", "kick", "ban" |
member_ban |
Banning members | "none", "warn", "timeout", "kick", "ban" |
member_unban |
Unbanning people | "none", "warn", "timeout", "kick", "ban" |
webhook_create |
Creating spam webhooks | "none", "warn", "timeout", "kick", "ban" |
bot_add |
Adding bad bots | Always "ban" (automatic) |
vanity_url_code |
Changing server vanity URL | Coming soon |
vanity_url_code |
Changing server vanity URL | Coming soon |
Punishment Options Explained:
"none"- Only restore, don't punish"warn"- Send warning message"timeout"- Mute for 10 minutes (configurable)"kick"- Kick from server"ban"- Ban from server
๐จ Simple Examples
Example 1: Strict Mode (Ban Everything)
await sx.enable(
punishments={
"channel_delete": "ban",
"channel_create": "ban",
"role_delete": "ban",
"role_create": "ban",
"member_kick": "ban",
"member_ban": "ban"
}
)
Example 2: Gentle Mode (Warn Only)
await sx.enable(
punishments={
"channel_delete": "timeout",
"role_delete": "timeout",
"member_kick": "warn"
}
)
Example 3: Protection Without Punishment
await sx.enable()
This only restores deleted stuff but doesn't punish anyone.
๐ฅ Whitelist (Allow Trusted Users)
Want to allow some people to delete channels? Add them to the whitelist:
await sx.whitelist.add(guild_id, user_id)
Example:
@bot.command()
@commands.is_owner()
async def trust(ctx, member: discord.Member):
await sx.whitelist.add(ctx.guild.id, member.id)
await ctx.send(f"โ
{member.name} is now trusted!")
@bot.command()
@commands.is_owner()
async def untrust(ctx, member: discord.Member):
await sx.whitelist.remove(ctx.guild.id, member.id)
await ctx.send(f"โ {member.name} is no longer trusted!")
๐ Get Notified When Attacks Happen
Add this to your code to get alerts:
@sx.on_threat_detected
async def alert(threat):
print(f"๐จ ATTACK DETECTED!")
print(f" Type: {threat.type}")
print(f" Attacker: {threat.actor_id}")
print(f" Punishment: {threat.punishment_action}")
Fancier Alert (Discord Embed):
@sx.on_threat_detected
async def fancy_alert(threat):
channel = bot.get_channel(YOUR_LOG_CHANNEL_ID)
embed = discord.Embed(
title="๐จ Security Alert!",
description=f"Someone tried to {threat.type}!",
color=discord.Color.red()
)
embed.add_field(name="Attacker", value=f"<@{threat.actor_id}>")
embed.add_field(name="What Happened", value=threat.target_name)
embed.add_field(name="Punishment", value=threat.punishment_action.upper())
await channel.send(embed=embed)
๐ Full Working Example
Here's a complete bot with commands:
import discord
from discord.ext import commands
from securex import SecureX
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
sx = SecureX(bot)
@bot.event
async def on_ready():
await sx.enable(punishments={"channel_delete": "ban", "member_ban": "ban"})
print(f"โ
{bot.user.name} is protecting {len(bot.guilds)} servers!")
@sx.on_threat_detected
async def log_attack(threat):
print(f"๐จ Stopped {threat.type} by user {threat.actor_id}")
@bot.command()
@commands.is_owner()
async def trust(ctx, member: discord.Member):
await sx.whitelist.add(ctx.guild.id, member.id)
await ctx.send(f"โ
{member.mention} can now manage the server!")
@bot.command()
@commands.is_owner()
async def untrust(ctx, member: discord.Member):
await sx.whitelist.remove(ctx.guild.id, member.id)
await ctx.send(f"โ {member.mention} is no longer trusted!")
@bot.command()
async def ping(ctx):
await ctx.send(f"๐ Pong! Protection active!")
bot.run("YOUR_BOT_TOKEN")
โ Common Questions
Q: Will this slow down my bot?
A: No! SecureX is SUPER fast (5-10 milliseconds). Your bot will work normally.
Q: What if I accidentally delete a channel?
A: If you're the server owner, SecureX won't stop you! Or add yourself to the whitelist.
Q: Can I change punishments later?
A: Yes! Just call await sx.enable(punishments={...}) again with new settings.
Q: Does it work on multiple servers?
A: Yes! It automatically protects all servers your bot is in.
Q: What if my bot goes offline?
A: When it comes back online, it automatically creates new backups. But it can't stop attacks while offline.
Q: How do I make my own commands?
A: Check discord.py documentation to learn more about making bot commands!
๐ง Troubleshooting
โ "Missing Permissions" Error
Solution: Make sure your bot has Administrator permission, or at least these:
- Manage Channels
- Manage Roles
- Ban Members
- Kick Members
- View Audit Log
โ Bot doesn't detect attacks
Solution:
- Check if you enabled SERVER MEMBERS INTENT in Discord Developer Portal
- Make sure your bot is using
intents=discord.Intents.all() - Check if bot role is above other roles in Server Settings โ Roles
โ Can't restore deleted channels
Solution: Bot role must be higher than the roles it needs to manage
๐๏ธ Architecture (How It Works Under the Hood)
SecureX uses a Triple-Worker Architecture for maximum speed and reliability. Here's how it works:
โก The Triple-Worker System
Think of SecureX like a security team with 3 specialized workers:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DISCORD SERVER โ
โ (Someone deletes a channel, kicks a member, etc.) โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DISCORD AUDIT LOG EVENT (Instant!) โ
โ Discord creates a log entry: "User X deleted #general"โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ (5-10 milliseconds)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SECUREX EVENT LISTENER โ
โ (Catches the audit log instantly) โ
โโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโ โโโโโโโ โโโโโโโ
โ Q1 โ โ Q2 โ โ Q3 โ (3 Queues)
โโโโฌโโโ โโโโฌโโโ โโโโฌโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ
โWorker 1 โ โWorker 2 โ โWorker 3 โ
โ Action โ โ Cleanup โ โ Log โ
โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ
๐จ Worker 1: Action Worker (PUNISHER)
Job: Ban/kick bad users INSTANTLY
What it does:
- Checks if user is whitelisted
- If NOT whitelisted โ BAN them immediately
- Takes only 5-10 milliseconds!
Example:
User "Hacker123" deletes #general
โ (5ms later)
Action Worker: "Hacker123 is NOT whitelisted"
โ
*BANS Hacker123 instantly*
๐งน Worker 2: Cleanup Worker (CLEANER)
Job: Delete spam creations (channels, roles, webhooks)
What it does:
- If someone creates 50 spam channels
- Deletes them all INSTANTLY
- Prevents server from getting cluttered
Example:
User creates spam channel "#spam1"
โ (10ms later)
Cleanup Worker: "Unauthorized channel!"
โ
*Deletes #spam1 immediately*
๏ฟฝ Worker 3: Log Worker (REPORTER)
Job: Alert you about attacks
What it does:
- Fires your callbacks
- Sends you alerts
- Logs everything for review
Example:
Attack detected!
โ
Log Worker: Calls your @sx.on_threat_detected
โ
You get an alert embed in Discord!
๐ Restoration System (Separate from Workers)
Job: Restore deleted stuff from backups
How it works:
Channel deleted
โ (500ms wait for audit log)
โ
Restoration Handler checks: "Was this authorized?"
โ NO
โ
Looks in backup: "Found #general backup!"
โ
*Recreates channel with same permissions*
Automatic Backups:
- Creates backup every 10 minutes
- Saves: Channels, roles, permissions, positions
- Stored in
./data/backups/folder
๐ฐ Worker 4: Guild Worker (GUILD SETTINGS PROTECTOR)
NEW in v2.15+! The Guild Worker protects and restores critical guild settings.
Job: Restore guild name, icon, banner, vanity URL when changed unauthorized (Vanity restoration coming soon)
What it does:
- Monitors
guild_updateaudit log events - Detects changes to server name, icon, banner, description, vanity URL (Vanity URL coming soon)
- Restores from backup if unauthorized user made changes
- Uses user tokens for vanity URL restoration (Discord API limitation) (Coming soon)
Protected Settings:
- โ Server Name
- โ Server Icon
- โ Server Banner
- โ Server Description
- โ Vanity URL (requires user token)
- โ Vanity URL (requires user token) (Coming soon)
Example:
Unauthorized user changes server name to "HACKED SERVER"
โ (50ms wait for audit log)
โ
Guild Worker checks: "Was this authorized?"
โ NO
โ
Looks in backup: "Found original name: Cool Community"
โ
*Restores server name to "Cool Community"*
๐ Setting Up Guild Worker (Vanity URL Support Coming Soon)
Important: Vanity URL restoration requires a user token due to Discord API limitations. Bot tokens cannot modify vanity URLs. (Coming soon)
Step 1: Get Your User Token (One-Time Setup)
โ ๏ธ WARNING: Your user token is VERY sensitive! Never share it publicly!
How to get it:
- Open Discord in your browser (not the app!)
- Press
F12to open Developer Tools - Go to Console tab
- Type:
window.webpackChunkdiscord_app.push([[''],{},e=>{m=[];for(let c in e.c)m.push(e.c[c])}]);m.find(m=>m?.exports?.default?.getToken!==void 0).exports.default.getToken() - Copy the long string that appears (your token)
Alternative Method (Network Tab):
- Open Discord in browser โ
F12โ Network tab - Filter by "api"
- Click any request to
discord.com/api/ - Look in Headers โ Request Headers โ
authorization - Copy the token value
Step 2: Set The User Token in Your Bot
@bot.event
async def on_ready():
await sx.enable(punishments={...})
# Set user token for vanity URL restoration (Coming soon)
guild_id = 1234567890 # Your server ID
user_token = "YOUR_USER_TOKEN_HERE" # From step 1
await sx.guild_worker.set_user_token(guild_id, user_token)
print("โ
Guild settings protection enabled with vanity URL support! (Coming soon)")
Step 3: Test It!
Try changing your server's vanity URL - SecureX will restore it automatically! (Coming soon)
Full Example:
import discord
from discord.ext import commands
from securex import SecureX
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
sx = SecureX(bot)
@bot.event
async def on_ready():
# Enable punishments
await sx.enable(punishments={"channel_delete": "ban"})
# Set user token for each guild
for guild in bot.guilds:
token = get_user_token_for_guild(guild.id) # Your token storage
await sx.guild_worker.set_user_token(guild.id, token)
print(f"โ
{bot.user.name} protecting {len(bot.guilds)} servers!")
bot.run("YOUR_BOT_TOKEN")
๐ฏ Guild Worker API
Set User Token:
await sx.guild_worker.set_user_token(guild_id, "user_token_here")
Get User Token:
token = sx.guild_worker.get_user_token(guild_id)
Remove User Token:
await sx.guild_worker.remove_user_token(guild_id)
Check If Token Is Set:
if sx.guild_worker.get_user_token(guild_id):
print("Token is configured!")
else:
print("No token set - vanity restoration won't work! (Coming soon)")
๐พ User Token Storage
User tokens are automatically saved to ./data/backups/user_tokens.json for persistence.
Token Data Model:
from securex.models import UserToken
# Create token metadata
token_data = UserToken(
guild_id=123456789,
token="user_token_here",
set_by=999888777, # Admin who set it
description="Production server token"
)
# Track usage
token_data.mark_used() # Updates last_used timestamp
# Serialize
token_dict = token_data.to_dict()
Storage Format (user_tokens.json):
{
"1234567890": "user_token_abc...",
"9876543210": "user_token_xyz..."
}
โ ๏ธ Important Notes About User Tokens
Security:
- โ
Tokens are stored locally in
./data/backups/ - โ
Never commit
user_tokens.jsonto Git! - โ
Add to
.gitignore:data/backups/user_tokens.json - โ ๏ธ User tokens are more powerful than bot tokens - keep them secure!
Limitations:
- User tokens can only restore vanity URLs
- User tokens can only restore vanity URLs (Coming soon)
- Other guild settings (name, icon, banner) use bot permissions
- User must be a server owner or have Manage Guild permission
- User token must be from someone with vanity URL access
- User token must be from someone with vanity URL access (Coming soon)
What Happens Without User Token:
Unauthorized user changes vanity URL
Unauthorized user changes vanity URL (Coming soon)
โ
Guild Worker tries to restore
โ
โ ๏ธ No user token set!
โ
Prints: "No user token set for guild 123! Cannot restore vanity."
Prints: "No user token set for guild 123! Cannot restore vanity. (Coming soon)"
โ
Other settings (name, icon) still restored via bot!
๐ Complete Guild Protection Flow
Timeline of Guild Name Change:
0ms - Unauthorized user changes server name
50ms - Discord audit log updated
75ms - Guild Worker detects change
80ms - Checks whitelist (user not whitelisted)
85ms - Loads backup (finds original name)
100ms - Calls guild.edit(name="Original Name")
300ms - Server name restored!
๐พ Storage Backends
SecureX v3.0+ supports two storage backends for maximum flexibility:
๐๏ธ SQLite (Default)
The recommended choice for most users. SQLite provides fast, reliable local storage with zero configuration.
Features:
- โ Zero Configuration - Works out of the box
- โ WAL Mode - Write-Ahead Logging for concurrent read/write
- โ ACID Compliant - Guaranteed data integrity
- โ
Single File - All data in
./data/securex.db - โ High Performance - Indexed queries, fast I/O
- โ No Dependencies - Built into Python
Usage:
# Automatic (default)
sx = SecureX(bot)
# Explicit
sx = SecureX(bot, storage_backend="sqlite")
# Custom database path
sx = SecureX(bot, storage_backend="sqlite", backup_dir="./custom/path")
# Database will be at: ./custom/path/securex.db
What WAL Mode Means: Write-Ahead Logging allows multiple simultaneous readers while one writer is active. This means SecureX can read backups while creating new ones, preventing any blocking.
๐ PostgreSQL (Optional)
For enterprise deployments requiring centralized database management or multi-instance setups.
Features:
- โ Centralized Storage - Single database for multiple bot instances
- โ Connection Pooling - Efficient resource usage
- โ Advanced Queries - Full SQL capabilities
- โ Professional Tools - pgAdmin, psql, monitoring
- โ Scalable - Handle thousands of guilds
Installation:
pip install dc-securex[postgres]
This installs the asyncpg driver.
Usage:
import discord
from securex import SecureX
bot = discord.Client(intents=discord.Intents.all())
sx = SecureX(
bot,
storage_backend="postgres",
postgres_url="postgresql://username:password@host:5432/database",
postgres_pool_size=10 # Optional, default: 10
)
@bot.event
async def on_ready():
await sx.enable(guild_id=YOUR_GUILD_ID)
print("โ
Connected to PostgreSQL")
bot.run("YOUR_BOT_TOKEN")
Connection URL Format:
postgresql://username:password@hostname:port/database_name
Examples:
# Local PostgreSQL
postgres_url = "postgresql://securex:mypassword@localhost:5432/securex_db"
# Remote server
postgres_url = "postgresql://user:pass@db.example.com:5432/prod_securex"
# With connection pooling
sx = SecureX(
bot,
storage_backend="postgres",
postgres_url=postgres_url,
postgres_pool_size=20 # Max connections
)
๐ Storage Backend Comparison
| Feature | SQLite | PostgreSQL |
|---|---|---|
| Setup Complexity | Zero config | Requires DB server |
| Installation | Built-in | pip install dc-securex[postgres] |
| Performance | Excellent | Excellent |
| Concurrency | WAL mode (good) | Connection pooling (excellent) |
| Scalability | Up to ~100 guilds | Unlimited |
| Multi-Instance | No | Yes |
| Maintenance | Zero | DB administration |
| Best For | Most use cases | Enterprise deployments |
๐ Migrating from JSON to SQLite
If you're upgrading from SecureX v2.x (JSON storage):
Important: JSON data is not automatically migrated. The new SQLite backend starts fresh.
Migration Steps:
-
Backup your existing data:
cp -r ./data/backups ./data/backups_old cp -r ./data/whitelists ./data/whitelists_old
-
Upgrade SecureX:
pip install --upgrade dc-securex
-
Update your code (no changes needed - SQLite is now default)
-
Re-add whitelisted users:
@bot.event async def on_ready(): await sx.enable(guild_id=YOUR_GUILD_ID) # Re-add your whitelisted users await sx.whitelist.add(YOUR_GUILD_ID, USER_ID_1) await sx.whitelist.add(YOUR_GUILD_ID, USER_ID_2)
-
Create fresh backups:
# Automatic on first enable await sx.enable(guild_id=YOUR_GUILD_ID, auto_backup=True) # Or manual backup_info = await sx.create_backup(YOUR_GUILD_ID) print(f"โ Backup created: {backup_info.channel_count} channels, {backup_info.role_count} roles")
What You'll Lose:
- Historical JSON backup files (new SQLite backups will be created)
- Old JSON whitelist files (re-add users)
- User tokens (re-configure if using vanity URL restoration)
- User tokens (re-configure if using vanity URL restoration) (Coming soon)
What You'll Gain:
- ๐ Faster performance with indexed queries
- ๐ Better data integrity with ACID transactions
- โก Concurrent access with WAL mode
- ๐ฆ Single file storage instead of multiple JSON files
๐ง Storage Configuration
SQLite Configuration:
sx = SecureX(
bot,
storage_backend="sqlite",
backup_dir="./data/backups" # Database location
)
# Creates: ./data/backups/securex.db
PostgreSQL Configuration:
sx = SecureX(
bot,
storage_backend="postgres",
postgres_url="postgresql://user:pass@host:5432/db",
postgres_pool_size=15 # Connection pool size
)
Environment Variables (Recommended for Production):
import os
sx = SecureX(
bot,
storage_backend=os.getenv("STORAGE_BACKEND", "sqlite"),
postgres_url=os.getenv("DATABASE_URL") # For PostgreSQL
)
.env file:
STORAGE_BACKEND=postgres
DATABASE_URL=postgresql://securex:password@localhost:5432/securex_db
DISCORD_TOKEN=your_bot_token_here
Multi-Setting Attack:
User changes: name + icon + banner + vanity
User changes: name + icon + banner + vanity (Vanity coming soon)
- Vanity: Restored via user token (API) (Coming soon)
โ
Guild Worker restores ALL in one go:
- Name: Restored via bot
- Icon: Restored via bot
- Banner: Restored via bot
- Vanity: Restored via user token (API)
โ
Total time: ~500ms for all 4 settings!
๐ Guild Worker vs Other Workers
| Worker | Speed | What It Protects | Token Needed |
|---|---|---|---|
| Action Worker | 5-10ms | Punishes attackers | Bot token โ |
| Cleanup Worker | 10-20ms | Deletes spam | Bot token โ |
| Log Worker | 15ms | Sends alerts | Bot token โ |
| Guild Worker | 50-500ms | Server settings | Bot + User token โ ๏ธ |
Why Guild Worker is slower:
- Waits for audit log (50ms)
- Loads backup from disk
- Makes API calls to restore
- Vanity URL uses external API endpoint
But still VERY fast compared to manual restoration!
๐ฏ Why Triple Workers?
Speed:
- Workers don't wait for each other
- All process in parallel
- Punishment happens in 5-10ms!
Reliability:
- If one worker crashes, others keep working
- Each worker has its own queue
- No single point of failure
Separation:
- Punishment (fast) โ Restoration (slower but thorough)
- Action Worker = instant ban
- Restoration Handler = careful rebuild
๐ Data Flow Example
Let's say "BadUser" deletes 5 channels:
Timeline:
0ms - BadUser deletes #general
5ms - SecureX detects it (audit log)
7ms - Broadcasts to 3 workers
10ms - Action Worker BANS BadUser
12ms - Cleanup Worker ready (no cleanup needed)
15ms - Log Worker alerts you
500ms - Restoration Handler starts
750ms - #general recreated with permissions
Result:
- โ BadUser banned in 10ms
- โ You alerted in 15ms
- โ #general restored in 750ms
- โ Total response: Less than 1 second!
๐ง Smart Permission Detection
When someone updates a member's roles:
User "Sneaky" gives Admin role to "Friend"
โ
Member Update Handler triggered
โ
Checks: "Is Sneaky whitelisted?"
โ NO
โ
Scans ALL roles of "Friend"
โ
Finds roles with dangerous permissions:
- Administrator โ
- Manage Roles โ
- Ban Members โ
โ
*Removes ALL dangerous roles in ONE API call*
โ
Friend is now safe!
Dangerous Permissions Detected:
- Administrator
- Kick Members
- Ban Members
- Manage Guild
- Manage Roles
- Manage Channels
- Manage Webhooks
- Manage Emojis
- Mention Everyone
- Manage Expressions
๐พ Caching System
SecureX uses caching for maximum speed:
Cached Data:
- Whitelist - Frozenset for O(1) lookup
- Dangerous Permissions - Class-level constant
- Guild Backups - Updated every 10 minutes
Why This Matters:
OLD (v1.x):
Check whitelist โ Database query (50-100ms)
NEW (v2.x):
Check whitelist โ Memory lookup (0.001ms)
50,000x faster!
๐ How It Works (Simple Summary)
- Someone does something bad (delete channel, ban member, etc.)
- Discord logs it (in audit log)
- SecureX sees it instantly (5-10 milliseconds later!)
- Checks if they're allowed (whitelist check)
- If NOT allowed:
- Bans/kicks them (punishment)
- Restores what they deleted (from backup)
- Alerts you (via callback)
All of this happens automatically while you sleep! ๐ด
๐ Next Steps
- โ Get bot token from Discord Developer Portal
- โ
Install:
pip install dc-securex - โ Copy the example code
- โ Add your bot token
- โ
Run:
python bot.py - ๐ Your server is protected!
๐ Want to Learn More?
- Discord.py Docs - Learn to make Discord bots
- Python Tutorial - Learn Python basics
- Discord Developer Portal - Official Discord docs
๐ License
MIT License - Free to use! โค๏ธ
๐ Support
Having issues? Questions? Found a bug?
- Open an issue on GitHub
- Read this README carefully
- Check if your bot has all permissions
Made with โค๏ธ for Discord bot developers
Version 2.15.5 - Lightning-fast server protection!
๐ Start protecting your server today!
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dc_securex-3.3.4-py3-none-any.whl.
File metadata
- Download URL: dc_securex-3.3.4-py3-none-any.whl
- Upload date:
- Size: 62.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0ecb74cd4eb002f5e64a4aaa939dae23fbe8f0bdd232b8e27c473c5240bdcf9e
|
|
| MD5 |
46a6c03c0ea9f01f03db8bebbb95b5d0
|
|
| BLAKE2b-256 |
e2deb3cb75a16dddf5a46baa5a47fb1d2ec2aa76cf7a13c26efe1ac6403a46d9
|