### Install PlexAPI Source: https://github.com/hellowlol/plexapi/blob/master/README.md Install the PlexAPI library using pip. ```bash pip install plexapi ``` -------------------------------- ### Get Specific Resource and Connect Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve a specific Plex resource by name and establish a connection to it, returning a PlexServer instance. ```python server_resource = account.resource('My Home Server') plex = server_resource.connect() # Returns PlexServer instance ``` -------------------------------- ### Handle PlexAPI Client Not Found Errors Source: https://context7.com/hellowlol/plexapi/llms.txt Demonstrates catching a NotFound exception when attempting to get a client that is not connected or does not exist. ```python from plexapi.server import PlexServer from plexapi.myplex import MyPlexAccount from plexapi.exceptions import BadRequest, NotFound, Unauthorized, Unsupported # Invalid client operations try: plex = PlexServer('http://localhost:32400', 'your-token') client = plex.client('Unknown Client') except NotFound as e: print(f"Client not found: {e}") ``` -------------------------------- ### Get Specific Device Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve a specific Plex device by its name. ```python device = account.device('My iPhone') ``` -------------------------------- ### Navigate TV Shows, Seasons, and Episodes Source: https://context7.com/hellowlol/plexapi/llms.txt Connects to Plex and retrieves information about TV shows, including properties like title, year, season count, and episode counts. It also demonstrates how to iterate through seasons, get specific seasons, and list all episodes. Requires a valid Plex server connection and token. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') shows = plex.library.section('TV Shows') # Get a specific show show = shows.get('Friends') # Show properties print(f"Title: {show.title}") print(f"Year: {show.year}") print(f"Seasons: {show.childCount}") print(f"Episodes: {show.leafCount}") print(f"Watched Episodes: {show.viewedLeafCount}") print(f"Is Fully Watched: {show.isWatched}") # Get all seasons for season in show.seasons(): print(f"Season {season.seasonNumber}: {season.leafCount} episodes") print(f" Watched: {season.viewedLeafCount}/{season.leafCount}") # Get a specific season season1 = show.season(1) # or show.season('Season 1') # Get all episodes all_episodes = show.episodes() print(f"Total episodes: {len(all_episodes)}") # Get watched/unwatched episodes watched = show.watched() unwatched = show.unwatched() print(f"Watched: {len(watched)}, Unwatched: {len(unwatched)}") # Find specific episode by title or number episode = show.episode('The One Where Everybody Finds Out') episode = show.episode(season=5, episode=14) print(f"{episode.grandparentTitle} S{episode.seasonNumber}E{episode.index}") print(f"Title: {episode.title}") print(f"Air Date: {episode.originallyAvailableAt}") ``` -------------------------------- ### Get Movie Object Properties Source: https://context7.com/hellowlol/plexapi/llms.txt Connects to a Plex server and retrieves basic and advanced properties of a specific movie. Ensure you replace 'your-token' with your actual Plex token. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') movies = plex.library.section('Movies') # Get a specific movie movie = movies.get('Jurassic Park') # Basic properties print(f"Title: {movie.title}") print(f"Original Title: {movie.originalTitle}") print(f"Year: {movie.year}") print(f"Duration: {movie.duration // 60000} minutes") print(f"Content Rating: {movie.contentRating}") print(f"Studio: {movie.studio}") print(f"Tagline: {movie.tagline}") print(f"Summary: {movie.summary}") # Ratings print(f"Rating: {movie.rating}") print(f"Audience Rating: {movie.audienceRating}") print(f"User Rating: {movie.userRating}") # Watch status print(f"View Count: {movie.viewCount}") print(f"Is Watched: {movie.isWatched}") print(f"Last Viewed: {movie.lastViewedAt}") # Cast and crew (requires full object) movie.reload() # Fetch full details if needed for director in movie.directors: print(f"Director: {director.tag}") for actor in movie.actors[:5]: print(f"Actor: {actor.tag} as {actor.role}") for genre in movie.genres: print(f"Genre: {genre.tag}") # Mark as watched/unwatched movie.markWatched() movie.markUnwatched() # Refresh metadata movie.refresh() # Analyze media movie.analyze() ``` -------------------------------- ### Get Account Information Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve and print various details about the authenticated Plex account, including username, email, ID, and home server information. ```python print(f"Username: {account.username}") print(f"Email: {account.email}") print(f"ID: {account.id}") print(f"UUID: {account.uuid}") print(f"Locale: {account.locale}") print(f"Home: {account.home}") print(f"Home Size: {account.homeSize} / {account.maxHomeSize}") ``` -------------------------------- ### Access Sync Items on a Device Source: https://context7.com/hellowlol/plexapi/llms.txt Get a device that supports sync and access its sync items. Note: Requires a Plex Pass subscription. This snippet outlines properties of a SyncItem. ```python from plexapi.myplex import MyPlexAccount account = MyPlexAccount.signin('username@email.com', 'password') # Get a device that supports sync device = account.device('My iPhone') # Access sync items on the device (if supported) # Note: Requires Plex Pass subscription # SyncItem properties # sync_item.id - Unique sync item ID # sync_item.title - Title of synced content # sync_item.rootTitle - Root title (e.g., show name) # sync_item.metadataType - Type of content # sync_item.machineIdentifier - Server identifier # sync_item.status - Sync status information # sync_item.MediaSettings - Quality/format settings # sync_item.policy - Sync policy (e.g., unwatched only) # sync_item.location - Storage location # Get media items for a sync item # media_items = sync_item.getMedia() # Mark sync item as downloaded # sync_item.markAsDone(sync_id) ``` -------------------------------- ### Safely Get and Mark Movie as Watched in PlexAPI Source: https://context7.com/hellowlol/plexapi/llms.txt Implement a safe pattern for retrieving a movie by its title and marking it as watched, handling both NotFound and general exceptions. ```python plex = PlexServer('http://localhost:32400', 'your-token') try: movie = plex.library.section('Movies').get('Avatar') movie.markWatched() print(f"Marked {movie.title} as watched") except NotFound: print("Movie not found in library") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Get Stream URL for Media Source: https://github.com/hellowlol/plexapi/blob/master/README.md Generate a direct stream URL for a movie or show, which can be used with external players like VLC. Specify desired video resolution. ```python # Example 8: Get a URL to stream a movie or show in another client jurassic_park = plex.library.section('Movies').get('Jurassic Park') print 'Run running the following command to play in VLC:' print 'vlc "%s"' % jurassic_park.getStreamUrl(videoResolution='800x600') ``` -------------------------------- ### List All Resources Source: https://context7.com/hellowlol/plexapi/llms.txt Iterate through all available Plex resources (servers, players) associated with the account and print their details, including name, product, platform, and connection URIs. ```python for resource in account.resources(): print(f"\nResource: {resource.name}") print(f" Product: {resource.product} v{resource.productVersion}") print(f" Platform: {resource.platform}") print(f" Owned: {resource.owned}") print(f" Presence: {resource.presence}") print(f" Provides: {resource.provides}") for conn in resource.connections: print(f" Connection: {conn.uri}") ``` -------------------------------- ### Connect to Plex Server using MyPlex Account Source: https://github.com/hellowlol/plexapi/blob/master/README.md Sign in to your MyPlex account to obtain a PlexServer instance. Replace and with your Plex credentials, and with your Plex server's name. ```python from plexapi.myplex import MyPlexAccount account = MyPlexAccount.signin('', '') plex = account.resource('').connect() # returns a PlexServer instance ``` -------------------------------- ### Navigate and Manage Media Objects Source: https://context7.com/hellowlol/plexapi/llms.txt Basic operations for navigating media hierarchies, retrieving file paths, and updating watch status. ```python season = latest.season() show = latest.show() # Get file paths for part in latest.iterParts(): print(f"File: {part.file}") # Mark watched/unwatched latest.markWatched() latest.markUnwatched() # Search episodes across the show section tv_shows = plex.library.section('TV Shows') recent_episodes = tv_shows.searchEpisodes(sort='addedAt:desc', maxresults=10) for ep in recent_episodes: print(f"{ep.grandparentTitle} - S{ep.seasonNumber}E{ep.index}: {ep.title}") ``` -------------------------------- ### Connect to Plex Server Source: https://context7.com/hellowlol/plexapi/llms.txt Establish a connection to a Plex Media Server using its URL and a token. This provides a PlexServer instance for further operations. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') ``` -------------------------------- ### Discover and Connect to Clients Source: https://context7.com/hellowlol/plexapi/llms.txt Identify connected Plex clients and monitor their playback state and timeline. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # List all connected clients for client in plex.clients(): print(f"Client: {client.title}") print(f" Platform: {client.platform} {client.platformVersion}") print(f" Product: {client.product} v{client.version}") print(f" Device: {client.device}") print(f" Capabilities: {client.protocolCapabilities}") # Get a specific client by name client = plex.client("Living Room TV") print(f"Connected to: {client.title}") # Check if client is playing media if client.isPlayingMedia(): print("Currently playing media") if client.isPlayingMedia(includePaused=True): print("Currently playing or paused") # Get timeline information timeline = client.timeline() for media_type in timeline: state = media_type.get('state') if state: print(f"Type: {media_type.tag}, State: {state}") ``` -------------------------------- ### Handle PlexAPI Connection Errors Source: https://context7.com/hellowlol/plexapi/llms.txt Demonstrates how to catch a NotFound exception when attempting to connect to an invalid Plex server URL. ```python from plexapi.server import PlexServer from plexapi.exceptions import BadRequest, NotFound, Unauthorized, Unsupported # Connection errors try: plex = PlexServer('http://invalid-server:32400', 'token') except NotFound as e: print(f"Server not found: {e}") ``` -------------------------------- ### List All Devices Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve and display information for all devices linked to the Plex account, including device name, ID, product, platform, and connections. ```python for device in account.devices(): print(f"\nDevice: {device.name}") print(f" ID: {device.id}") print(f" Product: {device.product} v{device.productVersion}") print(f" Platform: {device.platform}") print(f" Connections: {device.connections}") ``` -------------------------------- ### Handle PlexAPI Authentication Errors Source: https://context7.com/hellowlol/plexapi/llms.txt Shows how to catch an Unauthorized exception when attempting to sign in with incorrect Plex credentials. ```python from plexapi.server import PlexServer from plexapi.myplex import MyPlexAccount from plexapi.exceptions import BadRequest, NotFound, Unauthorized, Unsupported # Authentication errors try: account = MyPlexAccount.signin('user@email.com', 'wrong-password') except Unauthorized as e: print(f"Authentication failed: {e}") ``` -------------------------------- ### Manage Playlists with PlexAPI Source: https://context7.com/hellowlol/plexapi/llms.txt Create, modify, and delete playlists by interacting with library sections and items. ```python movies = plex.library.section('Movies') favorites = [ movies.get('The Matrix'), movies.get('Inception'), movies.get('Interstellar') ] new_playlist = plex.createPlaylist('Sci-Fi Marathon', favorites) print(f"Created playlist: {new_playlist.title}") # Add items to existing playlist new_movie = movies.get('Blade Runner') playlist.addItems(new_movie) # Add multiple items at once more_movies = [movies.get('Avatar'), movies.get('Alien')] playlist.addItems(more_movies) # Remove an item from playlist items = playlist.items() playlist.removeItem(items[0]) # Remove first item # Move items within playlist items = playlist.items() playlist.moveItem(items[2], after=items[0]) # Move 3rd item after 1st # Edit playlist metadata playlist.edit(title='Updated Title', summary='My favorite movies') # Delete playlist playlist.delete() ``` -------------------------------- ### Browse and Manage Music Library Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve artists, albums, and tracks, and perform searches within a music library section. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') music = plex.library.section('Music') # Get an artist artist = music.get('Aerosmith') print(f"Artist: {artist.title}") print(f"Location: {artist.location}") # Get artist's albums for album in artist.albums(): print(f" Album: {album.title} ({album.year})") print(f" Tracks: {len(album.tracks())}") # Get a specific album album = artist.album('Get a Grip') print(f"Album: {album.title}") print(f"Artist: {album.parentTitle}") print(f"Year: {album.year}") print(f"Studio: {album.studio}") # List all tracks on an album for track in album.tracks(): print(f" {track.index}. {track.title} ({track.duration // 1000}s)") # Get a specific track track = artist.track('Dream On') print(f"Track: {track.title}") print(f"Album: {track.parentTitle}") print(f"Artist: {track.grandparentTitle}") print(f"Duration: {track.duration // 1000} seconds") # Navigate from track to album and artist album = track.album() artist = track.artist() # Search music artists = music.searchArtists(genre='Rock') albums = music.searchAlbums(year=1993) tracks = music.searchTracks(title='Love') ``` -------------------------------- ### List Files for the Latest Episode of a Show Source: https://github.com/hellowlol/plexapi/blob/master/README.md Retrieve and print the file paths for all parts of the latest episode of a given TV show. This is useful for locating the actual media files on the server. ```python # Example 7: List files for the latest episode of Friends. thelastone = plex.library.get('Friends').episodes()[-1] for part in thelastone.iterParts(): print(part.file) ``` -------------------------------- ### List Available Genre Choices Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieves and prints a list of available genre choices from the movies library. Requires an initialized PlexServer object. ```python genres = movies.listChoices('genre') for genre in genres: print(f"{genre.title} ({genre.key})") ``` -------------------------------- ### Perform Library Section Operations Source: https://context7.com/hellowlol/plexapi/llms.txt Demonstrates common maintenance operations on a Plex library section, such as refreshing, analyzing, and emptying the trash. Also shows how to access section properties. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # Get a library section movies = plex.library.section('Movies') # Refresh the section (scan for new media) movies.refresh() # Analyze all media in section movies.analyze() # Empty trash for this section movies.emptyTrash() # Section properties print(f"Section: {movies.title}") print(f"Key: {movies.key}") print(f"Type: {movies.type}") print(f"UUID: {movies.uuid}") print(f"Agent: {movies.agent}") print(f"Scanner: {movies.scanner}") print(f"Language: {movies.language}") print(f"Refreshing: {movies.refreshing}") print(f"Created: {movies.createdAt}") print(f"Updated: {movies.updatedAt}") print(f"Locations: {movies.locations}") ``` -------------------------------- ### Handle PlexAPI Item Not Found Errors Source: https://context7.com/hellowlol/plexapi/llms.txt Illustrates catching a NotFound exception when trying to access a library item that does not exist. ```python from plexapi.server import PlexServer from plexapi.myplex import MyPlexAccount from plexapi.exceptions import BadRequest, NotFound, Unauthorized, Unsupported # Not found errors try: plex = PlexServer('http://localhost:32400', 'your-token') movie = plex.library.section('Movies').get('Non-Existent Movie') except NotFound as e: print(f"Item not found: {e}") ``` -------------------------------- ### Manage Playlists Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve and inspect playlists and their contents. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # List all playlists for playlist in plex.playlists(): print(f"{playlist.title} ({playlist.playlistType})") print(f" Items: {playlist.leafCount}") print(f" Duration: {playlist.duration // 60000} minutes") print(f" Smart: {playlist.smart}") # Get a specific playlist playlist = plex.playlist('My Favorites') print(f"Playlist: {playlist.title}") # List items in a playlist for item in playlist.items(): print(f" - {item.title}") ``` -------------------------------- ### Generate Streaming URLs for External Players Source: https://context7.com/hellowlol/plexapi/llms.txt Create playback URLs for movies, TV episodes, and music, including options for resolution, bitrate, and resume offsets. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # Get a movie movie = plex.library.section('Movies').get('Jurassic Park') # Get basic stream URL stream_url = movie.getStreamURL() print(f"Stream URL: {stream_url}") print(f"\nPlay with VLC:\nvlc \"{stream_url}\"") # Get stream URL with custom resolution stream_url = movie.getStreamURL(videoResolution='1280x720') print(f"\n720p Stream: {stream_url}") # Get stream URL with bitrate limit stream_url = movie.getStreamURL( videoResolution='1920x1080', maxVideoBitrate=8000 # 8 Mbps ) # Stream with offset (resume from position) stream_url = movie.getStreamURL(offset=movie.viewOffset) print(f"\nResume playback: {stream_url}") # Get stream URL for an episode episode = plex.library.section('TV Shows').get('Friends').episode(season=1, episode=1) stream_url = episode.getStreamURL(videoResolution='1280x720') # Get stream URL for a music track track = plex.library.section('Music').get('Aerosmith').track('Dream On') audio_url = track.getStreamURL() print(f"\nAudio stream: {audio_url}") # Transcode image movie_thumb = plex.transcodeImage( movie.thumb, height=300, width=200 ) print(f"Thumbnail URL: {movie_thumb}") ``` -------------------------------- ### Control Media Playback Source: https://context7.com/hellowlol/plexapi/llms.txt Manage playback, navigation, volume, and UI interactions on a connected Plex client. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') client = plex.client("Living Room TV") # Play a movie on the client movie = plex.library.section('Movies').get('Avatar') client.playMedia(movie) # Play a specific episode episode = plex.library.section('TV Shows').get('Friends').episode(season=1, episode=1) client.playMedia(episode) # Basic playback controls (mtype: 'video', 'music', 'photo') client.play('video') client.pause('video') client.stop('video') # Navigation within playback client.seekTo(120000, mtype='video') # Seek to 2 minutes (in milliseconds) client.skipNext(mtype='video') client.skipPrevious(mtype='video') client.stepForward('video') client.stepBack('video') # Volume and playback settings client.setVolume(75, mtype='video') # 0-100 client.setShuffle(1, mtype='music') # 0=off, 1=on client.setRepeat(2, mtype='music') # 0=off, 1=repeat one, 2=repeat all # Audio and subtitle selection client.setAudioStream(audioStreamID=12345, mtype='video') client.setSubtitleStream(subtitleStreamID=67890, mtype='video') # UI Navigation client.goToHome() client.goBack() client.moveUp() client.moveDown() client.moveLeft() client.moveRight() client.select() client.toggleOSD() ``` -------------------------------- ### Manage Sessions and Watch History Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieve active playback sessions, view history, and access account subscription details. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # Get all active sessions sessions = plex.sessions() for session in sessions: print(f"Now Playing: {session.title}") print(f" User: {session.username}") print(f" Player: {session.player.title if session.player else 'Unknown'}") print(f" Progress: {session.viewOffset // 1000}s / {session.duration // 1000}s") if session.transcodeSession: ts = session.transcodeSession print(f" Transcoding: {ts.videoDecision} video, {ts.audioDecision} audio") # Get watch history history = plex.history() for item in history[:10]: print(f"Watched: {item.title}") print(f" Viewed At: {item.viewedAt}") print(f" User: {item.username}") # Access account information account = plex.account() print(f"Account: {account.username}") print(f"Subscription: {account.subscriptionState}") print(f"Features: {account.subscriptionFeatures}") ``` -------------------------------- ### Search for Content by Title Source: https://github.com/hellowlol/plexapi/blob/master/README.md Search the Plex library for content containing a specific keyword in its title. The output includes the content title and its type. ```python # Example 5: List all content with the word 'Game' in the title. for video in plex.search('Game'): print('%s (%s)' % (video.title, video.TYPE)) ``` -------------------------------- ### Manage Plex Library Sections Source: https://context7.com/hellowlol/plexapi/llms.txt Access and manage your Plex media library sections. Includes listing sections, retrieving specific sections, and performing library maintenance tasks like refreshing metadata, cleaning bundles, optimizing the database, and emptying the trash. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # List all library sections for section in plex.library.sections(): print(f"{section.title} ({section.type}) - {section.key}") print(f" Scanner: {section.scanner}") print(f" Agent: {section.agent}") print(f" Locations: {section.locations}") # Get a specific section by name movies = plex.library.section('Movies') shows = plex.library.section('TV Shows') music = plex.library.section('Music') # Refresh library metadata plex.library.refresh() # Clean bundles and optimize database plex.library.cleanBundles() plex.library.optimize() # Empty trash from all sections plex.library.emptyTrash() ``` -------------------------------- ### Connect to Plex Server using Auth Token Source: https://github.com/hellowlol/plexapi/blob/master/README.md Connect directly to a Plex server using its base URL and authentication token, avoiding MyPlex sign-in. Ensure the baseurl and token are correct for your server. ```python from plexapi.server import PlexServer baseurl = 'http://plexserver:32400' token = '2ffLuB84dqLswk9skLos' plex = PlexServer(baseurl, token) ``` -------------------------------- ### List Connected Plex Clients Source: https://github.com/hellowlol/plexapi/blob/master/README.md Retrieve and print the titles of all clients currently connected to the Plex server. This helps in managing playback devices. ```python # Example 3: List all clients connected to the Server. for client in plex.clients(): print(client.title) ``` -------------------------------- ### Handle Unsupported Operation in PlexAPI Source: https://context7.com/hellowlol/plexapi/llms.txt Use a try-except block to catch and handle Unsupported exceptions when attempting to send an unsupported command to a Plex client. ```python try: plex = PlexServer('http://localhost:32400', 'your-token') client = plex.clients()[0] # Attempting unsupported command client.sendCommand('unsupported/command') except Unsupported as e: print(f"Operation not supported: {e}") ``` -------------------------------- ### Perform Global and Library Searches Source: https://context7.com/hellowlol/plexapi/llms.txt Search for content across the entire server or within specific library sections using various filters. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # Global search across all libraries results = plex.search('Game') for item in results: print(f"{item.title} ({item.TYPE})") # Search with media type filter movies_only = plex.search('Star', mediatype='movie') shows_only = plex.search('Star', mediatype='show') # Library-level search library_results = plex.library.search(title='Batman') for item in library_results: print(f"{item.title} - {item.type}") # Search by type across library all_movies = plex.library.search(libtype='movie') all_episodes = plex.library.search(libtype='episode') # Get content from the entire library all_content = plex.library.all() print(f"Total items in library: {len(all_content)}") # Get recently added across all sections recent = plex.library.recentlyAdded() for item in recent[:10]: print(f"Recently added: {item.title}") # Get On Deck (continue watching) on_deck = plex.library.onDeck() for item in on_deck: print(f"Continue watching: {item.title}") ``` -------------------------------- ### List Shared Users Source: https://context7.com/hellowlol/plexapi/llms.txt Enumerate all users who have access to the Plex account's resources and display their details such as username, email, ID, and permissions. ```python for user in account.users(): print(f"\nUser: {user.username}") print(f" Email: {user.email}") print(f" ID: {user.id}") print(f" Home: {user.home}") print(f" Allow Sync: {user.allowSync}") print(f" Allow Channels: {user.allowChannels}") ``` -------------------------------- ### List All Playlists Source: https://github.com/hellowlol/plexapi/blob/master/README.md Retrieve and print the titles of all playlists available on the Plex server. This includes audio, video, and mixed-media playlists. ```python # Example 9: Get audio/video/all playlists for playlist in self.plex.playlists(): print(playlist.title) ``` -------------------------------- ### Play Media on a Specific Client Source: https://github.com/hellowlol/plexapi/blob/master/README.md Play a specific movie on a designated client. Note that the client must be on the same network as the Plex server for this to work. ```python # Example 4: Play the movie Avatar on another client. # Note: Client must be on same network as server. avatar = plex.library.section('Movies').get('Avatar') client = plex.client("Michael's iPhone") client.playMedia(avatar) ``` -------------------------------- ### List Unwatched Content in Library Source: https://github.com/hellowlol/plexapi/blob/master/README.md Iterate through all library sections and print titles of unwatched videos. This is useful for quickly identifying content that needs attention. ```python # Example 1: List all unwatched content in library. for section in plex.library.sections(): print('Unwatched content in %s:' % section.title) for video in section.unwatched(): print(' %s' % video.title) ``` -------------------------------- ### Search Music Library Source: https://context7.com/hellowlol/plexapi/llms.txt Query the Music library section to find albums, artists, or tracks based on criteria like year, country, or genre. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # Music section specific methods music = plex.library.section('Music') all_albums = music.albums() artists = music.searchArtists(country='United States') albums = music.searchAlbums(year=2023) tracks = music.searchTracks(genre='Rock') ``` -------------------------------- ### Connect to Plex Server via MyPlex Account Source: https://context7.com/hellowlol/plexapi/llms.txt Connect to Plex servers through your MyPlex account, which is useful for remote access or when using Plex Users. Lists available resources and connects to a specific server. ```python from plexapi.myplex import MyPlexAccount # Sign in to MyPlex account = MyPlexAccount.signin('username@email.com', 'password') # List all available resources (servers, players, etc.) for resource in account.resources(): print(f"{resource.name} - {resource.product} ({resource.platform})") # Connect to a specific server by name plex = account.resource('My Plex Server').connect() # Access account information print(f"Username: {account.username}") print(f"Email: {account.email}") print(f"Home Size: {account.homeSize}") ``` -------------------------------- ### Browse Plex Library Content Source: https://context7.com/hellowlol/plexapi/llms.txt Browse content within a Plex library section, including retrieving all items, recently added, 'On Deck' content, and specific items by title. Displays details such as title, year, duration, rating, and summary. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') movies = plex.library.section('Movies') # Get all movies in the library all_movies = movies.all() print(f"Total movies: {len(all_movies)}") # Get recently added content recent = movies.recentlyAdded(maxresults=10) for movie in recent: print(f"{movie.title} ({movie.year}) - Added: {movie.addedAt}") # Get "On Deck" content (partially watched) on_deck = movies.onDeck() for movie in on_deck: print(f"{movie.title} - {movie.viewOffset}ms watched") # Get a specific movie by title avatar = movies.get('Avatar') print(f"Title: {avatar.title}") print(f"Year: {avatar.year}") print(f"Duration: {avatar.duration}ms") print(f"Rating: {avatar.rating}") print(f"Summary: {avatar.summary[:100]}...") ``` -------------------------------- ### Authenticate with MyPlex Account Source: https://context7.com/hellowlol/plexapi/llms.txt Sign in to a MyPlex account to manage users and resources. ```python from plexapi.myplex import MyPlexAccount account = MyPlexAccount.signin('username@email.com', 'password') ``` -------------------------------- ### Mark All Episodes of a Show as Watched Source: https://github.com/hellowlol/plexapi/blob/master/README.md Mark all episodes of a specific TV show as watched. This is useful for cleaning up your watch history. ```python # Example 2: Mark all Conan episodes watched. plex.library.get('Conan (2010)').markWatched() ``` -------------------------------- ### Access Movie Media Files and Streams Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieves detailed information about a movie's media files, including resolution, bitrate, container, codecs, and file paths. Also accesses video, audio, and subtitle stream details. Requires an active Plex connection. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') movie = plex.library.section('Movies').get('Avatar') # Iterate through media files for media_item in movie.media: print(f"Resolution: {media_item.videoResolution}") print(f"Bitrate: {media_item.bitrate} kbps") print(f"Container: {media_item.container}") print(f"Video Codec: {media_item.videoCodec}") print(f"Audio Codec: {media_item.audioCodec}") print(f"Audio Channels: {media_item.audioChannels}") # Access file parts for part in media_item.parts: print(f" File: {part.file}") print(f" Size: {part.size} bytes") print(f" Duration: {part.duration}ms") # Iterate through all parts using helper method for part in movie.iterParts(): print(f"File path: {part.file}") # Access stream information for stream in movie.videoStreams: print(f"Video: {stream.codec} {stream.width}x{stream.height}") for stream in movie.audioStreams: print(f"Audio: {stream.codec} {stream.channels}ch - {stream.language}") for stream in movie.subtitleStreams: print(f"Subtitle: {stream.codec} - {stream.language}") ``` -------------------------------- ### Find Specific User Source: https://context7.com/hellowlol/plexapi/llms.txt Locate and retrieve a specific shared user by their email address. ```python user = account.user('friend@email.com') ``` -------------------------------- ### Find Movies by Director Source: https://github.com/hellowlol/plexapi/blob/master/README.md List all movies in the 'Movies' library that share the same director as a specified movie. This requires retrieving the director of one movie and then searching for others by that director. ```python # Example 6: List all movies directed by the same person as Jurassic Park. movies = plex.library.section('Movies') jurassic_park = movies.get('Jurassic Park') director = jurassic_park.directors[0] for movie in movies.search(None, director=director): print(movie.title) ``` -------------------------------- ### Search TV Shows and Episodes Source: https://context7.com/hellowlol/plexapi/llms.txt Perform searches within a TV Show library section by genre or year. Retrieves all shows of a specific genre or episodes from a particular year. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') # TV Show section specific methods tv = plex.library.section('TV Shows') all_shows = tv.searchShows(genre='Comedy') all_episodes = tv.searchEpisodes(year=2023) recent = tv.recentlyAdded(libtype='episode', maxresults=20) ``` -------------------------------- ### Episode Operations and Properties Source: https://context7.com/hellowlol/plexapi/llms.txt Retrieves the latest episode of a TV show and prints its properties, including show title, season and episode numbers, duration, rating, directors, and writers. This snippet assumes a valid Plex connection and that the specified show exists. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') show = plex.library.section('TV Shows').get('The Office') # Get the latest episode latest = show.episodes()[-1] print(f"Latest: S{latest.seasonNumber}E{latest.index} - {latest.title}") # Episode properties print(f"Show: {latest.grandparentTitle}") print(f"Season: {latest.parentIndex}") print(f"Episode: {latest.index}") print(f"Duration: {latest.duration // 60000} minutes") print(f"Rating: {latest.rating}") print(f"Directors: {[d.tag for d in latest.directors]}") print(f"Writers: {[w.tag for w in latest.writers]}") ``` -------------------------------- ### Advanced Plex Library Search Source: https://context7.com/hellowlol/plexapi/llms.txt Perform advanced searches within a Plex library section using various filters such as title, genre, year, director, actor, content rating, and resolution. Supports sorting by criteria like 'addedAt:desc' or 'rating:desc', and filtering for unwatched content. ```python from plexapi.server import PlexServer plex = PlexServer('http://localhost:32400', 'your-token') movies = plex.library.section('Movies') # Search by title results = movies.search(title='Star Wars') for movie in results: print(f"{movie.title} ({movie.year})") # Search with multiple filters action_2020 = movies.search(genre='Action', year=2020) spielberg_movies = movies.search(director='Steven Spielberg') # Search with sorting newest = movies.search(sort='addedAt:desc', maxresults=20) highest_rated = movies.search(sort='rating:desc', maxresults=10) # Filter unwatched movies unwatched = movies.search(unwatched=True) print(f"Unwatched movies: {len(unwatched)}") # Search by content rating pg13_movies = movies.search(contentRating='PG-13') # Search by resolution hd_movies = movies.search(resolution='1080') ``` -------------------------------- ### Handle Bad Request Errors in PlexAPI Source: https://context7.com/hellowlol/plexapi/llms.txt Catch BadRequest exceptions when making requests with invalid parameters, such as an invalid filter in a search query. ```python try: plex = PlexServer('http://localhost:32400', 'your-token') movies = plex.library.section('Movies') # Invalid filter results = movies.search(invalid_filter='value') except BadRequest as e: print(f"Bad request: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.