Metadata-Version: 2.4
Name: dc-securex
Version: 1.8.5
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 Anti-Nuke SDK

**Backend-only Discord anti-nuke protection.** You provide the UI, we provide the security logic.

[![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/)

## Installation

```bash
pip install dc-securex
```

## Quick Start

```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():
    # Enable protection with punishments
    await sx.enable(
        punishments={
            "channel_delete": "ban",
            "role_delete": "ban"
        }
    )

# Register callback for custom UI
@sx.on_threat_detected
async def alert(threat):
    print(f"⚠️ {threat.type} by {threat.actor_id} - Punishment: {threat.punishment_action}")

bot.run("TOKEN")
```

## Features

✅ **Channel Protection** - Detects & restores unauthorized channel changes  
✅ **Role Protection** - Detects & restores unauthorized role changes  
✅ **Member Protection** - Blocks unauthorized bots, bans, kicks  
✅ **Webhook Protection** - Removes spam webhooks  
✅ **Punishment System** - Configurable kick/ban/timeout/warn actions  
✅ **Role Position Monitoring** - 5-second checks with bulk restore  
✅ **Category Children Restoration** - Auto-restores child channels  
✅ **Auto-Backup** - Automatic server backups  
✅ **Whitelist System** - Manage authorized users  
❌ **No UI** - You decide how to present data!

---

## Complete API Reference

### Initialization

```python
sx = SecureX(bot, backup_dir="./data/backups")
```

**Parameters:**
- `bot` (required): Your discord.py Bot or Client instance
- `backup_dir` (optional): Path to store backups (default: `"./data/backups"`)

---

### `enable()` - Enable Protection

```python
await sx.enable(
    guild_id=None,
    whitelist=None,
    auto_backup=True,
    role_position_monitoring=True,
    punishments=None,
    timeout_duration=600,
    notify_user=True
)
```

**All Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `guild_id` | `int` | `None` | Specific guild to enable for (optional) |
| `whitelist` | `List[int]` | `None` | List of user IDs to whitelist |
| `auto_backup` | `bool` | `True` | Enable automatic backups |
| `role_position_monitoring` | `bool` | `True` | Enable 5-second role position checks |
| `punishments` | `Dict[str, str]` | `None` | Punishment actions per violation type |
| `timeout_duration` | `int` | `600` | Timeout duration in seconds (for timeout punishment) |
| `notify_user` | `bool` | `True` | Whether to DM violators about punishment |

**Punishment Configuration:**

Available actions: `"none"`, `"warn"`, `"timeout"`, `"kick"`, `"ban"`

Available violation types:
- `channel_delete` - Channel deletion
- `channel_create` - Mass channel creation
- `channel_update` - Channel permission/name changes
- `role_delete` - Role deletion
- `role_create` - Mass role creation
- `role_update` - Role permission changes
- `member_ban` - Unauthorized bans
- `member_kick` - Unauthorized kicks
- `webhook_create` - Webhook spam
- `webhook_spam` - Webhook abuse

**Examples:**

```python
# Example 1: Ban for delete, kick for create
await sx.enable(
    punishments={
        "channel_delete": "ban",
        "role_delete": "ban",
        "channel_create": "kick",
        "role_create": "kick"
    }
)

# Example 2: Use timeouts (30 minutes)
await sx.enable(
    punishments={
        "channel_delete": "timeout",
        "role_delete": "timeout"
    },
    timeout_duration=1800,
    notify_user=True
)

# Example 3: Just warnings (no action)
await sx.enable(
    punishments={
        "channel_delete": "warn",
        "role_create": "warn"
    }
)

# Example 4: No punishments (just restore)
await sx.enable()  # All violations default to "none"
```

---

### Other Methods

#### Backup Management

```python
# Create manual backup
backup_info = await sx.create_backup(guild_id)
# Returns: BackupInfo(guild_id, timestamp, channel_count, role_count, ...)
```

#### Threat History

```python
# Get recent threats
threats = await sx.get_recent_threats(guild_id, limit=10)
# Returns: List[ThreatEvent]
```

#### Whitelist Management

```python
# Add user to whitelist
await sx.whitelist.add(guild_id, user_id)

# Remove from whitelist
await sx.whitelist.remove(guild_id, user_id)

# Get all whitelisted users
users = await sx.whitelist.get_all(guild_id)
# Returns: List[int]

# Check if whitelisted
is_safe = await sx.whitelist.is_whitelisted(guild_id, user_id)
# Returns: bool
```

---

## Data Models

### ThreatEvent

```python
@dataclass
class ThreatEvent:
    type: str                    # "channel_delete", "role_create", etc.
    guild_id: int
    actor_id: int                # Who committed the violation
    target_id: int               # What was affected
    target_name: str
    prevented: bool              # Was it stopped?
    restored: bool               # Was it restored?
    timestamp: datetime
    details: Dict                # Additional context
    punishment_action: str       # What punishment was applied ("none", "warn", "kick", etc.)
```

**Methods:**
- `threat.to_dict()` - Convert to dictionary
- `threat.to_json()` - Convert to JSON string

### BackupInfo

```python
@dataclass
class BackupInfo:
    guild_id: int
    timestamp: datetime
    channel_count: int
    role_count: int
    backup_path: str
    success: bool
```

### RestoreResult

```python
@dataclass
class RestoreResult:
    success: bool
    items_restored: int
    items_failed: int
    errors: List[str]
    duration: float
    details: Dict
```

### WhitelistChange

```python
@dataclass
class WhitelistChange:
    guild_id: int
    user_id: int
    action: str              # "added" or "removed"
    timestamp: datetime
    moderator_id: int
```

---

## Callbacks

Register custom handlers for events:

```python
@sx.on_threat_detected
async def handle_threat(threat: ThreatEvent):
    # threat.punishment_action tells you what happened
    print(f"{threat.type} - Punishment: {threat.punishment_action}")

@sx.on_backup_completed
async def handle_backup(backup: BackupInfo):
    print(f"Backup completed: {backup.channel_count} channels")

@sx.on_restore_completed
async def handle_restore(result: RestoreResult):
    print(f"Restored {result.items_restored} items")

@sx.on_whitelist_changed
async def handle_whitelist(change: WhitelistChange):
    print(f"User {change.user_id} {change.action}")
```

---

## Advanced Examples

### Custom Discord Embed UI

```python
@sx.on_threat_detected
async def custom_alert(threat):
    embed = discord.Embed(
        title="🚨 Security Alert",
        description=f"**{threat.type.replace('_', ' ').title()}**",
        color=discord.Color.red()
    )
    embed.add_field(name="Violator", value=f"<@{threat.actor_id}>", inline=True)
    embed.add_field(name="Target", value=threat.target_name, inline=True)
    embed.add_field(name="Prevented", value="✅" if threat.prevented else "❌", inline=True)
    
    if threat.punishment_action and threat.punishment_action != "none":
        embed.add_field(
            name="Punishment",
            value=f"**{threat.punishment_action.upper()}**",
            inline=False
        )
    
    await log_channel.send(embed=embed)
```

### Webhook Integration

```python
@sx.on_threat_detected
async def send_to_webhook(threat):
    async with aiohttp.ClientSession() as session:
        await session.post(
            "https://your-webhook-url.com/alerts",
            json=threat.to_dict()
        )
```

### Database Logging

```python
@sx.on_threat_detected
async def log_to_database(threat):
    await db.execute(
        "INSERT INTO threats (type, actor_id, target_name, punishment) VALUES (?, ?, ?, ?)",
        threat.type, threat.actor_id, threat.target_name, threat.punishment_action
    )
```

### Multi-Mode Punishment

```python
@bot.command()
@commands.is_owner()
async def set_mode(ctx, mode: str):
    """Switch between strict/normal/lenient modes"""
    
    modes = {
        "strict": {
            "channel_delete": "ban",
            "channel_create": "ban",
            "role_delete": "ban",
            "role_create": "ban"
        },
        "normal": {
            "channel_delete": "kick",
            "channel_create": "timeout",
            "role_delete": "kick",
            "role_create": "timeout"
        },
        "lenient": {
            "channel_delete": "warn",
            "channel_create": "warn",
            "role_delete": "warn",
            "role_create": "warn"
        }
    }
    
    await sx.enable(punishments=modes.get(mode, {}))
    await ctx.send(f"✅ Set to {mode} mode")
```

---

## Why SDK Approach?

- 🎨 **Full UI Control** - Design your own embeds, dashboards, webhooks
- 📦 **Easy Integration** - Just `pip install` and import
- 🔒 **Battle-Tested Logic** - Proven anti-nuke protection
- 🚀 **No Boilerplate** - We handle the complex stuff
- 💰 **Reusable** - Use across multiple projects
- ⚙️ **Configurable** - Every parameter is optional with sensible defaults

## Requirements

- Python 3.8+
- discord.py 2.0+
- Bot with these intents: `guilds`, `members`, `bans`, `webhooks`
- Bot permissions: `MANAGE_CHANNELS`, `MANAGE_ROLES`, `BAN_MEMBERS`, `KICK_MEMBERS`, `MODERATE_MEMBERS`

## License

MIT License - see [LICENSE](LICENSE) file

## Support

- **PyPI**: [dc-securex](https://pypi.org/project/dc-securex/)
- **Issues**: Report bugs on GitHub
- **Examples**: Check the `examples/` directory

---

**Version 1.4.0** - Now with configurable punishment system!

Made with ❤️ by SecureX Team


**Backend-only Discord anti-nuke protection.** You provide the UI, we provide the security logic.

## Installation

```bash
pip install securex-antinuke
```

## Quick Start

```python
import discord
from discord.ext import commands
from securex import SecureX

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
sx = SecureX(bot)

# Enable protection
await sx.enable(whitelist=[123456789])

# Register callback - you build your own UI!
@sx.on_threat_detected
async def alert(threat):
    # threat.type, threat.actor_id, threat.prevented, etc.
    await channel.send(f"⚠️ Threat: {threat.type}")

bot.run("TOKEN")
```

## Features

✅ **Channel Protection** - Detects & restores unauthorized channel changes  
✅ **Role Protection** - Detects & restores unauthorized role changes  
✅ **Member Protection** - Blocks unauthorized bots, bans, kicks  
✅ **Webhook Protection** - Removes spam webhooks  
✅ **Auto-Backup** - Automatic server backups  
✅ **Whitelist System** - Manage authorized users  
✅ **Role Position Monitoring** - 5-second checks with bulk restore (NEW in v1.2!)  
❌ **No UI** - You decide how to present data!

## Data Objects

All callbacks receive **pure data objects** (no Discord embeds):

### ThreatEvent
```python
@dataclass
class ThreatEvent:
    type: str          # "channel_delete", "role_create", etc.
    guild_id: int
    actor_id: int      # Who did it
    target_id: int     # What was affected
    target_name: str
    prevented: bool    # Was it stopped?
    restored: bool     # Was it restored?
    timestamp: datetime
    details: dict      # Additional context
```

## Examples

### Custom Embed UI
```python
@sx.on_threat_detected
async def custom_alert(threat):
    embed = discord.Embed(
        title="🚨 Security Alert",
        description=f"Detected: {threat.type}"
    )
    embed.add_field(name="User", value=f"<@{threat.actor_id}>")
    await log_channel.send(embed=embed)
```

### Webhook Integration
```python
@sx.on_threat_detected
async def send_webhook(threat):
    await webhook.send(threat.to_json())
```

### Multi-Output
```python
@sx.on_threat_detected
async def handle(threat):
    # Send to Discord
    await channel.send(f"Threat: {threat.type}")
    
    # Log to database
    await db.insert(threat.to_dict())
    
    # Send to external API
    await api.post("/alerts", threat.to_json())
```

## API Reference

### Main Client

```python
sx = SecureX(bot, backup_dir=Path("./backups"))
```

### Methods

```python
await sx.enable(whitelist=[...], auto_backup=True, role_position_monitoring=True)
await sx.create_backup(guild_id)
await sx.get_recent_threats(guild_id, limit=10)
```

### Whitelist

```python
await sx.whitelist.add(guild_id, user_id)
await sx.whitelist.remove(guild_id, user_id)
users = await sx.whitelist.get_all(guild_id)
```

### Callbacks

```python
@sx.on_threat_detected       # ThreatEvent
@sx.on_backup_completed      # BackupInfo
@sx.on_restore_completed     # RestoreResult
@sx.on_whitelist_changed     # WhitelistChange
```

## Why SDK?

- 🎨 **Full UI Control** - Design your own embeds, dashboards, webhooks
- 📦 **Easy Integration** - Just `pip install` and import
- 🔒 **Battle-Tested Logic** - Proven anti-nuke protection
- 🚀 **No Boilerplate** - We handle the complex stuff
- 💰 **Reusable** - Use across multiple projects

## License

MIT License - see LICENSE file

## Support

- GitHub: [github.com/yourusername/securex-antinuke](https://github.com/yourusername/securex-antinuke)
- Issues: [Report a bug](https://github.com/yourusername/securex-antinuke/issues)

---

Made with ❤️ by SecureX Team
