Skip to content

joelstanner/twitchbot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

170 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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:

TwitchBot

A comprehensive FastAPI-based Twitch chat bot with real-time EventSub integration, featuring:

🚀 Core Features

  • 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

🎯 EventSub Real-time Events

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

🎮 Interactive Channel Point Rewards

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.

🎤 SayIntentions.ai Integration

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

📍 Position & Flight Data

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: !location provides current position with Google Maps links
  • SayIntentions Integration: Position requests trigger radio communication

🧪 Development & Testing

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

🚀 Quick start

1. Environment Setup

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/

2. Install Dependencies

# Install with development tools (~21 seconds)
pip install -e '.[dev]'

3. Configuration

# Copy example environment file
cp .env.example .env

# For local development (recommended)
# Edit .env and set:
USE_MOCKS=1

4. Run the Bot

# Start the bot (includes OAuth flow if needed)
python -m twitchbot.bot

# Alternative: FastAPI development server
fastapi dev twitchbot/bot.py

On first run, the bot opens a browser for interactive OAuth unless valid refresh tokens exist.

🔧 Development Workflow

Code Quality (MANDATORY)

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)
pytest

Zero tolerance policy: All linting and type errors must be fixed before committing.

Testing Modes

# 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

Coverage Reports

# Standard coverage
pytest --cov=twitchbot --cov-report=term-missing

# Detailed HTML coverage report
pytest --cov=twitchbot --cov-report=html

⚙️ Configuration

Core Environment Variables

Required 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/

OAuth Scopes

The bot automatically requests these Twitch API scopes:

  • chat:read & chat:edit - Chat interaction capabilities
  • user:write:chat & channel:bot - API message sending with bot badge
  • channel:read:redemptions & channel:manage:redemptions - Channel point handling
  • channel:read:subscriptions - Subscription EventSub events
  • moderator:read:followers - Follower EventSub events
  • bits:read - Cheer/bits EventSub events
  • channel:read:hype_train - Hype train events
  • channel:read:polls & channel:read:predictions - Interactive content
  • moderation:read - Moderation events

Boolean Environment Parsing

Environment variables support multiple formats:

  • True values: true, True, 1, yes, on
  • False values: false, False, 0, no, off

Environment File Management

  • .env - Main configuration file (copy from .env.example)
  • .env.mock - Pre-configured for Twitch CLI mock development
  • user_token.json - Auto-generated OAuth token storage
  • TWITCHBOT_ENV_PATH - Override default .env location

🏗️ Architecture & Components

Core Modules

  • twitchbot/bot.py - Main FastAPI application with lifespan management
  • twitchbot/chatbot.py - Chat command handling and message processing
  • twitchbot/auth.py - OAuth2 authentication endpoints
  • twitchbot/eventsub.py - Real-time EventSub WebSocket integration
  • twitchbot/position.py - Position tracking (SimConnect/mock)
  • twitchbot/say.py - SayIntentions.ai integration and channel management
  • twitchbot/browser_source.py - OBS WebSocket integration
  • twitchbot/settings.py - Pydantic configuration management
  • twitchbot/token_manager.py - OAuth token persistence utilities
  • twitchbot/mock_cli.py - Twitch CLI mock server integration

Authentication Architecture

Dual Authentication System:

  1. App Authentication - Bot badge for API message sending
  2. 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

EventSub Integration

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

Mock System

Three-Tier Mock Architecture:

  1. Simple Mocks (USE_MOCKS=1) - Basic functionality simulation
  2. Twitch CLI Mocks (USE_TWITCH_CLI_MOCKS=1) - Realistic API simulation
  3. Production Mode (USE_MOCKS=0) - Full Twitch integration

�️ Platform Compatibility

Windows

  • Full functionality with SimConnect for real flight simulator data
  • EventSub integration for real-time Twitch events
  • SayIntentions.ai for authentic aviation radio communication

macOS/Linux

  • Mock position data simulating KSEA airport vicinity
  • Full chat and EventSub functionality
  • All features except SimConnect work perfectly

Cross-Platform Development

  • Use USE_MOCKS=1 for consistent development experience
  • Automatic graceful degradation when platform features unavailable
  • Comprehensive test suite runs on all platforms

🐛 Troubleshooting

Common Issues

Port conflicts:

# Kill existing processes
pkill -f twitch
# Or check what's using the port
lsof -i :8080

OAuth failures:

  • Check client ID/secret in .env
  • Verify redirect URI matches Twitch app settings
  • Delete user_token.json to force re-authentication

SimConnect errors on non-Windows:

  • Ensure USE_MOCKS=1 is 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

Performance Notes

  • 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

📚 Additional Documentation

🤝 Contributing

  1. Fork and clone the repository
  2. Create virtual environment and install with pip install -e '.[dev]'
  3. Make changes following the type safety requirements
  4. Run validation sequence: black . && isort . && mypy . && ruff check . && pytest
  5. Submit pull request with passing tests and clean code

Code Standards

  • 100% type annotations required (mypy compliance)
  • Zero linting errors (ruff and black formatting)
  • Comprehensive tests for new features
  • Documentation updates for user-facing changes

📄 License

See pyproject.toml for license information. Contributions welcome with tests and validation compliance.


Status: ✅ Production Ready | Python: 3.13+ | Coverage: 80%+ | Platform: Cross-platform

About

No description, website, or topics provided.

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors