Advanced Telegram Bot for detecting NSFW content in user profile pictures within groups
This project was created out of necessity when I needed a compact NSFW detection solution for Telegram groups but had limited disk quota on server. Traditional NSFW detection models are often hundreds of megabytes or even gigabytes in size, making them impractical for resource-constrained environments.
This bot uses an optimized TensorFlow Lite model (INT8 quantized) based on the NSFW model by GantMan that's only a few megabytes while maintaining good accuracy for detecting inappropriate user bots with NSFW profile pictures in groups.
- π― Lightweight: Ultra-small model size optimized for limited storage (~8-10MB)
- β‘ Fast Detection: Efficient TensorFlow Lite inference (100-300ms per image)
- π Async Processing: Non-blocking NSFW detection with queue system
- π Detailed Analysis: Confidence scores and category breakdown
- π¨ Admin Alerts: Immediate notifications to group administrator
- π False Alert Reporting: Built-in feedback system for improving accuracy
- π Webhook Support: Production-ready with webhook deployment
- πΎ Database Integration: PostgreSQL with async operations
- ποΈ Group Management: Per-group settings with kick/delete options
- π Permission Control: Automatic permission checking and validation
- π’ Admin Commands: Built-in announcement system for developers
- ποΈ Modular Architecture: Clean separation of concerns with handlers
The project follows a clean, modular architecture with separated concerns:
βββ bot/ # Main bot package
β βββ main.py # Bot initialization and startup logic
β βββ settings.py # Configuration and environment variables
β βββ database.py # Database models and connection
β βββ detect.py # NSFW detection engine
β βββ nsfw_worker.py # Background worker for async processing
β βββ keyboards.py # Telegram keyboard layouts
β βββ utils.py # Utility functions and callback data
β βββ handlers/ # Message and event handlers
β β βββ commands.py # Command handlers (/start, /say)
β β βββ messages.py # Message processing and group monitoring
β β βββ callback_queries.py # Inline button handlers
β β βββ chat_members.py # Group membership events
β β βββ common.py # Shared handler functions
β βββ migrations/ # Database migrations
βββ model/ # AI model files
β βββ model_int8.tflite # Quantized TensorFlow Lite model
βββ run.py # Main application launcher
βββ pyproject.toml # Modern Python project configuration
βββ requirements.txt # Python dependencies
βββ README.md # This file
bot/main.py- Application entry point with bot initialization and lifecycle managementbot/handlers/- Modular handlers for different types of Telegram eventsbot/nsfw_worker.py- Asynchronous background worker for NSFW detectionbot/database.py- Database models with async support and connection poolingrun.py- Production launcher with webhook/polling support
The detection model classifies images into 5 categories:
- drawings - Artistic/cartoon content
- hentai - Explicit animated content
- neutral - Safe content
- porn - Explicit real content
- sexy - Suggestive content
NSFW threshold combines: porn + hentai + sexy probabilities
git clone https://github.com/abduakhads/spot-userbot.git
cd nsftbotUsing uv (recommended):
uv syncOr using pip:
pip install -r requirements.txtCreate a .env file with the following variables:
# Bot Configuration
BOT_TOKEN=your_bot_token_from_botfather
DEVELOPER_ID=your_telegram_user_id
# Database Configuration
DATABASE_NAME=your_database_name
DATABASE_USER=your_database_user
DATABASE_PASSWORD=your_database_password
DATABASE_HOST=your_database_host
DATABASE_PORT=5432
# Webhook Configuration (Optional)
USE_WEBHOOK=false
WEBHOOK_SECRET=your_webhook_secret
BASE_WEBHOOK_URL=https://yourdomain.comEnsure PostgreSQL is running and create your database:
CREATE DATABASE your_database_name;
CREATE USER your_database_user WITH PASSWORD 'your_database_password';
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_database_user;Tables are created automatically at start of the bot.
python run.pySet USE_WEBHOOK=true in your .env file and configure your web server.
Add this location block to your Nginx configuration:
location /webhook {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://127.0.0.1:8080;
}Then restart Nginx and run the bot:
python run.py# Install ngrok and run
ngrok http 8080
# Copy the HTTPS URL to BASE_WEBHOOK_URL in .env# Install jprq and run
jprq http 8080
# Copy the HTTPS URL to BASE_WEBHOOK_URL in .env- Start the bot: Send
/startto your bot in a private chat - Add to group: Add the bot to your supergroup
- Automatic monitoring: The bot monitors user profile pictures and alerts admin of NSFW content
- Manage settings: Use "My Groups π₯" button to configure per-group settings
- My Groups π₯: View and manage all groups the bot monitors
- Individual Settings: Configure kick and delete options per group
- Permission Validation: Automatic checking of bot permissions
- Kick User Bots: Automatically ban users with NSFW profile pictures
- Delete Messages: Remove messages from users with NSFW content
- Smart Permission Handling: Settings auto-disable if bot lacks permissions
- False Alert Reporting: Users can report false positives via inline buttons
- Developer Announcements: Broadcast messages to all bot users
- Detailed Logging: Comprehensive detection results with confidence scores
- Markdown-Safe Reporting: Proper escaping of special characters in reports
- Link Generation: Direct links to flagged messages and profiles
- Multi-Category Analysis: Detailed breakdown of detection categories
/start- Initialize the bot and get welcome message- My Groups π₯ (button) - View and manage monitored groups
/say <message>- Broadcast announcement to all bot users (developer only)
The bot requires the following permissions for full functionality:
- Restrict Members - To kick users with NSFW content (if enabled)
- Delete Messages - To remove messages with NSFW content (if enabled)
Note: Settings automatically disable if the bot lacks required permissions
- Modular Handler System: Clean separation of commands, messages, callbacks, and chat events
- Async Queue Processing: Background workers prevent blocking on detection tasks
- Database Connection Pooling: Efficient PostgreSQL connections with peewee-async
- Smart Permission Management: Automatic detection and handling of bot permissions
- Migration System: Structured database schema updates
- Enhanced Error Handling: Comprehensive exception handling and fallbacks
commands.py:/start,/say(announcements), and other bot commandsmessages.py: Group message processing and profile picture detectioncallback_queries.py: Inline keyboard interactions and settings managementchat_members.py: Group join/leave events and permission changescommon.py: Shared functionality for group management
- User Management: Track all users for announcements
- Group Settings: Per-group configuration storage
- Migration Support: Structured schema updates
- Async Operations: Non-blocking database interactions
- Model Size: ~8-10MB (INT8 quantized TensorFlow Lite)
- Inference Time: ~100-300ms per image
- Memory Usage: Minimal RAM footprint with efficient cleanup
- Database: Connection pooling with keepalive for stability
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Model not found: Ensure
model_int8.tfliteis in themodel/directory - Database connection: Verify PostgreSQL credentials and connectivity
- Webhook issues: Check firewall settings and SSL certificate (Telegram enforces HTTPS)
- Permission errors: Ensure bot has admin rights with restrict/delete permissions
- Memory errors: Reduce worker count in
main.pyif needed
Enable detailed logging by setting environment variables:
export DEBUG=true
python run.pyYou need to manage migrations manually - create migration file under bot/migrations/ (if models are modified) then/else just run:
python bot/migrations/<file_name>.py- β Complete restructuring into modular package architecture
- β Advanced group management with per-group settings
- β Enhanced permission system with automatic validation
- β Improved user interface with inline keyboards
- β Database migrations
- β Enhanced error handling and logging
- β Production-ready webhook support
- β Developer announcement system
If upgrading from the older single-file version, you need to migrate database.
- GantMan/nsfw_model - For the base NSFW detection model
- aiogram - Modern Telegram Bot API framework
- TensorFlow Lite team - For the efficient inference engine
