This project is experimental and still under active development. It may contain bugs, incomplete features, or destructive code. Running it may damage your Discord server, bot data, or even your computer. Use extreme caution.
- Do not run this on a production server or with privileged accounts.
- Backup everything (server data, bot tokens, config files) before running.
- Run only in isolated environments — a disposable test Discord server, a VM, or a container/sandbox.
- Review the code thoroughly before executing. Do not run unreviewed scripts as root/administrator.
- Use throwaway Discord accounts/tokens when testing features that interact with Discord.
- I accept no responsibility for any loss, downtime, or damage caused by using this project.
- Create a fresh Discord server with no important members or data.
- Create a bot token tied to a test account with minimal permissions.
- Run the project inside a VM or container snapshot so you can rollback.
- Monitor logs and network activity while first running.
- Revoke the bot token and delete test accounts after finishing.
If you understand the risks and still want to proceed, you do so at your own risk. Consider adding more specific risks here (e.g., which commands may be destructive) as you develop the project.
A powerful Discord bot built with discord.py 2.6.4 that integrates Gemini 2.5 for AI-driven server management. Authorized users can perform administrative tasks like creating channels, managing roles, and more through natural language commands.
This bot implements multiple layers of security:
- AST Validation: All AI-generated code is parsed and validated before execution
- Role-Based Access Control: Only users with specified roles can use the bot
- Human-in-the-Loop: Manual approval required before executing any action
- Rate Limiting: Prevents abuse with configurable cooldowns
- Comprehensive Logging: All actions, errors, and validations are logged
- No Dangerous Operations: Blocks imports, file I/O, and system calls
- Python 3.11+
- Discord Bot Token
- Google Gemini API Key
- Discord Server with Administrator permissions
Copy .env.example to .env and fill in your real credentials. Do NOT commit .env.
cp .env.example .env
# then open and edit .env in your editorInstall the Python dependencies using the generated requirements.txt:
python -m pip install -r requirements.txtAlternatively use your preferred environment manager (venv, pipx, poetry).
Edit config.py only if you need to change defaults (rate limit, model, etc.).
Run the bot using:
python index.pyThe bot will:
- Connect to Discord
- Sync slash commands to your servers
- Start listening for
/aicommands
Execute an AI-powered server management task.
Examples:
/ai Create a text channel named "announcements"
/ai Create a role called "VIP" with blue color
/ai Make a private channel visible only to Moderators
/ai Delete the channel named "old-chat"
Clear your AI conversation history and start fresh.
- User: Type
/ai <task>with your request - AI: Generates Python code to accomplish the task
- Validation: Code is checked against security rules
- Confirmation: User approves or cancels the action
- Execution: If approved, code runs safely
- Feedback: User receives success or error message
User: /ai Create a text channel named "dev-logs"
Bot: 🧠 AI Generated Action Plan
Task: Create a text channel named "dev-logs"
Generated Code:
```python
guild = interaction.guild
await guild.create_text_channel('dev-logs')
[✅ Approve] [❌ Cancel]
User: clicks Approve
Bot: ✅ Task executed successfully!
## 🔐 Security Architecture
### Layer 1: Role Check
Only users with roles specified in `BOT_ALLOWED_ROLES` can use `/ai`.
### Layer 2: AST Validation
Generated code is parsed into an Abstract Syntax Tree and validated:
- ✅ **Allowed**: Discord API calls, control flow, basic Python operations
- ❌ **Blocked**: Imports, file I/O, `eval/exec`, system calls, meta-programming
### Layer 3: Human Confirmation
Users must click `✅ Approve` before any code executes.
### Layer 4: Safe Execution
Code runs in a controlled context with only necessary objects available.
### Layer 5: Rate Limiting
Each user can only make one request every 10 seconds (configurable).
### Layer 6: Logging
All actions, validations, and errors are logged for audit purposes.
## 🧠 AI System Prompt
The bot uses a structured protocol to communicate with Gemini:
- **JSON-only responses**: AI must respond with valid JSON
- **Code blocks**: Python code wrapped in ```python``` blocks
- **Error handling**: Automatic retry on validation/execution errors
- **User queries**: AI can ask clarifying questions
## 🎯 Supported Operations
### Channel Management
- Create text/voice channels
- Delete channels
- Modify channel settings
- Set channel permissions
- Create categories
### Role Management
- Create roles
- Assign/remove roles
- Modify role properties
- Delete roles
- Change role colors and permissions
### Utility Functions
Available helper functions in AI context:
**role_utils:**
- `get_role_by_name(guild, name)`
- `create_role_safe(guild, name, color, hoist, mentionable, permissions)`
- `assign_role_to_member(member, role)`
- `remove_role_from_member(member, role)`
- `delete_role_safe(role)`
- `modify_role_safe(role, ...)`
**channel_utils:**
- `create_text_channel_safe(guild, name, ...)`
- `create_voice_channel_safe(guild, name, ...)`
- `create_category_safe(guild, name, ...)`
- `get_channel_by_name(guild, name)`
- `delete_channel_safe(channel)`
- `modify_channel_safe(channel, ...)`
- `set_channel_permissions(channel, target, ...)`
## 🐛 Troubleshooting
### Bot doesn't respond to commands
1. Ensure bot has proper Discord permissions
2. Check that commands are synced: Look for "Commands synced" in logs
3. Verify your role is in `BOT_ALLOWED_ROLES`
### Validation errors
- The AI-generated code contains forbidden operations
- Bot will automatically ask AI to retry with valid code
- Check logs for specific validation errors
### Execution errors
- Code is valid but fails at runtime (e.g., role doesn't exist)
- Bot will send error back to AI for correction
- Review error message in the response
### Rate limit hit
- Wait the specified cooldown period (default: 10 seconds)
- Use `/reset` if conversation state is problematic
## 📊 Logging
Logs are written to:
- **Console**: Real-time output
- **bot.log**: Persistent log file
- **Discord Webhook** (optional): Visual logs in Discord channel
## ⚙️ Configuration Options
### Environment Variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `DISCORD_BOT_TOKEN` | Yes | - | Your Discord bot token |
| `GEMINI_API_KEY` | Yes | - | Your Google Gemini API key |
| `BOT_ALLOWED_ROLES` | No | `Administrator,Moderator` | Comma-separated role names |
| `LOG_WEBHOOK_URL` | No | `None` | Discord webhook for logging |
### config.py Constants
```python
RATE_LIMIT_SECONDS = 10 # Cooldown between commands
GEMINI_MODEL = "gemini-2.0-flash-exp" # Gemini model to use
PROTOCOL_VERSION = "1.1-AST" # Protocol version
This bot follows the design specification in the attached design document. Key principles:
- Security first - never compromise validation
- User-friendly - clear confirmations and error messages
- Robust - handle all edge cases gracefully
- Logged - track all actions for accountability
This project is provided as-is for educational and practical use.
If you encounter issues:
- Check bot.log for detailed error messages
- Verify all environment variables are set
- Ensure Discord bot has necessary permissions
- Review the security validation logs
- ✅ Natural language server management
- ✅ AST-based code validation
- ✅ Human-in-the-loop confirmation
- ✅ Automatic error recovery
- ✅ Rate limiting
- ✅ Comprehensive logging
- ✅ Role-based access control
- ✅ Conversation history per user
- ✅ AI can ask clarifying questions
Built with ❤️ using discord.py, ChatGPT, Copilot, Replit and Google Gemini AI