Production-ready reference implementation for detecting and mitigating malicious operators in Telegram (spam, raids, scams, multi-accounting).
Status: β
PRODUCTION READY β Complete antifraud system with risk scoring, strikes, memory, and admin controls
License: MIT β See LICENSE, COPYRIGHT.md, and COPYING
Last Updated: March 3, 2026
This is a complete, containerized anti-fraud solution with advanced risk assessment and automated moderation:
- Risk Assessment: Multi-factor risk scoring (SAFE/SUSPICIOUS/DANGEROUS/BANNED levels)
- Strike System: Progressive discipline (1-3 strikes to ban)
- User Memory: Persistent behavior tracking with JSON storage
- Behavior Fingerprinting: Multi-account detection via pattern analysis
- Message Analysis: Content-based risk evaluation
- Raid Detection: Coordinated attack pattern recognition
- Admin Bot: Comprehensive command interface for user management
- Automated Actions: Risk-based automatic moderation
- Memory Persistence: User history and behavior tracking
- Test Mode: Validation without Telegram connection
- Comprehensive Testing: Full test suite for all components
- β Docker Compose containerization (Redis + bots)
- β JSON-based user database with metadata
- β Automated test suite (comprehensive validation)
- β Admin command interface
- β Risk assessment engine
- β Strike and ban management
- β Memory and fingerprinting systems
telegram_antifraud/
βββ bots/
β βββ public_bot.py # Main bot with antifraud integration
β βββ private_bot.py # Admin bot with management commands
β βββ userbot.py # Userbot for investigation
βββ engine/
β βββ risk_assessment.py # Risk level evaluation engine
β βββ scoring.py # Message and behavior scoring
β βββ clusters.py # Multi-account detection
β βββ honeypot.py # Spam pattern matching
β βββ raid.py # Raid detection and containment
β βββ signals.py # Signal definitions
β βββ logger.py # Event logging
βββ services/
β βββ memory.py # User data persistence
β βββ strike_manager.py # Strike progression system
β βββ ban_manager.py # Ban management and fingerprinting
βββ data/
β βββ store.json # User database
βββ examples/
β βββ logging.py # Logging examples
β βββ metrics.py # Metrics collection
βββ tests.py # Comprehensive test suite
βββ docker-compose.yml # Multi-service setup
βββ requirements.txt # Python dependencies
βββ config.py # Configuration settings
βββ README.md # This file
- Ve a @BotFather en Telegram
- Crea dos bots:
/newbotβ Bot pΓΊblico (para monitoreo de grupos)/newbotβ Bot privado (para comandos admin)
- Copia los tokens que te da BotFather
# Instalar dependencias
pip install -r requirements.txt
# Ejecutar setup interactivo
python run.pyEl script de setup te guiarΓ‘ para:
- β Verificar dependencias
- β
Crear archivo
.envcon tus tokens - β Verificar Redis
- β Ejecutar tests
- β Iniciar los bots
Crea un archivo .env en la raΓz del proyecto:
PUBLIC_BOT_TOKEN=tu_token_del_bot_publico
PRIVATE_BOT_TOKEN=tu_token_del_bot_privado
REDIS_URL=redis://localhost:6379/0
ADMIN_IDS=123456789,987654321
API_KEY=your-secure-api-key-here
API_ID=tu_api_id
API_HASH=tu_api_hash# Instalar Redis (Windows con Chocolatey)
choco install redis-64
# O usar Docker
docker run -d -p 6379:6379 redis:7-alpine
# Iniciar Redis
redis-server# OpciΓ³n A: Usar el script interactivo
python run.py
# Selecciona opciΓ³n 3 para ejecutar ambos bots
# OpciΓ³n B: Manualmente en terminales separadas
# Terminal 1: Bot pΓΊblico (monitoreo)
python bots/public_bot.py
# Terminal 2: Bot privado (admin)
python bots/private_bot.py# Construir e iniciar todos los servicios
docker-compose up --build
# O en background
docker-compose up -d --build
# Ver logs
docker-compose logs -f
# Detener
docker-compose downLos servicios incluyen:
- Redis: Cache y cola de mensajes
- PostgreSQL: Base de datos persistente
- API: FastAPI server en puerto 8000
- Public Bot: Bot de monitoreo
- Private Bot: Bot de administraciΓ³n
- Bot PΓΊblico: Envia
/starten chat privado con el bot pΓΊblico - Bot Admin: Envia
/starten chat privado con el bot privado - En Grupo: Agrega el bot pΓΊblico a un grupo como administrador
/start- InformaciΓ³n del bot/help- Ayuda/status- Estado del sistema
/start- Lista de comandos/stats- EstadΓsticas del sistema/user <id>- InformaciΓ³n de usuario/ban <id> [razΓ³n]- Banear usuario/unban <id>- Desbanear usuario/strike <id> [razΓ³n]- Agregar strike/forgive <id>- Quitar strike/risk <id>- Evaluar riesgo/containment <chat_id> <modo>- Modo contenciΓ³n/whitelist <id>- Agregar a whitelist/blacklist <id>- Agregar a blacklist/test- Ejecutar tests
# Ejecutar tests
python tests.py
# Modo test (sin Telegram)
python bots/public_bot.py --test-mode
python bots/private_bot.py --test-modepython bots/private_bot.py --test-mode
python tests.py
---
## π― Core Features
### Risk Assessment Engine
- **Multi-level Risk**: SAFE, SUSPICIOUS, DANGEROUS, BANNED
- **Factor-based Scoring**: Combines message content, user history, and behavior patterns
- **Real-time Evaluation**: Assess risk on every message and user action
### Strike System
- **Progressive Discipline**: 1st strike (warning), 2nd strike (restriction), 3rd strike (ban)
- **Reason Tracking**: Detailed strike history with timestamps
- **Flexible Management**: Add/remove strikes via admin commands
### User Memory System
- **Persistent Storage**: JSON-based user database
- **Behavior Tracking**: Message history, strikes, bans, timestamps
- **Metadata Management**: First seen, last seen, tags, whitelist/blacklist
### Admin Command Interface
Comprehensive bot management via private chat:
/start - Show available commands /stats - System statistics /user - User information and risk assessment /ban [reason] - Ban user /unban - Unban user /strike [reason] - Add strike to user /forgive - Remove strike from user /risk - Assess user risk /containment <chat_id> - Set containment mode /whitelist - Add to whitelist /blacklist - Add to blacklist /test - Run system tests
### Automated Moderation
- **Risk-based Actions**: Automatic moderation based on risk levels
- **Strike Progression**: Automatic strikes for suspicious behavior
- **Ban Automation**: Automatic bans after 3 strikes
- **Containment Modes**: Slow mode, bunker mode for raid protection
---
## π§ͺ Testing
Run the comprehensive test suite:
```bash
python tests.py
Tests cover:
- β Memory service functionality
- β Strike manager operations
- β Ban manager and fingerprinting
- β Risk assessment engine
- β Scoring algorithms
- β Full system integration
The project includes GitHub Actions CI that runs on every push and PR:
- Linting: flake8 for code quality
- Formatting: black for consistent code style
- Imports: isort for organized imports
- Testing: Full test suite with Redis and PostgreSQL services
- Services: Redis and PostgreSQL containers for integration tests
CI ensures code quality and prevents regressions.
# Telegram Bot Tokens
PUBLIC_BOT_TOKEN = "your_public_bot_token_here"
PRIVATE_BOT_TOKEN = "your_private_bot_token_here"
# Redis Configuration
REDIS_URL = "redis://localhost:6379/0"
# Risk Assessment Thresholds
SAFE_THRESHOLD = 0.3
SUSPICIOUS_THRESHOLD = 0.6
DANGEROUS_THRESHOLD = 0.8
# Strike Configuration
MAX_STRIKES_BEFORE_BAN = 3
# Memory Configuration
STORE_FILE = "data/store.json"{
"users": {
"12345": {
"message_count": 10,
"strikes": 1,
"banned": false,
"first_seen": "2024-01-01T10:00:00Z",
"last_seen": "2024-01-02T15:30:00Z",
"tags": ["suspicious"],
"strike_history": [
{"reason": "spam", "timestamp": "2024-01-02T14:00:00Z"}
]
}
},
"metadata": {
"last_updated": "2024-01-02T15:30:00Z",
"version": "1.0"
}
}version: '3.8'
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
public-bot:
build: .
command: python bots/public_bot.py
environment:
- REDIS_URL=redis://redis:6379/0
depends_on:
- redis
private-bot:
build: .
command: python bots/private_bot.py
environment:
- REDIS_URL=redis://redis:6379/0
depends_on:
- redis- Set up Redis cluster for high availability
- Configure monitoring with Prometheus/Grafana
- Set up backups for user database
- Configure logging aggregation
- Set up health checks and alerting
- Total users tracked
- Active bans and strikes
- Risk distribution
- Message processing rate
- System uptime and performance
Access via private bot commands to monitor:
- User statistics
- Risk assessments
- Strike distributions
- System health
- User data stored locally in JSON format
- No external data sharing
- Configurable data retention
- GDPR-compliant data handling
- Private admin bot for management commands
- Token-based authentication
- Command-level permissions
- Comprehensive logging of all actions
- Strike and ban history
- Admin command usage tracking
- Risk Factors: Extend
engine/risk_assessment.py - Admin Commands: Add to
bots/private_bot.py - Memory Fields: Update
services/memory.py - Tests: Add to
tests.py
- Comprehensive test coverage
- Type hints and documentation
- Modular architecture
- Error handling and logging
MIT License - see LICENSE for details.
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Built with β€οΈ for safer Telegram communities βββ engine/ β βββ scoring.py # User risk scoring with decay β βββ clusters.py # Multi-account network detection (BFS) β βββ honeypot.py # Spam template matching (Levenshtein) β βββ raid.py # Join spike detection + containment modes β βββ signals.py # Signal definitions (link, honeypot, velocity, etc.) β βββ rules.py # Decision engine (AND/OR, priorities) β βββ worker.py # Main processing pipeline β βββ shadow_mod.py # Silent moderation (throttle, mute, suppress) β βββ logger.py # Structured JSON event logging βββ db/ β βββ models.py # SQLAlchemy ORM (6 models, migrations ready) βββ api/ β βββ dashboard.py # FastAPI REST API (13 endpoints) βββ tools/ β βββ traffic_simulator.py # Synthetic attack generation (6 modes) β βββ userbot_opsec.py # Session rotation, proxy management β βββ metrics.py # Prometheus integration (docs) βββ docs/ β βββ MODERATION_POLICY.md # Behavior classification & moderator roles β βββ TOS_CHECKLIST.md # GDPR, CCPA, Telegram compliance matrix β βββ PRIVACY_POLICY.md # User data practices & rights β βββ SECURITY_POLICY.md # Incident response, vulnerability disclosure β βββ OPERATIONS_MANUAL.md # Deployment, monitoring, troubleshooting β βββ SCALABILITY.md # Redis Cluster, Kafka, multi-worker setups βββ tests/ β βββ test_advanced.py # 14 comprehensive pytest tests βββ docker-compose.yml # Full stack: Redis + 3 bots + dashboard βββ Dockerfile # Python 3.11 container image βββ config.py # Centralized configuration βββ requirements.txt # Pinned dependencies (FastAPI, SQLAlchemy, Pyrogram) βββ .env.example # Template for credentials βββ rules.json # 5 example rules (priorities, conditions) βββ demo.py # 5-demo showcase of all subsystems βββ README.md # This file
---
## π Quick Start
### Prerequisites
- **Python 3.9+** or **Docker**
- **Redis 6.0+** (bundled in docker-compose)
- **PostgreSQL 13+** (optional, for persistence)
- **Telegram bot tokens** (create via [@BotFather](https://t.me/BotFather))
### Installation
1. **Clone & setup environment:**
```bash
git clone https://github.com/your-org/telegram_antifraud
cd telegram_antifraud
cp .env.example .env
# Edit .env with your Telegram tokens and Redis URL
nano .env
- Option A: Docker Compose (Recommended)
The project now includes a webhook endpoint and a worker pipeline:
- API:
bots/webhook.py(FastAPI, accepts Telegram updates at/webhook) - Worker:
engine/worker.py(consumesdata_bus, processes rules, pushes actions toaction_bus) - Helper script:
scripts/setup_webhook.shto set Telegram webhook
To use:
- Set
WEBHOOK_URLandWEBHOOK_SECRET_TOKENin.env. - Start compose:
docker compose up -d
- Configure webhook:
./scripts/setup_webhook.sh
- Validate service:
curl http://localhost:8000/healthz
-
Option A: Docker Compose (Recommended)
docker-compose up -d # Services: public_bot, worker, private_bot, redis all running docker-compose logs -f worker # Monitor processing
-
Option B: Local Python
pip install -r requirements.txt # Terminal 1: python bots/public_bot.py # Terminal 2: python engine/worker.py # Terminal 3: python bots/private_bot.py
For highβtraffic groups the recommended platform is Kubernetes. A simple cluster offers
high availability, autoβscaling and the ability to handle tens of thousands of messages
per minute. The k8s/ directory contains example manifests that match this repository's
architecture.
- Build & publish a container image to a registry, e.g.
ghcr.io/<you>/telegram_antifraud:latest. - Create secrets for the database and Telegram token:
kubectl create secret generic telegram-secret --from-literal=token="$TELEGRAM_TOKEN" kubectl create secret generic antifraud-db-secret --from-literal=password="supersecret"
- Apply infrastructure manifests (adjust storage classes and resource sizes):
kubectl apply -f k8s/redis-statefulset.yaml kubectl apply -f k8s/postgres-deployment.yaml kubectl apply -f k8s/webhook-deployment.yaml kubectl apply -f k8s/worker-deployment.yaml kubectl apply -f k8s/ingress.yaml kubectl apply -f k8s/hpa.yaml
- Configure TLS & DNS: ensure
cert-manageris installed andyourdomain.example.compoints to the ingress controller. Webhook endpoint should behttps://yourdomain.example.com/webhook. - Autoscaling: the HPA uses CPU and a custom Prometheus metric (
redis_queue_length) to
tools/backup.pyβ scheduleable Postgres/Redis backup helper (see docs/OPERATIONS_MANUAL.md).tools/sdk.pyβ simple Python client for the REST API.tools/load_test.pyβ generate traffic against the webhook endpoint for benchmarking.
These are useful when automating maintenance, integrating with other systems, or validating performance under load.
grow/shrink the worker set automatically.
With this setup the system can scale horizontally by simply increasing the Replica count or allowing the HPA to adjust based on load. Redis and Postgres are the only stateful services and can be backed by managed offerings for production.
Hecho por hasbulla
### Verify Installation
```bash
# Add bot to Telegram chat
# Send test message in chat (bot should process it)
# Check dashboard
open http://localhost:8000/docs # Swagger UI with all endpoints
# Run test suite
pytest tests/test_advanced.py -v # Should see 14/14 passing
# Simulate spam attack
python tools/traffic_simulator.py --attack spam --chat <YOUR_CHAT_ID>
# Telegram tokens (from .env)
TELEGRAM_TOKEN_PUBLIC = "1234567:ABC..."
TELEGRAM_TOKEN_PRIVATE = "7654321:XYZ..."
# Redis
REDIS_URL = "redis://localhost:6379/0"
# Scoring thresholds
VELOCITY_THRESHOLD = 40 # msg/hour to flag
RAID_THRESHOLD = 15 # joins in 5 min to trigger raid mode
SCORE_BAN_THRESHOLD = 120 # kick user if score > 120
# Database (optional)
DATABASE_URL = "postgresql://user:pass@localhost/antifraud"[
{
"name": "high_score_kick",
"priority": 1,
"conditions": {
"type": "AND",
"items": [{"type": "score_gt", "value": 100}]
},
"actions": ["kick"],
"enabled": true
},
{
"name": "honeypot_immediate_kick",
"priority": 2,
"conditions": {
"type": "AND",
"items": [
{"type": "has_signal", "value": "honeypot"},
{"type": "velocity_gt", "value": 20}
]
},
"actions": ["kick"],
"enabled": true
}
]| Signal | Description | Implementation |
|---|---|---|
| Velocity | High message rate | defaultdict + time windows |
| Repetition | Duplicate messages | MD5 hash matching |
| Honeypot | Known spam templates | Levenshtein distance (< 0.3) |
| Raid | Coordinated joins | Join spike detection + clustering |
| Links | Suspicious URLs | Keyword/tld blacklist |
| Cluster | Multi-account networks | BFS graph traversal |
Actions: ["kick", "mute", "restrict", "raid_alert", "raid_bunker", "containment_off"]
# Examples
kick(chat_id, user_id, reason="spam detected")
restrict(chat_id, user_id, can_send_messages=False) # Soft ban13 REST endpoints for moderators:
GET /api/usersβ List users (filtered by score/status)GET /api/users/{uid}β User details + signal historyPOST /api/users/{uid}/actionβ Manual moderator actionGET/POST/PUT/DELETE /api/rulesβ Rule CRUDGET /api/alertsβ Recent actionsGET /api/auditβ Audit trailGET /api/statsβ System dashboard
Auto-generated docs: http://localhost:8000/docs (Swagger UI)
6 SQLAlchemy ORM models:
- User: telegram_id, score, status, last_seen
- Signal: signal_type, value, chat_id, raw_text, timestamp
- ModAction: audit records of all kicks/mutes/restricts
- Rule: versioned rule storage with created_by audit
- AuditLog: comprehensive action log (who did what, when)
- Session factory: async-ready for production
Migration-ready: Use Alembic for schema updates
- β GDPR: Data minimization, encryption, right to deletion
- β CCPA: Opt-out, data disclosure, non-discrimination
- β Telegram ToS: Rate limit compliance, API usage policy
- β Privacy: Structured logging, user consent mechanisms
- β Security: Vulnerability disclosure, incident response
Policy documents included:
MODERATION_POLICY.mdβ Behavior classification, moderator roles, escalationTOS_CHECKLIST.mdβ GDPR/CCPA/Telegram compliance matrixPRIVACY_POLICY.mdβ Data collection, retention, user rightsSECURITY_POLICY.mdβ Incident response, vulnerability reportingOPERATIONS_MANUAL.mdβ Deployment, monitoring, troubleshooting
Public Bot Redis Queue Worker Database
(Telegram API) (data_bus) (Rules Engine) (PostgreSQL)
β β β β
ββ User sends message βββ Data Bus Process signal ββββ Audit Log
β - user_id, text - store ~100 events - calc score - Store signals
β - timestamp - 1sec TTL - check rules - Store actions
β - chat_id - trigger action
β β
ββ User joins chat βββββ Data Bus β
β - user_id, join_time - store joins β
β - detect raid β
β β
β Action Bus (action_bus)ββββ
β - kick: user 123
β - mute: user 456
β - raid_bunker: chat_id
β β
ββ Private Bot (Action Handler)
- Execute kick/mute/restrict
- Log result to audit_bus
- Send moderator notification
pytest tests/test_advanced.py -v
# Expected output:
# test_scoring.py::test_velocity_tracking β
# test_scoring.py::test_repetition_detection β
# test_honeypot.py::test_levenshtein_similarity β
# test_rules.py::test_rule_engine_and_or β
# test_raid.py::test_raid_detection β
# ... (14 total)
# ======== 14 passed in 2.34s ========python demo.py
# Showcases:
# 1. Velocity detection (high-rate messages)
# 2. Repetition detection (duplicate messages)
# 3. Honeypot similarity (spam template matching)
# 4. Raid detection (coordinated joins)
# 5. Rule engine evaluation (complex conditions)
### Simulate Traffic
```bash
python tools/traffic_simulator.py --attack spam --chat <YOUR_CHAT_ID>
python tools/traffic_simulator.py --attack raid --chat <YOUR_CHAT_ID>
python tools/traffic_simulator.py --attack all --chat <YOUR_CHAT_ID># Start all services
docker-compose up -d
# Verify
docker-compose ps
# redis:6379 β | public_bot β | worker β | private_bot β
# Monitor
docker-compose logs -f worker# Deploy multi-replica worker pool
kubectl apply -f k8s/antifraud-deployment.yaml
# Multi-worker + Redis Sentinel HA
# See docs/SCALABILITY.md for Kafka setup# Telegram
TELEGRAM_TOKEN_PUBLIC=your_public_bot_token
TELEGRAM_TOKEN_PRIVATE=your_private_bot_token
# Redis (production: use SSL)
REDIS_URL=rediss://password@redis-cluster:6379
# PostgreSQL (production: use SSL)
DATABASE_URL=postgresql://user:pwd@db-host/antifraud?sslmode=require
# Configuration
RAID_THRESHOLD=15 # joins triggering raid
VELOCITY_THRESHOLD=40 # msg/hour to flag
RULES_FILE=rules.json- Data minimization: Only collect user_id, score, signals (not full messages)
- Retention: Auto-delete user data after 90 days inactivity
- User rights:
/data_disclosure,/delete_my_data,/opt_outcommands - Processing basis: Legitimate interest (spam/fraud prevention)
- Consumer rights: Know, Delete, Opt-Out, Non-Discrimination
- Data broker clause: No third-party data sales
- Disclosure: Privacy policy available at
/privacy
- Rate limits respected (100 msg/min per chat)
- API usage limited to moderation (kick, mute, restrict)
- Private bot has minimal permissions
- No intercepting private messages
- Secrets stored in
.env(excluded from git) - TLS 1.3 for API communication
- Immutable audit logs (append-only, tamper-proof)
- Structured JSON logging for forensics
- Incident response playbook included
See docs/ for full policies:
SECURITY_POLICY.mdβ Vulnerability disclosure, incident responsePRIVACY_POLICY.mdβ User data practices & rightsMODERATION_POLICY.mdβ Behavior classification & appealsTOS_CHECKLIST.mdβ Compliance matrix (GDPR, CCPA, Telegram)
| Document | Purpose |
|---|---|
MODERATION_POLICY.md |
5-tier behavior classification, moderator roles, escalation procedures |
TOS_CHECKLIST.md |
GDPR/CCPA/Telegram compliance mapping + implementation status |
PRIVACY_POLICY.md |
Data collection, retention, user rights, FAQs |
SECURITY_POLICY.md |
Incident response, vulnerability reporting, audit schedule |
OPERATIONS_MANUAL.md |
Deployment, monitoring, troubleshooting, incident playbooks |
SCALABILITY.md |
Redis Cluster, Kafka setup, multi-worker deployment, monitoring |
- Sub-millisecond latency for message processing
- Persistence via RDB/AOF for recovery
- Horizontal scaling with Redis Cluster (millions of events/day)
- Developer-friendly Pub/Sub + List operations
- ACID compliance for data integrity
- Queryable JSON for flexible logging
- Indexes on audit_log for fast forensics
- Replication for high availability
- Schema safety with migrations (Alembic)
- Type safety with Pydantic integration
- Relationship management (User β Signal β Action)
- Production-ready connection pooling
- Auto-generated docs (Swagger/ReDoc)
- Type validation via Pydantic
- Async support for 1000s of concurrent moderators
- CORS-ready for web frontend integration
| Traffic Volume | Architecture | Details |
|---|---|---|
| < 1M msg/day | Redis single instance | This deployment |
| 1M β 10M msg/day | Redis Cluster (3+ nodes) | Horizontal sharding |
| > 10M msg/day | Redis + Kafka + multi-worker | Event sourcing, replay |
See docs/SCALABILITY.md for:
- Docker Compose Redis Cluster setup (3-node)
- Kafka topic configuration (partition strategy)
- Multi-worker deployment (replicas=4+)
- Monitoring with Prometheus/Grafana
- PostgreSQL read replicas for queries
# Check public_bot logs
docker-compose logs public_bot | tail -20
# Verify Telegram token
curl https://api.telegram.org/bot${TOKEN}/getMe | jq .ok
# Restart bot
docker-compose restart public_bot# Check queue backlog
redis-cli LLEN data_bus # Should be small (< 1000)
# Check worker logs
docker-compose logs worker | grep ERROR
# Verify database connection
docker-compose logs worker | grep "connection"
# Restart worker
docker-compose restart workerredis-cli INFO memory
# If > 1 GB, check:
# - Are signals being purged? (90-day retention)
# - Is worker stuck processing old events?
# - Set EXPIRE on queues: redis-cli EXPIRE data_bus 86400For complete troubleshooting: See docs/OPERATIONS_MANUAL.md
pip install -r requirements.txt
pip install pytest pytest-asyncio pytest-mock # testing
pip install black ruff mypy # lintingpytest tests/ -v # All tests
pytest tests/test_advanced.py::test_rule_engine_and_or -v # Single test
pytest --cov=engine tests/ # Coverage reportblack engine/ bots/ api/ tools/ # Format
ruff check engine/ bots/ api/ # Lint
mypy engine/ --strict # Type check# Run with local Redis (no Docker)
docker run -d -p 6379:6379 redis:7-alpine
# Set environment
export TELEGRAM_TOKEN_PUBLIC=...
export REDIS_URL=redis://localhost:6379
# Run components
python bots/public_bot.py # Terminal 1
python engine/worker.py # Terminal 2
python bots/private_bot.py # Terminal 3worker_messages_processed # Total messages analyzed
worker_actions_taken # Total moderation actions
worker_error_count # Processing failures
worker_latency_ms # Time per message (p50, p99)
active_users_risk_score_gt_50 # High-risk user count
raids_detected_today # Raid events
false_positive_rate # % of kicks that were wrong
# Enable metrics in worker.py
# Scrape endpoint: /metrics
docker-compose -f docker-compose.monitoring.yml up -d
# Prometheus: http://localhost:9090
# Grafana: http://localhost:3000- Dashboard β Review alerts in real-time
- User detail β Inspect score, signal history, appeals
- Manual action β Kick/mute/restrict if needed
- Appeal review β Check user's
/appealrequest - Audit trail β Verify all actions logged
- Rules update β Edit
rules.json, test with simulator - Signal addition β Extend
engine/signals.py - Scoring tweak β Adjust weights in
engine/scoring.py - Deploy β Merge β CI/CD β production docker-compose restart
- Policy review β Quarterly check of
MODERATION_POLICY.md - Incident audit β Review
audit_logtable for anomalies - Compliance scan β Verify GDPR/CCPA checklist
- Penetration test β Annual security audit
P1 Emergency (data loss, all bots down):
- Page on-call engineer immediately
- Check
docker-compose psfor failed services - Review logs:
docker-compose logs --since 10m - Restore from backup:
psql $DB < backup.sql - Restart:
docker-compose restart
P2 High (moderators can't kick, > 5% errors):
- Check worker logs for exceptions
- Verify database connection
- Restart worker:
docker-compose restart worker - If persists, escalate to DBA
See docs/OPERATIONS_MANUAL.md for full incident playbook
This code is provided as-is for reference. When deploying in production:
- β
Review
docs/SECURITY_POLICY.mdfor vulnerability reporting - β
Publish
docs/PRIVACY_POLICY.mdto users - β
Follow
docs/MODERATION_POLICY.mdfor appeals - β
Validate
docs/TOS_CHECKLIST.mdcompliance with your legal team - β
Archive
docs/OPERATIONS_MANUAL.mdfor future operators
Contributions welcome! Please:
- Fork repository
- Create feature branch (
feature/your-idea) - Add tests (must pass:
pytest) - Submit pull request with description
- Address security/compliance review
Documentation: See /docs folder for detailed guides
Issues: Report via GitHub Issues
Security: Email security@example.com (see SECURITY_POLICY.md)
Questions: Create Discussion in GitHub
- β Phase 1-5: Core detection (velocity, repetition, honeypot, raid, clustering)
- β Phase 6-9: Advanced features (rules, shadow_mod, OPSEC, logging)
- β Phase 10-12: Persistence (database, dashboard, API)
- β Phase 13-16: Production infrastructure (simulator, scaling, docs)
- β³ Phase 17: Grafana dashboards (monitoring)
- β³ Phase 18: A/B testing framework (rule variants)
- β³ Phase 19: Web UI for moderators (React/Next.js frontend)
This project is licensed under the MIT License β see the LICENSE file for details.
- Email: hasbullita007@gmail.com
- GitHub Issues: Report bugs or request features
- GitHub Discussions: Ask questions or share ideas
- Support Guide: See SUPPORT.md
- Contributing Guide: See CONTRIBUTING.md
For security vulnerabilities, please refer to SECURITY.md.
Hecho por hasbulla con β€οΈ para una moderaciΓ³n segura y transparente
Γltima actualizaciΓ³n: 3 de marzo de 2026