A big part of this project was an excerize in using new (at the time) AI coding assistants and learning about their capibilities and limitations. I also needed a bot for my Twitch channel. I present to you:
A comprehensive FastAPI-based Twitch chat bot with real-time EventSub integration, featuring:
- Headless OAuth2 Authentication - Automatic token management with refresh handling
- Interactive Chat Commands - Built-in commands:
!ping,!reply <text>,!location - Real-time EventSub Integration - Live notifications for follows, subs, raids, cheers, and channel points
- Position Tracking - SimConnect integration for real flight data (Windows) with KSEA mock fallback
- SayIntentions.ai Integration - Aviation radio communication with multiple channels
- Channel Point Redemptions - Automated responses for custom rewards
- OBS WebSocket Integration - Custom browser source support with real-time updates
- Comprehensive Mock System - Full Twitch CLI mock support for offline development
- Type-Safe Configuration - Pydantic Settings with environment variable management
- Production-Ready Architecture - Dual authentication, error handling, and structured logging
The bot automatically listens for and responds to:
- New Followers - Welcome messages and analytics tracking
- Subscriptions - Tier-based subscription notifications
- Channel Point Redemptions - Automated custom reward responses
- Cheers/Bits - Real-time cheer acknowledgments
- Raids - Incoming raid notifications with viewer counts
- Stream Events - Online/offline status changes
Pre-configured responses for popular redemptions:
- "Bring me a Pillow" - Flight crew pillow service announcement
- "Hot Towel" - Luxurious hot towel service with refreshing message
- "Blanket" - Cozy blanket comfort service
- "Plane Tour" - Randomized aircraft tour experiences (5+ variations)
- "Do A Barrel Roll" - Aerobatic maneuver announcements with safety themes
- "Trigger a Random Cabin Crisis" - Emergency scenario simulation
All redemptions integrate with SayIntentions.ai for realistic aviation announcements.
Full aviation radio communication support:
- Multiple Channels: INTERCOM1/2, COM1/2, ACARS_IN with directional variants
- Message Rephrasing: AI-powered message variation for natural communication
- Position Reporting: Automated location announcements with aviation formatting
- Channel Point Integration: Contextual radio calls for passenger services
- Mock Mode Support: Offline development with simulated responses
Advanced position tracking with dual-mode support:
- Windows SimConnect: Real flight simulator position data
- Mock Mode: Realistic KSEA airport vicinity simulation with movement
- Aviation Formatting: Degrees/minutes coordinate display
- Location Command:
!locationprovides current position with Google Maps links - SayIntentions Integration: Position requests trigger radio communication
Twitch CLI Mock Integration:
- Complete offline development environment
- Mock EventSub events and API calls
- Realistic test data with consistent user IDs
- Command-line tools for testing automation
Quality Assurance:
- 100% type safety with mypy compliance
- Comprehensive test suite with 80%+ coverage
- Automated linting with black, isort, and ruff
- Pre-commit validation workflow
ALWAYS use a virtual environment - Required for proper dependency isolation:
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # macOS/Linux
# venv\Scripts\activate # Windows
# Verify virtual environment
which python # Should show path with /venv/# Install with development tools (~21 seconds)
pip install -e '.[dev]'# Copy example environment file
cp .env.example .env
# For local development (recommended)
# Edit .env and set:
USE_MOCKS=1# Start the bot (includes OAuth flow if needed)
python -m twitchbot.bot
# Alternative: FastAPI development server
fastapi dev twitchbot/bot.pyOn first run, the bot opens a browser for interactive OAuth unless valid refresh tokens exist.
All code changes must pass these validation steps:
# 1. Format code (~0.5s)
black .
# 2. Sort imports (~0.2s)
isort .
# 3. Type checking (~10s)
mypy .
# 4. Fast linting (~0.01s)
ruff check .
# 5. Run tests (~2.5s)
pytestZero tolerance policy: All linting and type errors must be fixed before committing.
# Mock mode (recommended for development)
USE_MOCKS=1 python -m twitchbot.bot
# Twitch CLI mock mode (for EventSub testing)
USE_TWITCH_CLI_MOCKS=1 python -m twitchbot.bot
# Production mode (real Twitch API)
USE_MOCKS=0 python -m twitchbot.bot# Standard coverage
pytest --cov=twitchbot --cov-report=term-missing
# Detailed HTML coverage report
pytest --cov=twitchbot --cov-report=htmlRequired for production operation:
# Twitch API Credentials (required)
TWITCH_CLIENT_ID=your_client_id_here
TWITCH_CLIENT_SECRET=your_secret_here
TWITCH_BOT_USERNAME=your_bot_username
TWITCH_BOT_ID=your_bot_user_id
BROADCASTER_USERNAME=your_channel_name
BROADCASTER_ID=your_broadcaster_id
TWITCH_REDIRECT_URI=http://localhost:8000/auth/callback
# Authentication Tokens (auto-managed)
TWITCH_ACCESS_TOKEN=auto_generated_on_oauth
TWITCH_REFRESH_TOKEN=auto_generated_on_oauth
# SayIntentions.ai Integration (optional)
SAY_API_KEY=your_sayintentions_api_key
SAY_REPHRASE=1 # Enable AI message rephrasing
# Development & Runtime
USE_MOCKS=1 # Enable mock mode for development
STATE=dev
LOG_LEVEL=INFO
COLOR=1 # Enable colored console output
# OBS Integration (optional)
OBS_WEBSOCKET_URL=ws://localhost:4455
OBS_WEBSOCKET_PASSWORD=your_obs_password
# Twitch CLI Mock Testing (optional)
USE_TWITCH_CLI_MOCKS=1
TWITCH_MOCK_USER_ID=726145
TWITCH_MOCK_BASE_URL=http://localhost:8080/mock/The bot automatically requests these Twitch API scopes:
chat:read&chat:edit- Chat interaction capabilitiesuser:write:chat&channel:bot- API message sending with bot badgechannel:read:redemptions&channel:manage:redemptions- Channel point handlingchannel:read:subscriptions- Subscription EventSub eventsmoderator:read:followers- Follower EventSub eventsbits:read- Cheer/bits EventSub eventschannel:read:hype_train- Hype train eventschannel:read:polls&channel:read:predictions- Interactive contentmoderation:read- Moderation events
Environment variables support multiple formats:
- True values:
true,True,1,yes,on - False values:
false,False,0,no,off
.env- Main configuration file (copy from.env.example).env.mock- Pre-configured for Twitch CLI mock developmentuser_token.json- Auto-generated OAuth token storageTWITCHBOT_ENV_PATH- Override default.envlocation
twitchbot/bot.py- Main FastAPI application with lifespan managementtwitchbot/chatbot.py- Chat command handling and message processingtwitchbot/auth.py- OAuth2 authentication endpointstwitchbot/eventsub.py- Real-time EventSub WebSocket integrationtwitchbot/position.py- Position tracking (SimConnect/mock)twitchbot/say.py- SayIntentions.ai integration and channel managementtwitchbot/browser_source.py- OBS WebSocket integrationtwitchbot/settings.py- Pydantic configuration managementtwitchbot/token_manager.py- OAuth token persistence utilitiestwitchbot/mock_cli.py- Twitch CLI mock server integration
Dual Authentication System:
- App Authentication - Bot badge for API message sending
- User Authentication - Chat connection and EventSub access
Token Management:
- Automatic OAuth flow with browser redirect
- Persistent token storage with refresh handling
- Graceful fallback for authentication failures
Real-time Event Processing:
- WebSocket connection to Twitch EventSub
- Custom event handler registration system
- Automatic reconnection with exponential backoff
- Mock support via Twitch CLI for testing
Three-Tier Mock Architecture:
- Simple Mocks (
USE_MOCKS=1) - Basic functionality simulation - Twitch CLI Mocks (
USE_TWITCH_CLI_MOCKS=1) - Realistic API simulation - Production Mode (
USE_MOCKS=0) - Full Twitch integration
- Full functionality with SimConnect for real flight simulator data
- EventSub integration for real-time Twitch events
- SayIntentions.ai for authentic aviation radio communication
- Mock position data simulating KSEA airport vicinity
- Full chat and EventSub functionality
- All features except SimConnect work perfectly
- Use
USE_MOCKS=1for consistent development experience - Automatic graceful degradation when platform features unavailable
- Comprehensive test suite runs on all platforms
Port conflicts:
# Kill existing processes
pkill -f twitch
# Or check what's using the port
lsof -i :8080OAuth failures:
- Check client ID/secret in
.env - Verify redirect URI matches Twitch app settings
- Delete
user_token.jsonto force re-authentication
SimConnect errors on non-Windows:
- Ensure
USE_MOCKS=1is set in environment - Verify virtual environment is activated
Module import errors:
# Ensure virtual environment is active
which python # Should show venv path
# Reinstall if needed
pip install -e '.[dev]'Type checking failures:
# Install development dependencies
pip install -e '.[dev]'
# Update type stubs
mypy --install-types- Installation: ~21 seconds (
pip install -e '.[dev]') - Bot startup: ~1-2 seconds
- Test suite: ~2.5 seconds
- Type checking: ~10 seconds
- Linting: <1 second combined
- EventSub Integration Guide - Comprehensive EventSub documentation
- Mock Integration Guide - Twitch CLI mock development setup
- Copilot Instructions - Complete development guidelines
- Fork and clone the repository
- Create virtual environment and install with
pip install -e '.[dev]' - Make changes following the type safety requirements
- Run validation sequence:
black . && isort . && mypy . && ruff check . && pytest - Submit pull request with passing tests and clean code
- 100% type annotations required (mypy compliance)
- Zero linting errors (ruff and black formatting)
- Comprehensive tests for new features
- Documentation updates for user-facing changes
See pyproject.toml for license information. Contributions welcome with tests and validation compliance.
Status: ✅ Production Ready | Python: 3.13+ | Coverage: 80%+ | Platform: Cross-platform