Metadata-Version: 2.4
Name: dc-securex
Version: 2.21.1
Summary: Backend-only Discord anti-nuke protection SDK
Home-page: https://github.com/yourusername/securex-antinuke-sdk
Author: SecureX Team
Author-email: SecureX Team <contact@securex.dev>
License: MIT
Project-URL: Homepage, https://github.com/yourusername/securex-antinuke-sdk
Project-URL: Repository, https://github.com/yourusername/securex-antinuke-sdk
Project-URL: Issues, https://github.com/yourusername/securex-antinuke-sdk/issues
Keywords: discord,bot,antinuke,security,protection,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: discord.py>=2.0.0
Requires-Dist: aiofiles>=23.0.0
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# 🛡️ SecureX SDK - Discord Server Protection Made Easy

**Protect your Discord server from attacks in just 5 lines of code!**

[![PyPI version](https://badge.fury.io/py/dc-securex.svg)](https://pypi.org/project/dc-securex/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

## 🤔 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!

---

## ✨ What can it do?

✅ **Instant Protection** - Stops attacks in 5-10 milliseconds  
✅ **Auto Restore** - Brings back deleted channels and roles  
✅ **Smart Punishment** - Bans/kicks bad users automatically  
✅ **Easy Setup** - Just 5 lines of code!  
✅ **Your Design** - You build the commands & UI, we handle security  

---

## 📋 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:**
```bash
pip install dc-securex
```

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:**
```python
import discord
intents = discord.Intents.all()
```

Or specific intents:
```python
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
  ```bash
  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](https://discord.com/developers/applications)
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:**
```bash
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](https://python.org)
- During installation, check "Add Python to PATH"

**Install SecureX SDK:**
```bash
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)**
```bash
python -m venv venv
source venv/bin/activate
pip install dc-securex
```

**Verify installation:**
```bash
pip show dc-securex
```

You should see version 2.15.3 or higher!

---

## 🚀 Quick Setup (5 Steps!)

### Step 1: Install SecureX

Open your terminal/command prompt and type:
```bash
pip install dc-securex
```

### Step 2: Create Your Bot File

Create a file called `bot.py` and copy this code:

```python
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",
            "role_delete": "ban",
            "member_ban": "ban",
            "member_kick": "ban"
        }
    )
    print(f"✅ {bot.user.name} is online and protected!")

bot.run("YOUR_BOT_TOKEN_HERE")
```

### 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

```bash
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:

```python
from securex import SecureX
```
This imports the SecureX library.

```python
sx = SecureX(bot)
```
This connects SecureX to your bot.

```python
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) |

**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)

```python
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)

```python
await sx.enable(
    punishments={
        "channel_delete": "timeout",
        "role_delete": "timeout",
        "member_kick": "warn"
    }
)
```

### Example 3: Protection Without Punishment

```python
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:

```python
await sx.whitelist.add(guild_id, user_id)
```

**Example:**
```python
@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:

```python
@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):**

```python
@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:

```python
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](https://discordpy.readthedocs.io/) 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

---

### 🎯 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:**
```python


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?

- [Discord.py Docs](https://discordpy.readthedocs.io/) - Learn to make Discord bots
- [Python Tutorial](https://docs.python.org/3/tutorial/) - Learn Python basics
- [Discord Developer Portal](https://discord.com/developers/docs) - 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!**
