Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Example environment file for 7xbot
# Copy this to .env and fill in your actual values

BOT_KEY=your_discord_bot_token_here
NOTDIAMOND_API_KEY=your_notdiamond_api_key_here
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ database.json
har_and_cookies/
role_slots.json
slowmode_settings.json

restart_flag
bot_restart.log
.env


# Byte-compiled / optimized / DLL files
Expand Down
198 changes: 198 additions & 0 deletions MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
# Migration Guide: Monolithic to Cog System

This guide explains how to complete the migration of remaining functionality from the original monolithic `7xbot.py` to the new cog system.

## Migration Status

### ✅ **Completed**
- Core bot infrastructure and cog loading system
- Admin commands (shutdown, eval, repl, debug)
- Basic utility commands (tc, echo, man, beta management)
- Points system and shop functionality
- Event handlers (on_ready, on_message, error handling)
- Database utilities and shared functions
- Restart monitoring system
- Documentation and examples

### 🔄 **Partially Migrated** (Placeholders Created)
- AI functionality (`cogs/ai.py`)
- Moderation system (`cogs/moderation.py`)
- Channel management (`cogs/channel_management.py`)

### 📋 **Remaining to Migrate**

#### From Original `7xbot.py` Lines ~900-1950:

1. **Full AI System** (lines 901-1050)
- Complex AI chat functionality with multiple models
- Flag parsing (`-s`, `-search`, `-model`)
- NotDiamond API integration
- Web search capabilities
- Response formatting and chunking

2. **Complete Moderation System** (lines 436-570)
- Strike/warning system with role escalation
- Filler spam command
- Warning and pardon commands with database tracking
- Lockdown mode implementation
- Spam ping detection

3. **Full Channel Management** (lines 1132-1560)
- HTTP command with complex deletion logic
- Message scanning and AI-based flagging
- Bulk message transfer between channels
- Auto-slowmode with traffic monitoring
- Message fetching and processing utilities

4. **Role Management System** (lines 1700-1850)
- Custom role creation with color support
- Role slot limitations (3 slots per user)
- Role deletion and cleanup
- Role slots persistence

5. **Poll System** (lines 1885-1950)
- Yes/No and multiple choice polls
- Timed poll management
- Vote collection and results

## Migration Instructions

### Step 1: AI System Migration

```python
# Move from 7xbot.py lines 901-1050 to cogs/ai.py
# Key components to migrate:
- parse_flags_and_content() function
- AI model integration (NotDiamond, g4f)
- Web search functionality
- Response chunking logic
- Model selection and routing
```

### Step 2: Moderation System Migration

```python
# Move from 7xbot.py lines 436-570 to cogs/moderation.py
# Key components to migrate:
- strike_roles array
- warn() command with role escalation
- pardon() command with database updates
- lockdown() implementation
- fillerspam() development tool
```

### Step 3: Channel Management Migration

```python
# Move from 7xbot.py lines 1132-1560 to cogs/channel_management.py
# Key components to migrate:
- http() command with all deletion modes
- AI message scanning functions
- Message transfer utilities
- Auto-slowmode traffic monitoring
- Data persistence functions
```

### Step 4: Role Management Migration

```python
# Create new cogs/roles.py
# Move from 7xbot.py lines 1700-1850
# Key components to migrate:
- role() command group
- Custom role creation logic
- Role slot management (SLOTS_FILE)
- Color validation and parsing
- Role cleanup on deletion
```

### Step 5: Poll System Migration

```python
# Create new cogs/polls.py or add to utility.py
# Move from 7xbot.py lines 1885-1950
# Key components to migrate:
- poll() command with timing
- Yes/No and multiple choice modes
- Vote collection via reactions
- Results calculation and display
```

## Migration Process

For each system:

1. **Extract Functions**: Copy relevant functions from `7xbot.py`
2. **Update Imports**: Add necessary imports to the cog file
3. **Adapt to Cog Structure**: Wrap in cog class and use `self.bot`
4. **Update Database Access**: Use shared database utilities from `cogs/database.py`
5. **Test Functionality**: Use `7/reload_cog <name>` to test changes
6. **Update Documentation**: Add commands to help system

## Example Migration Template

```python
# cogs/example.py
from discord.ext import commands
import discord
from .database import load_db, save_db

class ExampleCog(commands.Cog):
"""Description of cog functionality"""

def __init__(self, bot):
self.bot = bot
# Initialize any cog-specific data
self.example_data = {}

@commands.command()
async def example_command(self, ctx, arg: str):
"""Example command implementation"""
# Migrated functionality here
await ctx.send(f"Example: {arg}")

# Helper functions (previously global functions)
def example_helper(self, data):
"""Helper function migrated from original file"""
return processed_data

async def setup(bot):
await bot.add_cog(ExampleCog(bot))
```

## Testing Migration

1. **Syntax Check**: `python3 -m py_compile cogs/new_cog.py`
2. **Load Test**: Use `7/load_cog new_cog` in Discord
3. **Functionality Test**: Test all commands in the cog
4. **Reload Test**: Use `7/reload_cog new_cog` to verify hot-reloading
5. **Integration Test**: Ensure cog works with other cogs

## Benefits After Full Migration

