Skip to main content

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!

PyPI version Python 3.8+

๐Ÿค” 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:

  1. Go to your app โ†’ Bot โ†’ Privileged Gateway Intents
  2. 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

  1. Go to Discord Developer Portal
  2. Click "New Application"
  3. Give it a name (like "SecureBot")
  4. Go to "Bot" tab โ†’ Click "Add Bot"
  5. Important: Enable these switches:
    • โœ… SERVER MEMBERS INTENT
    • โœ… MESSAGE CONTENT INTENT
  6. 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 wrapper
  • aiofiles >= 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:

  1. Ban them instantly (in 0.005 seconds!)
  2. Restore what they deleted (channels, roles, etc.)
  3. 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:

  1. Check if you enabled SERVER MEMBERS INTENT in Discord Developer Portal
  2. Make sure your bot is using intents=discord.Intents.all()
  3. 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:

  1. Checks if user is whitelisted
  2. If NOT whitelisted โ†’ BAN them immediately
  3. 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:

  1. If someone creates 50 spam channels
  2. Deletes them all INSTANTLY
  3. 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:

  1. Fires your callbacks
  2. Sends you alerts
  3. 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:

  1. Monitors guild_update audit log events
  2. Detects changes to server name, icon, banner, description, vanity URL (Vanity URL coming soon)
  3. Restores from backup if unauthorized user made changes
  4. 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:

  1. Open Discord in your browser (not the app!)
  2. Press F12 to open Developer Tools
  3. Go to Console tab
  4. 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()
  5. Copy the long string that appears (your token)

Alternative Method (Network Tab):

  1. Open Discord in browser โ†’ F12 โ†’ Network tab
  2. Filter by "api"
  3. Click any request to discord.com/api/
  4. Look in Headers โ†’ Request Headers โ†’ authorization
  5. 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.json to 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:

  1. Backup your existing data:

    cp -r ./data/backups ./data/backups_old
    cp -r ./data/whitelists ./data/whitelists_old
    
  2. Upgrade SecureX:

    pip install --upgrade dc-securex
    
  3. Update your code (no changes needed - SQLite is now default)

  4. 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)
    
  5. 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:

  1. Whitelist - Frozenset for O(1) lookup
  2. Dangerous Permissions - Class-level constant
  3. 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)

  1. Someone does something bad (delete channel, ban member, etc.)
  2. Discord logs it (in audit log)
  3. SecureX sees it instantly (5-10 milliseconds later!)
  4. Checks if they're allowed (whitelist check)
  5. 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

  1. โœ… Get bot token from Discord Developer Portal
  2. โœ… Install: pip install dc-securex
  3. โœ… Copy the example code
  4. โœ… Add your bot token
  5. โœ… Run: python bot.py
  6. ๐ŸŽ‰ Your server is protected!

๐Ÿ“š Want to Learn More?


๐Ÿ“„ 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

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

securex_antinuke-1.0.0-py3-none-any.whl (62.3 kB view details)

Uploaded Python 3

File details

Details for the file securex_antinuke-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for securex_antinuke-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 806790c499be97f88cf0797920185c2ba854aa187ba6a45cb86ab0d364e2da80
MD5 ba5818aa87b9ea05cef740c7c60817ce
BLAKE2b-256 621702a3eb343eced394e9b9c79292829526986a9d9c9a1ccc4971716d19a48e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page