- Implemented a Python script for integrating Plex Media Server with Sonarr to manage TV show seasons based on viewing habits. - Added features for automated season management, exclusion list support, and detailed logging. - Created a requirements.txt file to include necessary packages: plexapi, requests, pytest, pytest-mock, and requests-mock. - Developed unit tests for the API verification function using pytest and requests_mock. - Included a standalone script to unmonitor excluded shows in Sonarr. - Added a test script for manual API verification with mock and real API tests.
5.5 KiB
Plex Sonarr Integration Script
This Python script integrates Plex Media Server with Sonarr to automatically manage TV show seasons based on viewing habits. It can unmonitor seasons in Sonarr and optionally delete them from Plex when certain conditions are met.
Features
- Automated Season Management: Automatically marks previous seasons as unmonitored in Sonarr when the latest season's last 3 episodes are watched
- Exclude List Support: Maintains a list of TV shows that should be excluded from automated processing
- TVDB Integration: Uses TVDB IDs to match shows between Plex and Sonarr
- Safe Operation: Includes verification of Sonarr API connectivity before processing
- Detailed Logging: Provides comprehensive output for monitoring and debugging
Prerequisites
Required Python Packages
pip install plexapi requests
Required Services
- Plex Media Server: Running and accessible
- Sonarr v3: Running and accessible with API access enabled
Configuration
Before running the script, you need to update the following configuration variables at the top of the script:
PLEX_TOKEN = "your_plex_token_here"
PLEX_SERVER_URL = "http://your_plex_server:32400"
SONARR_API_KEY = "your_sonarr_api_key_here"
SONARR_SERVER_URL = "http://your_sonarr_server:8989"
Getting Your Plex Token
- Sign in to your Plex account
- Visit: https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/
- Follow the instructions to find your X-Plex-Token
Getting Your Sonarr API Key
- Open Sonarr web interface
- Go to Settings → General
- Copy the API Key from the Security section
How It Works
Main Processing Logic
- API Verification: Verifies Sonarr API connectivity and authentication
- Show Iteration: Loops through all TV shows in the Plex "TV Shows" library
- Exclusion Check: Skips shows that are in the
exclude_showslist - Season Analysis: For each show:
- Gets all seasons sorted by index
- Checks if there are multiple seasons
- Examines the latest season's episodes
- Condition Check: If the last 3 episodes of the latest season are watched:
- Retrieves the show's TVDB ID from Plex metadata
- Finds the corresponding series in Sonarr
- Marks all previous seasons as unmonitored in Sonarr
- Optionally deletes previous seasons from Plex (currently commented out)
Excluded Shows
The script maintains a list of shows that will be skipped during processing:
- Stargate SG-1
- Space Sheriff Gavan
- Spider-Man and His Amazing Friends
- Super Sentai
- Superman & Lois
- UFO Robot Grendizer
- Zorro
- Saved by the Bell: The College Years
- Saber Rider and the Star Sheriffs
- Prison Break
- Power Rangers
- The Outer Limits (1995)
- MacGyver
- Knight Rider
- Chuck
- Breaking Bad
- Amazing Stories (1985)
- Airwolf
- The Adventures of Superboy (1988)
Usage
Basic Usage
python plexsonarr.py
Manual Exclude List Processing
To manually unmonitor all shows in the exclude list, uncomment this line in the script:
unmonitor_all_excluded_shows()
Enable Season Deletion
To actually delete seasons from Plex (currently disabled for safety), uncomment this line:
season.delete()
Functions
Core Functions
verify_sonarr_api(): Verifies Sonarr API connectivityget_tvdb_id(show): Extracts TVDB ID from Plex show metadataget_series_id_from_tvdb(tvdb_id): Gets Sonarr series ID from TVDB IDmark_season_unmonitored(series_id, season_number): Marks a season as unmonitored in Sonarrlast_3_episodes_watched(season): Checks if the last 3 episodes of a season are watchedunmonitor_all_excluded_shows(): Processes all shows in the exclude list
Safety Features
- Dry Run Mode: Season deletion is commented out by default
- API Verification: Checks Sonarr API before processing
- Exclude List: Protects specific shows from processing
- Latest Season Protection: Never processes the latest season for deletion
- Detailed Logging: Comprehensive output for monitoring operations
Error Handling
The script includes error handling for:
- Sonarr API connectivity issues
- Missing TVDB IDs in Plex metadata
- Series not found in Sonarr
- HTTP request failures
Logging Output
The script provides detailed console output including:
- Show titles being processed
- TVDB IDs found
- Sonarr series IDs
- Seasons being marked as unmonitored
- Watched episodes in the latest season
- API verification status
Important Notes
⚠️ Warning: This script can permanently delete media files from your Plex server. Always test thoroughly in a safe environment before running on production data.
- The season deletion functionality is disabled by default (commented out)
- Make sure your Plex and Sonarr instances are properly backed up
- Test with a small subset of shows before running on your entire library
- Monitor the output carefully during initial runs
Troubleshooting
Common Issues
- API Connection Failures: Check that your server URLs and API keys are correct
- Missing TVDB IDs: Some shows may not have TVDB metadata in Plex
- Series Not Found: Shows may exist in Plex but not in Sonarr
- Permission Errors: Ensure the script has appropriate network access
Debug Mode
For additional debugging, uncomment the print statements in the mark_season_unmonitored function to see detailed HTTP response information.
License
This script is provided as-is for educational and personal use. Use at your own risk.