- **No Downtime Updates**: Fix any component without bot restart
- **Feature Toggles**: Disable problematic features instantly
- **Development Isolation**: Work on features independently
- **Better Testing**: Test individual components in isolation
- **Cleaner Codebase**: Logical organization of related functionality

## Rollback Plan

The original `7xbot.py` file is preserved and can be used as a fallback:

```bash
# Emergency rollback to monolithic system
mv bot_main.py bot_main.py.backup
mv 7xbot.py bot_main.py
python3 bot_main.py
```

## Priority Order

1. **AI System** - Most complex, highest impact
2. **Moderation** - Critical for server management
3. **Channel Management** - Important admin tools
4. **Role Management** - User-facing features
5. **Poll System** - Nice-to-have functionality

This migration can be done incrementally, with each cog providing immediate benefits as it's completed.
145 changes: 145 additions & 0 deletions README_COG_SYSTEM.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# 7xBot Cog System Migration

This document explains the new cog-based architecture of 7xBot v2.0.

## Overview

The monolithic `7xbot.py` file has been restructured into a modular cog system that allows for:

- **Runtime reloading** of individual bot components without restarting
- **Selective enabling/disabling** of bot features
- **Better code organization** and maintainability
- **Emergency restart capability** with external script monitoring

## File Structure

```
7xbot/
├── bot_main.py # New main bot entry point
├── 7xbot.py # Original monolithic file (preserved)
├── restart_bot.sh # Bot restart monitoring script
├── .env.example # Environment variables template
├── cogs/
│ ├── __init__.py
│ ├── admin.py # Owner commands (shutdown, eval, repl)
│ ├── ai.py # AI functionality (placeholder)
│ ├── channel_management.py # Channel/message management
│ ├── database.py # Shared database utilities
│ ├── events.py # Event handlers (on_ready, on_message, etc.)
│ ├── moderation.py # Moderation commands
│ ├── points.py # Points system and shop
│ └── utility.py # Basic utility commands
└── test_cogs.py # Cog system testing script
```

## Usage

### Starting the Bot

1. **Standard startup:**
```bash
python3 bot_main.py
```

2. **With restart monitoring:**
```bash
./restart_bot.sh &
python3 bot_main.py
```

### Cog Management Commands

All cog management commands are owner-only:

- **Load a cog:** `7/load_cog <cog_name>`
- **Unload a cog:** `7/unload_cog <cog_name>`
- **Reload a cog:** `7/reload_cog <cog_name>`
- **List loaded cogs:** `7/list_cogs`
- **Restart entire bot:** `7/restart_bot`

### Examples

```bash
# Reload the admin cog after making changes
7/reload_cog admin

# Temporarily disable AI functionality
7/unload_cog ai

# List all currently loaded cogs
7/list_cogs

# Emergency restart the entire bot process
7/restart_bot
```

## Cog Descriptions

### admin.py
**Owner-only administrative commands:**
- `7/shutdown` - Graceful bot shutdown with countdown
- `7/eval` - Execute Python code
- `7/repl` - Interactive Python REPL in Discord
- `7/debug` - Debug command for testing

### utility.py
**Basic utility commands:**
- `7/tc` - Test channel connectivity
- `7/echo` - Echo messages
- `7/man` - Command manual/help
- `7/beta` - Beta tester management
- `7/cancel` - Toggle ecancel setting
- `7/derhop` - Fun command

### points.py
**Points system and shop:**
- `7/points add/remove/query` - Manage user points
- `7/shop` - Display purchasable items

### events.py
**Event handlers:**
- `on_ready` - Bot startup with status rotation
- `on_message` - Message processing and points awarding
- `on_command_error` - Error handling
- `on_guild_role_delete` - Role cleanup

### AI, Moderation, Channel Management
**Currently contain placeholder implementations** - the full functionality from the original monolithic file can be migrated to these cogs as needed.

## Migration Benefits

1. **Hot Reloading:** Fix bugs or add features without bot downtime
2. **Selective Disabling:** Turn off problematic features instantly
3. **Development Flexibility:** Work on individual components in isolation
4. **Emergency Recovery:** Full bot restart capability via external monitoring
5. **Code Organization:** Logical separation of concerns

## Restart System

The `restart_bot.sh` script provides a monitoring system that:

1. Watches for a `restart_flag` file
2. Kills the Python bot process when flag is detected
3. Waits for cleanup, then restarts the bot
4. Logs all restart activity to `bot_restart.log`

This allows the `7/restart_bot` command to trigger a complete process restart without manual intervention.

## Environment Setup

1. Copy `.env.example` to `.env`
2. Fill in your Discord bot token and API keys
3. Ensure Python dependencies are installed from `requirements.txt`

## Backward Compatibility

The original `7xbot.py` file is preserved for reference and emergency fallback. The new system maintains all existing command functionality while adding the modular architecture benefits.

## Development Workflow

1. Make changes to individual cog files
2. Use `7/reload_cog <cog_name>` to test changes instantly
3. Use `7/list_cogs` to verify loaded modules
4. Use `7/restart_bot` for full restart if needed

This system transforms 7xBot from a monolithic application into a flexible, maintainable, and hot-reloadable Discord bot framework.
Loading