An intelligent Twitter bot that detects Mandela Effect phrases and responds with factual corrections. Built with FastAPI and MongoDB, it continuously monitors mentions, uses fuzzy string matching to identify misremembered quotes, and replies with accurate information.
- π Intelligent Detection: Uses fuzzy string matching to detect Mandela Effect phrases in tweets
- π± Twitter Integration: Monitors mentions and replies automatically using Twitter API v2
- β‘ Real-time Processing: Event-driven architecture with scheduled polling
- π‘οΈ Rate Limiting: Smart rate limiting to prevent spam and respect API limits
- π Admin Dashboard: REST API for monitoring and management
- πΎ MongoDB Storage: Persistent data storage with Beanie ODM for async operations
The bot comes pre-loaded with popular Mandela Effects including:
- "Luke, I am your father" β "No, I am your father"
- "Mirror, mirror on the wall" β "Magic mirror on the wall"
- "Life is like a box of chocolates" β "Life was like a box of chocolates"
- "Berenstein Bears" β "Berenstain Bears"
- "We are the champions of the world" β "We are the champions"
- And many more!
- Spam Detection: Filters out spam and low-quality mentions
- User Rate Limiting: Prevents overwhelming individual users
- Global Rate Limiting: Controls overall bot activity
- Duplicate Prevention: Avoids replying to the same tweet multiple times
ββββββββββββββββββββββββββββββββ
β Twitter / X API β
β (Mentions, Tweet, Reply) β
ββββββββββββββ¬ββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββ
β Scheduler / Poller β
β (APScheduler + MongoDB) β
ββββββββββββββ¬ββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββ
β FastAPI Backend β
β - Validate Mention β
β - Apply Rate Limits β
β - Call Phrase Matcher β
β - Format & Post Reply β
ββββββββββββββ¬ββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ ββββββββββββββββββββββββββ
β Mandela Effect Matcher β<βββββ MongoDB Database β
β - Fuzzy Match (RapidFuzz)β β (Beanie ODM) β
ββββββββββββββ¬βββββββββββββ ββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββ
β MongoDB Collections: β
β - mandela_effects β
β - bot_responses β
β - rate_limit_entries β
β - tweet_mentions β
β - scheduler_jobs β
ββββββββββββββββββββββββββ
-
Clone the repository
git clone <repository-url> cd mandela
-
Configure environment
cp .env.example .env # Edit .env with your Twitter API credentials -
Start all services
docker-compose up -d
This will start:
- MandelaBot application (port 8000)
- MongoDB (port 27017)
-
Initialize the database
docker-compose exec mandelabot python scripts/init_mongodb.py
The bot will be available at http://localhost:8000
- Python 3.11+
- MongoDB
- Twitter Developer Account with API v2 access
-
Clone and setup Python environment
git clone <repository-url> cd mandela python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt
-
Start database
# Start MongoDB mongod --dbpath /path/to/your/db -
Configure environment
cp .env.example .env # Edit .env with your credentials and database URLs -
Initialize database
python scripts/init_mongodb.py
-
Run the application
python main.py
- Apply for a Twitter Developer Account at https://developer.twitter.com/
- Create a new App and generate API keys
- Ensure you have the following permissions:
- Read tweets
- Write tweets
- Read users
Key configuration options in .env:
# Database Configuration
MONGODB_URL=mongodb://localhost:27017
MONGODB_DATABASE=mandelabot
# Twitter API (Required)
TWITTER_BEARER_TOKEN=your_token_here
TWITTER_API_KEY=your_key_here
TWITTER_API_SECRET=your_secret_here
TWITTER_ACCESS_TOKEN=your_token_here
TWITTER_ACCESS_TOKEN_SECRET=your_secret_here
# Bot Behavior
BOT_USERNAME=YourBotUsername
MENTION_POLL_INTERVAL=60 # seconds between polls
GLOBAL_RATE_LIMIT_PER_HOUR=100 # global limit
USER_RATE_LIMIT_PER_HOUR=5 # per-user limit
# Matching Sensitivity
FUZZY_MATCH_THRESHOLD=80 # percentage (80-95 recommended)
MIN_PHRASE_LENGTH=10 # minimum characters to considerGET /health/- Basic health checkGET /health/status- Detailed system statusGET /health/readiness- Kubernetes readiness probeGET /health/liveness- Kubernetes liveness probe
POST /auth/login- User login with email/passwordGET /auth/verify- Verify JWT tokenPOST /auth/refresh- Refresh JWT tokenGET /auth/me- Get current user information
GET /dashboard/- Public statistics dashboard (HTML)GET /dashboard/admin- Admin dashboard with controls (requires auth)GET /dashboard/api/stats- JSON statistics API
POST /mentions/test- Test mention processingPOST /mentions/test-detection- Test Mandela Effect detectionPOST /mentions/trigger-poll- Manually trigger mention pollGET /mentions/statistics- Get processing statistics
GET /admin/mandela-effects- List all Mandela EffectsPOST /admin/mandela-effects- Add new Mandela EffectGET /admin/statistics- Comprehensive statisticsPOST /admin/control/start- Start the botPOST /admin/control/stop- Stop the botGET /admin/rate-limits/{user_id}- Check user rate limitsPOST /admin/reload-mandela-effects- Reload Mandela Effects
MandelaBot includes a comprehensive JWT-based authentication system and beautiful HTML dashboards:
- JWT Authentication: Secure token-based authentication for admin routes
- Public Dashboard: Real-time statistics without authentication at
/dashboard/ - Admin Dashboard: Advanced controls and monitoring at
/dashboard/admin - Auto-refresh: Live updates every 30 seconds
- Responsive Design: Works perfectly on desktop and mobile
- Beautiful UI: Modern design with Tailwind CSS and Chart.js
- Login: Default admin credentials are
admin@mandelabot.com/admin123 - Public Dashboard: Visit
http://localhost:8000/dashboard/ - Admin Dashboard: Visit
http://localhost:8000/dashboard/admin(requires login)
Update your .env file for production:
# JWT Authentication
JWT_SECRET_KEY=your-super-secret-jwt-key-change-in-production
ADMIN_EMAIL=your-admin@email.com
ADMIN_PASSWORD=your-secure-passwordπ Detailed Documentation: See docs/AUTHENTICATION_AND_DASHBOARD.md for complete implementation details, security considerations, and deployment guidance.
curl -X POST "http://localhost:8000/mentions/test-detection" \
-H "Content-Type: application/json" \
-d '{"text": "I love the quote Luke, I am your father from Star Wars"}'curl -X POST "http://localhost:8000/mentions/test" \
-H "Content-Type: application/json" \
-d '{
"text": "Remember when Darth Vader said Luke, I am your father?",
"username": "test_user"
}'version: "3.8"
services:
mongodb:
image: mongo:7
environment:
MONGO_INITDB_ROOT_USERNAME: mandelabot
MONGO_INITDB_ROOT_PASSWORD: your_secure_password
volumes:
- mongodb_data:/data/db
restart: unless-stopped
mandelabot:
build: .
environment:
- MONGODB_URL=mongodb://mandelabot:your_secure_password@mongodb:27017/mandelabot?authSource=admin
depends_on:
- mongodb
restart: unless-stopped
volumes:
mongodb_data:mandela/
βββ main.py # FastAPI application entry point
βββ config/
β βββ settings.py # Application configuration
βββ models/
β βββ mandela_effect.py # Beanie ODM models
βββ services/
β βββ database.py # MongoDB service
β βββ mandela_engine.py # Mandela Effect detection engine
β βββ twitter_service.py # Twitter API integration
β βββ rate_limiter.py # Rate limiting service
β βββ bot_processor.py # Mention processing logic
β βββ scheduler.py # APScheduler service
βββ routes/
β βββ health.py # Health check endpoints
β βββ admin.py # Admin endpoints
β βββ mentions.py # Mention handling endpoints
βββ scripts/
β βββ init_mongodb.py # Database initialization script
βββ requirements.txt # Python dependencies
βββ Dockerfile # Docker container configuration
βββ docker-compose.yml # Multi-container setup
βββ README.md # This file
- Async/Await: Built with FastAPI and async Python for high performance
- MongoDB Indexing: Optimized database queries with proper indexing
- Background Tasks: Non-blocking mention processing with APScheduler
- Connection Pooling: Efficient database connection management
- Rate Limiting: Multiple layers of rate limiting (global, per-user, per-endpoint)
- Input Validation: Pydantic models for robust input validation
- Error Handling: Comprehensive error handling and logging
- Docker Security: Non-root user in Docker containers
- API Security: Optional authentication for admin endpoints
- Health Checks: Multiple health check endpoints for monitoring
- Structured Logging: JSON-structured logs with correlation IDs
- Statistics API: Real-time statistics and metrics
- Database Monitoring: Connection status and performance metrics
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Create an issue for bug reports or feature requests
- Check the documentation in the
/docsendpoint when running - Review logs for troubleshooting (
docker-compose logs mandelabot)
- Twitter API for platform integration
- FastAPI for the awesome web framework
- MongoDB for flexible data storage
- APScheduler for reliable task scheduling
- RapidFuzz for efficient string matching
Disclaimer: This bot is for educational and entertainment purposes. Always verify facts from authoritative sources. The Mandela Effect is a fascinating psychological phenomenon, and this bot aims to provide accurate information in a helpful way.