Skip to content

timileyindev/mandela-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 MandelaBot

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.

🌟 Features

Core Functionality

  • πŸ” 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

Built-in Mandela Effects

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!

Safety Features

  • 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

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        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       β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Using Docker Compose (Recommended)

  1. Clone the repository

    git clone <repository-url>
    cd mandela
  2. Configure environment

    cp .env.example .env
    # Edit .env with your Twitter API credentials
  3. Start all services

    docker-compose up -d

    This will start:

    • MandelaBot application (port 8000)
    • MongoDB (port 27017)
  4. Initialize the database

    docker-compose exec mandelabot python scripts/init_mongodb.py

The bot will be available at http://localhost:8000

Manual Installation

Prerequisites

  • Python 3.11+
  • MongoDB
  • Twitter Developer Account with API v2 access

Setup Steps

  1. 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
  2. Start database

    # Start MongoDB
    mongod --dbpath /path/to/your/db
  3. Configure environment

    cp .env.example .env
    # Edit .env with your credentials and database URLs
  4. Initialize database

    python scripts/init_mongodb.py
  5. Run the application

    python main.py

πŸ”§ Configuration

Twitter API Setup

  1. Apply for a Twitter Developer Account at https://developer.twitter.com/
  2. Create a new App and generate API keys
  3. Ensure you have the following permissions:
    • Read tweets
    • Write tweets
    • Read users

Environment Variables

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 consider

πŸ“‹ API Endpoints

Health & Monitoring

  • GET /health/ - Basic health check
  • GET /health/status - Detailed system status
  • GET /health/readiness - Kubernetes readiness probe
  • GET /health/liveness - Kubernetes liveness probe

Authentication

  • POST /auth/login - User login with email/password
  • GET /auth/verify - Verify JWT token
  • POST /auth/refresh - Refresh JWT token
  • GET /auth/me - Get current user information

Dashboard & Monitoring

  • GET /dashboard/ - Public statistics dashboard (HTML)
  • GET /dashboard/admin - Admin dashboard with controls (requires auth)
  • GET /dashboard/api/stats - JSON statistics API

Testing & Development

  • POST /mentions/test - Test mention processing
  • POST /mentions/test-detection - Test Mandela Effect detection
  • POST /mentions/trigger-poll - Manually trigger mention poll
  • GET /mentions/statistics - Get processing statistics

Administration (πŸ”’ JWT Required)

  • GET /admin/mandela-effects - List all Mandela Effects
  • POST /admin/mandela-effects - Add new Mandela Effect
  • GET /admin/statistics - Comprehensive statistics
  • POST /admin/control/start - Start the bot
  • POST /admin/control/stop - Stop the bot
  • GET /admin/rate-limits/{user_id} - Check user rate limits
  • POST /admin/reload-mandela-effects - Reload Mandela Effects

πŸ” Authentication & Dashboard

MandelaBot includes a comprehensive JWT-based authentication system and beautiful HTML dashboards:

Features

  • 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

Quick Start

  1. Login: Default admin credentials are admin@mandelabot.com / admin123
  2. Public Dashboard: Visit http://localhost:8000/dashboard/
  3. Admin Dashboard: Visit http://localhost:8000/dashboard/admin (requires login)

Security Configuration

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.

πŸ§ͺ Testing

Test Mandela Effect Detection

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"}'

Simulate Mention Processing

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"
  }'

🐳 Docker Deployment

Production Docker Compose

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:

πŸ“ Project Structure

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

πŸš€ Performance Features

  • 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

πŸ”’ Security

  • 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

πŸ“Š Monitoring

  • 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

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

  • Create an issue for bug reports or feature requests
  • Check the documentation in the /docs endpoint when running
  • Review logs for troubleshooting (docker-compose logs mandelabot)

πŸ™ Acknowledgments

  • 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.

About

[Bot] A twitter bot written that searches Twitter, News Sources, RSS and curates top headlines for posting regularly on Twitter.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors