### Install PlexAPI Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/introduction.md Install the base library using pip. Extra features can be installed with specific dependencies. ```bash pip install plexapi ``` ```bash pip install plexapi[alert] # Install with dependencies required for plexapi.alert ``` ```bash pip install plexapi[jwt] # Install with dependencies required for Plex JWT authentication ``` -------------------------------- ### Install websocket-client for Alert Listener Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Install the 'websocket-client' library to enable the startAlertListener functionality. This is a prerequisite for receiving real-time notifications from the Plex Server. ```bash >> pip install websocket-client ``` -------------------------------- ### installUpdate Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Automatically installs the newest version of Plex Media Server. ```APIDOC ## installUpdate() ### Description Automatically install the newest version of Plex Media Server. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ``` -------------------------------- ### GDM Server Data Example Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/gdm.md Example structure of a discovered Plex Media Server entry. ```python [ { 'data': { 'Content-Type': 'plex/media-server', 'Host': '53f4b5b6023d41182fe88a99b0e714ba.plex.direct', 'Name': 'myfirstplexserver', 'Port': '32400', 'Resource-Identifier': '646ab0aa8a01c543e94ba975f6fd6efadc36b7', 'Updated-At': '1585769946', 'Version': '1.18.8.2527-740d4c206' }, 'from': ('10.10.10.100', 32414) } ] ``` -------------------------------- ### GDM Client Data Example Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/gdm.md Example structure of a discovered Plex client (player) entry. ```python [ { 'data': { 'Content-Type': 'plex/media-player', 'Device-Class': 'stb', 'Name': 'plexamp', 'Port': '36000', 'Product': 'Plexamp', 'Protocol': 'plex', 'Protocol-Capabilities': 'timeline,playback,playqueues,playqueues-creation', 'Protocol-Version': '1', 'Resource-Identifier': 'b6e57a3f-e0f8-494f-8884-f4b58501467e', 'Version': '1.1.0' }, 'from': ('10.10.10.101', 32412) } ] ``` -------------------------------- ### run Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Starts the thread which monitors the PIN login state. ```APIDOC ## run(callback=None, timeout=120) ### Description Starts the thread which monitors the PIN login state. ### Parameters #### Path Parameters - **callback** (Callable[[str]]) - Optional - Callback called with the received authentication token. - **timeout** (int) - Optional - Timeout in seconds to wait for user login. Default 120 seconds. ### Raises - **RuntimeError** – If the thread is already running. - **RuntimeError** – If the PIN login for the current PIN has expired. ``` -------------------------------- ### Start WebSocket Listener for Real-time Notifications Source: https://context7.com/pushingkarmaorg/python-plexapi/llms.txt Opens a WebSocket connection to receive real-time notifications from the Plex server. Requires `pip install websocket-client`. Ensure the callback functions `handle_alert` and `handle_error` are defined to process incoming data and errors. ```python from plexapi.server import PlexServer import time plex = PlexServer('http://plexserver:32400', 'token') def handle_alert(data): """Called for every notification received from the server.""" notification_type = data.get('type') print(f"Alert type: {notification_type}") if notification_type == 'timeline': for entry in data.get('TimelineEntry', []): state_map = {0: 'created', 1: 'processing', 2: 'matching', 3: 'downloading', 4: 'processing meta', 5: 'done', 9: 'deleted'} state = state_map.get(entry.get('state'), 'unknown') print(f" Library item state: {state} — {entry.get('title')}") elif notification_type == 'playing': for session in data.get('PlaySessionStateNotification', []): print(f" Session: {session.get('sessionKey')} state={session.get('state')}") def handle_error(error): print(f"WebSocket error: {error}") # Start listener — runs in a daemon thread listener = plex.startAlertListener(callback=handle_alert, callbackError=handle_error) # Keep the main thread alive try: time.sleep(60) finally: listener.stop() ``` -------------------------------- ### canInstallUpdate Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Checks if the newest version of Plex Media Server can be installed automatically. This is typically true for standard installations (Windows, Mac) but false for containerized or NAS installations. ```APIDOC ## canInstallUpdate() ### Description Returns True if the newest version of Plex Media Server can be installed automatically. (e.g. Windows and Mac can install updates automatically, but Docker and NAS devices cannot.) ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ``` -------------------------------- ### Basic Search Examples Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Demonstrates how to search for episodes and shows using the search method with different parameters. ```APIDOC ## Basic Search ### Description These examples show how to search for specific media items like episodes or shows using the `search` method with title and library type filters. ### Method ```python showLibrary.search(title="Winter is Coming", libtype='episode') showLibrary.search(libtype='episode', filters={"episode.title": "Winter is Coming"}) showLibrary.searchEpisodes(title="Winter is Coming") showLibrary.search(filters={"episode.title": "Winter is Coming"}) showLibrary.search(unwatched=True) ``` ### Notes - The first three options are identical and will return `Episode` objects. - The fourth option will search for the episode title but return `Show` objects. - The fifth option will fallback to searching for unwatched episodes. ``` -------------------------------- ### Create GUID Lookup Dictionary Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Create a dictionary for faster GUID lookups by iterating through all library items and their associated GUIDs. This is useful for quickly accessing specific media items using their Plex, IMDb, TMDB, or TVDB identifiers. ```python guidLookup = {} for item in library.all(): guidLookup[item.guid] = item guidLookup.update({guid.id: item for guid in item.guids}) result1 = guidLookup['plex://show/5d9c086c46115600200aa2fe'] result2 = guidLookup['imdb://tt0944947'] result3 = guidLookup['tmdb://1399'] result4 = guidLookup['tvdb://121361'] ``` -------------------------------- ### startAlertListener Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Creates a websocket connection to the Plex Server to optionally receive notifications for media scans and transcode session updates. Requires `websocket-client` to be installed. ```APIDOC ## startAlertListener(callback=None, callbackError=None) ### Description Creates a websocket connection to the Plex Server to optionally receive notifications. These often include messages from Plex about media scans as well as updates to currently running Transcode Sessions. Returns a new [`AlertListener`](alert.md#plexapi.alert.AlertListener) object. Note: `websocket-client` must be installed in order to use this feature. ```python >> pip install websocket-client ``` ### Parameters * **callback** (*func*) – Callback function to call on received messages. * **callbackError** (*func*) – Callback function to call on errors. ### Raises **Unsupported** – Websocket-client not installed. ``` -------------------------------- ### play Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/base.md Start playback of the media item on a specified Plex client. ```APIDOC ## play(client) ### Description Start playback on the specified client. ### Parameters #### Parameters - **client** ([`PlexClient`](client.md#plexapi.client.PlexClient)) - Client to start playing on. ``` -------------------------------- ### Syncing Movies to a Plex Client Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Sync movies to a specified Plex client device. This example demonstrates connecting to your Plex account, selecting a target device, and initiating a sync with specific quality, limit, and sorting options. ```python from plexapi import myplex from plexapi.sync import VIDEO_QUALITY_3_MBPS_720p c = myplex.MyPlexAccount() target = c.device('Plex Client') sync_items_wd = c.syncItems(target.clientIdentifier) srv = c.resource('Server Name').connect() section = srv.library.section('Movies') section.sync(VIDEO_QUALITY_3_MBPS_720p, client=target, limit=1, unwatched=True, title='Next best movie', sort='rating:desc') ``` -------------------------------- ### PlexAPI Configuration File Example Source: https://context7.com/pushingkarmaorg/python-plexapi/llms.txt PlexAPI reads settings from ~/.config/plexapi/config.ini and environment variables. Configuration keys follow the 'section.variable' format. ```ini # ~/.config/plexapi/config.ini [auth] server_baseurl = http://plexserver:32400 server_token = yourtoken myplex_username = user@example.com myplex_password = yourpassword [plexapi] timeout = 30 container_size = 100 enable_fast_connect = false [log] level = INFO ; path = /tmp/plexapi.log ; show_secrets = false ``` -------------------------------- ### GDM Discovery Example Data Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/gdm.md Examples of the data structure returned for discovered Plex servers and clients. ```APIDOC ## Data Structure Examples ### Server Example: ```json [ { "data": { "Content-Type": "plex/media-server", "Host": "53f4b5b6023d41182fe88a99b0e714ba.plex.direct", "Name": "myfirstplexserver", "Port": "32400", "Resource-Identifier": "646ab0aa8a01c543e94ba975f6fd6efadc36b7", "Updated-At": "1585769946", "Version": "1.18.8.2527-740d4c206" }, "from": ( "10.10.10.100", 32414 ) } ] ``` ### Client Example: ```json [ { "data": { "Content-Type": "plex/media-player", "Device-Class": "stb", "Name": "plexamp", "Port": "36000", "Product": "Plexamp", "Protocol": "plex", "Protocol-Capabilities": "timeline,playback,playqueues,playqueues-creation", "Protocol-Version": "1", "Resource-Identifier": "b6e57a3f-e0f8-494f-8884-f4b58501467e", "Version": "1.1.0" }, "from": ( "10.10.10.101", 32412 ) } ] ``` ``` -------------------------------- ### Play Media on Client Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/base.md Starts playback of a media item on a specified Plex client. ```python play(client) ``` -------------------------------- ### Example plexapi Configuration File Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/configuration.md This INI file demonstrates all possible configuration values for Python-PlexAPI. It includes settings for container size, timeout, authentication, headers, and logging. ```ini # ~/.config/plexapi/config.ini [plexapi] container_size = 50 timeout = 30 timezone = false [auth] myplex_username = johndoe myplex_password = kodi-stinks server_baseurl = http://127.0.0.1:32400 server_token = XBHSMSJSDJ763JSm client_baseurl = http://127.0.0.1:32433 client_token = BDFSLCNSNL789FH7 [header] identifier = 0x485b314307f3L platorm = Linux platform_version = 4.4.0-62-generic product = PlexAPI version = 3.0.0 [log] backup_count = 3 format = %(asctime)s %(module)12s:%(lineno)-4s %(levelname)-9s %(message)s level = INFO path = ~/.config/plexapi/plexapi.log rotate_bytes = 512000 show_secrets = false ``` -------------------------------- ### Get On Deck Media Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Retrieve a list of all media items currently on deck. ```APIDOC ## onDeck() ### Description Returns a list of all media items on deck. ### Method onDeck() ``` -------------------------------- ### resources() Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get a list of all MyPlexResource objects connected to your Plex account. ```APIDOC ## resources() ### Description Returns a list of all [`MyPlexResource`](#plexapi.myplex.MyPlexResource) objects connected to the server. ### Method APIDOC ### Endpoint APIDOC ``` -------------------------------- ### Initiate Plex OAuth Login and Get Account Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Use this snippet to initiate an OAuth login flow, print the URL for the user to visit, wait for the login to complete, and then create a MyPlexAccount instance with the retrieved token. ```python from plexapi.myplex import MyPlexAccount, MyPlexPinLogin pinlogin = MyPlexPinLogin(oauth=True) pinlogin.run() print(f'Login to Plex at the following url:\n{pinlogin.oauthUrl()}') pinlogin.waitForLogin() token = pinlogin.token account = MyPlexAccount(token=token) ``` -------------------------------- ### Using Plex Filters Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Explains how to use custom filters to refine search results, including examples of common filter fields. ```APIDOC ## Using Plex Filters ### Description Apply custom filters to narrow down search results. A list of available fields can be obtained using `listFields()`, operators with `listOperators()`, and filter choices with `listFilterChoices()`. ### Available Filter Fields (Examples) - **actor** (`MediaTag`): Search by actor's name. - **addedAt** (*datetime*): Search by date added (supports operators). - **audioLanguage** (*str*): Search by audio language code (e.g., 'jpn'). - **collection** (`MediaTag`): Search by collection name. - **contentRating** (`MediaTag`): Search by content rating. - **country** (`MediaTag`): Search by country. - **decade** (*int*): Search by decade (e.g., 2000). - **director** (`MediaTag`): Search by director's name. - **duplicate** (*bool*): Search for duplicate items. - **genre** (`MediaTag`): Search by genre. - **hdr** (*bool*): Search for HDR content. - **inProgress** (*bool*): Search for items currently in progress. - **label** (`MediaTag`): Search by label. - **lastViewedAt** (*datetime*): Search by last viewed date (supports operators). - **mood** (`MediaTag`): Search by mood. - **producer** (`MediaTag`): Search by producer's name. - **resolution** (*str*): Search by video resolution (e.g., '1080'). - **studio** (*str*): Search by studio name. - **style** (`MediaTag`): Search by style. - **subtitleLanguage** (*str*): Search by subtitle language code (e.g., 'eng'). - **unmatched** (*bool*): Search for unmatched items. - **unwatched** (*bool*): Search for unwatched items. - **userRating** (*int*): Search by user rating. - **writer** (`MediaTag`): Search by writer's name. - **year** (*int*): Search by year. ### Filter Value Types - **Tag type filters**: Can accept `FilterChoice` object, `MediaTag` object, `MediaTag.tag` (string), or `MediaTag.id` (integer). - **Date type filters**: Can accept `datetime` object, relative date string (e.g., '30d'), or 'YYYY-MM-DD' string. ### Relative Date Suffixes - `s`: seconds - `m`: minutes - `h`: hours - `d`: days - `w`: weeks - `mon`: months - `y`: years ### OR Operations Multiple values for a filter can be combined using a list to perform an OR operation. ### Examples ```python # Search for unwatched items from 2020 with 4k resolution library.search(unwatched=True, year=2020, resolution="4k") # Search for items by Arnold Schwarzenegger from the 1990s library.search(actor="Arnold Schwarzenegger", decade=1990) # Search for TV-G rated animated content library.search(contentRating="TV-G", genre="animation") # Search for animation OR comedy genres library.search(genre=["animation", "comedy"]) # Search for items from Disney OR Pixar studios library.search(studio=["Disney", "Pixar"]) ``` ``` -------------------------------- ### MyPlexPinLogin.run Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Start the background thread that monitors the PIN login status. This method can optionally accept a callback function. ```APIDOC ## run(callback=None, timeout=120) ### Description Starts the thread which monitors the PIN login state. This method supports a callback for asynchronous notification. ### Parameters - **callback** (Callable[[str], None], optional) - Callback called with the received authentication token. - **timeout** (int, optional) - Timeout in seconds to wait for user login. Default 120 seconds. ### Raises - **RuntimeError** - If the thread is already running. - **RuntimeError** - If the PIN login for the current PIN has expired. ``` -------------------------------- ### Get Media Item by GUID Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Retrieve a media item using its Plex, IMDB, TMDB, or TVDB ID. This method is only supported for Plex Movie and Plex TV Series agents. Raises NotFound if the GUID is not found. ```python result1 = library.getGuid('plex://show/5d9c086c46115600200aa2fe') result2 = library.getGuid('imdb://tt0944947') result3 = library.getGuid('tmdb://1399') result4 = library.getGuid('tvdb://121361') ``` -------------------------------- ### Get Watchlist and Search Item Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Retrieve released movies from the watchlist, sorted by rating, and then search for the first item on a Plex server using its GUID. ```python # Watchlist for released movies sorted by critic rating in descending order watchlist = account.watchlist(filter='released', sort='rating:desc', libtype='movie') item = watchlist[0] # First item in the watchlist # Search for the item on a Plex server result = plex.library.search(guid=item.guid, libtype=item.type) ``` -------------------------------- ### createHomeUser(user, server, sections=None, allowSync=False, allowCameraUpload=False, allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None) Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Create a home user and share library content with them. Allows configuration of sync, camera upload, and channel access, along with content filtering. ```APIDOC ## createHomeUser(user, server, sections=None, allowSync=False, allowCameraUpload=False, allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None) ### Description Share library content with the specified user. ### Parameters #### Path Parameters - **user** (MyPlexUser | str) - Required - MyPlexUser object, username, or email of the user to be added. - **server** (PlexServer | str) - Required - PlexServer object, or machineIdentifier containing the library sections to share. - **sections** (List[LibrarySection] | List[str]) - Optional - List of LibrarySection objects, or names to be shared (default None). sections must be defined in order to update shared libraries. - **allowSync** (Bool) - Optional - Set True to allow user to sync content. - **allowCameraUpload** (Bool) - Optional - Set True to allow user to upload photos. - **allowChannels** (Bool) - Optional - Set True to allow user to utilize installed channels. - **filterMovies** (Dict) - Optional - Dict containing key ‘contentRating’ and/or ‘label’ each set to a list of values to be filtered. ex: {‘contentRating’:[‘G’], ‘label’:[‘foo’]} - **filterTelevision** (Dict) - Optional - Dict containing key ‘contentRating’ and/or ‘label’ each set to a list of values to be filtered. ex: {‘contentRating’:[‘G’], ‘label’:[‘foo’]} - **filterMusic** (Dict) - Optional - Dict containing key ‘label’ set to a list of values to be filtered. ex: {‘label’:[‘foo’]} ### Method APIDOC ### Endpoint APIDOC ``` -------------------------------- ### Create Regular and Smart Playlists Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Demonstrates creating a regular playlist from a list of items and a smart playlist with specific criteria like limit, sort order, and filters. Use for organizing media collections. ```python episodes = plex.library.section("TV Shows").get("Game of Thrones").episodes() playlist = plex.createPlaylist( title="GoT Episodes", items=episodes ) ``` ```python playlist = plex.createPlaylist( title="Top 10 Unwatched Movies", section="Movies", smart=True, limit=10, sort="audienceRating:desc", filters={"audienceRating>>": 8.0, "unwatched": True} ) ``` -------------------------------- ### Guid Media Object Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/media.md Represents a single Guid media tag. It inherits from PlexObject and has TAG set to 'Guid'. ```APIDOC ## plexapi.media.Guid ### Description Represents a single Guid media tag. ### Variables * **TAG** (*str*) – ‘Guid’ * **id** (*id*) – The guid for external metadata sources (e.g. IMDB, TMDB, TVDB, MBID). ``` -------------------------------- ### PlexServer Initialization Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Initialize a connection to your Plex Media Server. You can provide the base URL and authentication token directly, or use your Plex account credentials to discover the server. ```APIDOC ## PlexServer(baseurl=None, token=None, session=None, timeout=None) ### Description This is the main entry point to interacting with a Plex server. It allows you to list connected clients, browse your library sections and perform actions such as emptying trash. If you do not know the auth token required to access your Plex server, or simply want to access your server with your username and password, you can also create an PlexServer instance from MyPlexAccount. ### Parameters * **baseurl** (*str*) – Base url for to access the Plex Media Server (default: ‘[http://localhost:32400](http://localhost:32400)’). * **token** (*str*) – Required Plex authentication token to access the server. * **session** (*requests.Session* *,* *optional*) – Use your own session object if you want to cache the http responses from the server. * **timeout** (*int* *,* *optional*) – Timeout in seconds on initial connection to the server (default config.TIMEOUT). ### Variables * **allowCameraUpload** (*bool*) – True if server allows camera upload. * **allowChannelAccess** (*bool*) – True if server allows channel access (iTunes?). * **allowMediaDeletion** (*bool*) – True is server allows media to be deleted. * **allowSharing** (*bool*) – True is server allows sharing. * **allowSync** (*bool*) – True is server allows sync. * **backgroundProcessing** (*bool*) – Unknown * **certificate** (*bool*) – True if server has an HTTPS certificate. * **companionProxy** (*bool*) – Unknown * **diagnostics** (*bool*) – Unknown * **eventStream** (*bool*) – Unknown * **friendlyName** (*str*) – Human friendly name for this server. * **hubSearch** (*bool*) – True if [Hub Search](https://www.plex.tv/blog/seek-plex-shall-find-leveling-web-app/) is enabled. I believe this is enabled for everyone * **machineIdentifier** (*str*) – Unique ID for this server (looks like an md5). * **multiuser** (*bool*) – True if [multiusers](https://support.plex.tv/hc/en-us/articles/200250367-Multi-User-Support) are enabled. * **myPlex** (*bool*) – Unknown (True if logged into myPlex?). * **myPlexMappingState** (*str*) – Unknown (ex: mapped). * **myPlexSigninState** (*str*) – Unknown (ex: ok). * **myPlexSubscription** (*bool*) – True if you have a myPlex subscription. * **myPlexUsername** (*str*) – Email address if signed into myPlex ([user@example.com](mailto:user@example.com)) * **ownerFeatures** (*list*) – List of features allowed by the server owner. This may be based on your PlexPass subscription. Features include: camera_upload, cloudsync, content_filter, dvr, hardware_transcoding, home, lyrics, music_videos, pass, photo_autotags, premium_music_metadata, session_bandwidth_restrictions, sync, trailers, webhooks (and maybe more). * **photoAutoTag** (*bool*) – True if photo [auto-tagging](https://support.plex.tv/articles/234976627-Auto-Tagging-of-Photos) is enabled. * **platform** (*str*) – Platform the server is hosted on (ex: Linux) * **platformVersion** (*str*) – Platform version (ex: ‘6.1 (Build 7601)’, ‘4.4.0-59-generic’). * **pluginHost** (*bool*) – Unknown * **readOnlyLibraries** (*bool*) – Unknown * **requestParametersInCookie** (*bool*) – Unknown * **streamingBrainVersion** (*bool*) – Current [Streaming Brain](https://www.plex.tv/blog/mcstreamy-brain-take-world-two-easy-steps/) version. * **sync** (*bool*) – True if [syncing to a device](https://support.plex.tv/articles/201053678-Sync-Media-to-a-Device) is enabled. * **transcoderActiveVideoSessions** (*int*) – Number of active video transcoding sessions. * **transcoderAudio** (*bool*) – True if audio transcoding audio is available. * **transcoderLyrics** (*bool*) – True if audio transcoding lyrics is available. * **transcoderPhoto** (*bool*) – True if audio transcoding photos is available. * **transcoderSubtitles** (*bool*) – True if audio transcoding subtitles is available. * **transcoderVideo** (*bool*) – True if audio transcoding video is available. * **transcoderVideoBitrates** (*bool*) – List of video bitrates. * **transcoderVideoQualities** (*bool*) – List of video qualities. * **transcoderVideoResolutions** (*bool*) – List of video resolutions. * **updatedAt** (*int*) – Datetime the server was updated. * **updater** (*bool*) – Unknown * **version** (*str*) – Current Plex version (ex: 1.3.2.3112-1751929) * **voiceSearch** (*bool*) – True if voice search is enabled. (is this Google Voice search?) * **_baseurl** (*str*) – HTTP address of the client. * **_token** (*str*) – Token used to access this client. * **_session** (*obj*) – Requests session object used to access this client. ``` -------------------------------- ### goToHome Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/client.md Go directly to the home screen. ```APIDOC ## goToHome() Go directly to the home screen. ``` -------------------------------- ### Guid Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Represents a single Guid library media tag. It inherits from LibraryMediaTag and has a specific TAGTYPE. ```APIDOC ## class plexapi.library.Guid(server, data, initpath=None, parent=None) Bases: [`LibraryMediaTag`](#plexapi.library.LibraryMediaTag) Represents a single Guid library media tag. * **Variables:** **TAGTYPE** (*int*) – 314 ``` -------------------------------- ### Create Music Playlist from M3U File Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Shows how to create a music playlist by importing an M3U file. Ensure the specified section is a music library. ```python playlist = plex.createPlaylist( title="Favorite Tracks", section="Music", m3ufilepath="/path/to/playlist.m3u" ) ``` -------------------------------- ### Create and Manage Plex Collections Source: https://context7.com/pushingkarmaorg/python-plexapi/llms.txt Shows how to create manual and smart collections, add/remove items, edit details, change display modes, and delete collections. Requires a PlexServer instance and library section access. ```python from plexapi.server import PlexServer plex = PlexServer('http://plexserver:32400', 'token') movies = plex.library.section('Movies') # Regular collection from specific movies m1 = movies.get('The Dark Knight') m2 = movies.get('Batman Begins') m3 = movies.get('The Dark Knight Rises') collection = plex.createCollection( title='The Dark Knight Trilogy', section=movies, items=[m1, m2, m3] ) print(f"Created: {collection.title} ({collection.childCount} items") # Smart collection — all animated G-rated movies smart_col = plex.createCollection( title='Family Animated Movies', section='Movies', smart=True, sort='titleSort:asc', filters={'contentRating': 'G', 'genre': 'Animation'} ) # Manage collection col = movies.collection('The Dark Knight Trilogy') col.addItems([movies.get('Batman v Superman: Dawn of Justice')]) col.removeItems([m3]) # Edit collection display col.editTitle('DC Batman Films') col.editSummary('The Batman film series from DC/Warner Bros.') col.editSortTitle('Batman') # Change collection mode (default, hide, hideItems, showItems) col.modeHide() col.modeDefault() col.delete() ``` -------------------------------- ### Connect to Plex Server and Switch User Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Connect to your Plex server using its URL and token. Demonstrates how to switch to a different user account on the same server. ```python from plexapi.server import PlexServer # Login to the Plex server using the admin token plex = PlexServer('http://plexserver:32400', token='2ffLuB84dqLswk9skLos') # Login to the same Plex server using a different account userPlex = plex.switchUser("Username") ``` -------------------------------- ### add(name, type, agent, scanner, location, language, *args, **kwargs) Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Simplified method for adding a new media library with common options. Allows for detailed configuration through keyword arguments. ```APIDOC ## add(name, type, agent, scanner, location, language, *args, **kwargs) ### Description Simplified method for adding a new media library with common options. Allows for detailed configuration through keyword arguments. ### Parameters #### Path Parameters * **name** (str) - Required - Name of the library. * **agent** (str) - Required - Example: com.plexapp.agents.imdb. * **type** (str) - Required - Type of media library (e.g., movie, show). * **location** (str or list) - Required - Path(s) to the media files. * **language** (str) - Optional - Language code for the library (e.g., en-US). Default value 'en-US'. * **scanner** (str) - Optional - The scanner to use for this library. * **kwargs** (dict) - Optional - Advanced options for library configuration. ### Photo Preferences (kwargs) * **agent** (str) - Optional - Agent for photo libraries. Default: com.plexapp.agents.none. * **enableAutoPhotoTags** (bool) - Optional - Enable automatic photo tagging. Default: false. * **enableBIFGeneration** (bool) - Optional - Enable video preview thumbnail generation. Default: true. * **includeInGlobal** (bool) - Optional - Include in dashboard. Default: true. * **scanner** (str) - Optional - Scanner for photo libraries. ### Movie Preferences (kwargs) * **agent** (str) - Optional - Agent for movie libraries. Possible options: com.plexapp.agents.none, com.plexapp.agents.imdb, tv.plex.agents.movie, com.plexapp.agents.themoviedb. Default: com.plexapp.agents.imdb. * **enableBIFGeneration** (bool) - Optional - Enable video preview thumbnail generation. Default: true. * **enableCinemaTrailers** (bool) - Optional - Enable Cinema Trailers. Default: true. * **includeInGlobal** (bool) - Optional - Include in dashboard. Default: true. * **scanner** (str) - Optional - Scanner for movie libraries. Possible options: Plex Movie, Plex Movie Scanner, Plex Video Files Scanner, Plex Video Files. ### IMDB Movie Options (kwargs, when agent is com.plexapp.agents.imdb) * **title** (bool) - Optional - Use localized titles. Default: false. * **extras** (bool) - Optional - Find trailers and extras automatically (Plex Pass required). Default: true. * **only_trailers** (bool) - Optional - Skip extras which aren’t trailers. Default: false. * **redband** (bool) - Optional - Use red band (restricted audiences) trailers when available. Default: false. * **native_subs** (bool) - Optional - Include extras with subtitles in Library language. Default: false. * **cast_list** (int) - Optional - Cast List Source. Default: 1. Possible options: 0:IMDb, 1:The Movie Database. * **ratings** (int) - Optional - Ratings Source. Default: 0. Possible options: 0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database. * **summary** (int) - Optional - Plot Summary Source. Default: 1. Possible options: 0:IMDb, 1:The Movie Database. * **country** (int) - Optional - Country code. Default: 46. See source for full list of options. * **collections** (bool) - Optional - Use collection info from The Movie Database. Default: false. * **localart** (bool) - Optional - Prefer artwork based on library language. Default: true. * **adult** (bool) - Optional - Include adult content. Default: false. * **usage** (bool) - Optional - Send anonymous usage data to Plex. Default: true. ### TheMovieDB Movie Options (kwargs, when agent is com.plexapp.agents.themoviedb) * **collections** (bool) - Optional - Use collection info from The Movie Database. Default: false. * **localart** (bool) - Optional - Prefer artwork based on library language. Default: true. * **adult** (bool) - Optional - Include adult content. Default: false. * **country** (int) - Optional - Country code (used for release date and content rating). Default: 47. See source for full list of options. ### Show Preferences (kwargs) * **agent** (str) - Optional - Agent for show libraries. Possible options: com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb, tv.plex.agents.series. Default: com.plexapp.agents.thetvdb. * **enableBIFGeneration** (bool) - Optional - Enable video preview thumbnail generation. Default: true. * **episodeSort** (int) - Optional - Episode order. Default: -1. Possible options: 0:Oldest first, 1:Newest first. * **flattenSeasons** (int) - Optional - Season display. Default: 0. Possible options: 0:Show, 1:Hide. * **includeInGlobal** (bool) - Optional - Include in dashboard. Default: true. ``` -------------------------------- ### plexapi.utils.sha1hash Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/utils.md Return the SHA1 hash of a guid. ```APIDOC ## plexapi.utils.sha1hash(guid) ### Description Return the SHA1 hash of a guid. ### Parameters #### Path Parameters * **guid** (str) - Required - The guid to hash. ``` -------------------------------- ### MyPlexServerShare.history Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get all Play History for a user in this shared server. ```APIDOC ## history(maxresults=9999999, mindate=None) ### Description Get all Play History for a user in this shared server. ### Parameters #### Query Parameters - **maxresults** (int) - Optional - Only return the specified number of results. - **mindate** (datetime) - Optional - Min datetime to return results from. ``` -------------------------------- ### Login and Switch Plex Home User Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Demonstrates how to log in to a Plex Home account and switch to a different home user. Requires valid Plex username and password. ```python from plexapi.myplex import MyPlexAccount # Login to a Plex Home account account = MyPlexAccount('', '') # Switch to a different Plex Home user userAccount = account.switchHomeUser('Username') ``` -------------------------------- ### geoip Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get geolocation information for a given IP address. ```APIDOC ## geoip(ip_address) ### Description Returns a [`GeoLocation`](#plexapi.myplex.GeoLocation) object with geolocation information for an IP address using Plex’s GeoIP database. ### Parameters * **ip_address** (*str*) – IP address to lookup. ``` -------------------------------- ### Get All Media Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Retrieve a list of all media items from all library sections. ```APIDOC ## all(**kwargs) ### Description Returns a list of all media from all library sections. This may be a very large dataset to retrieve. ### Method all(**kwargs) ``` -------------------------------- ### create Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/playlist.md Create a playlist on the Plex server. Can be a regular playlist with specified items or a smart playlist with filters. ```APIDOC ## create(server, title, section=None, items=None, smart=False, limit=None, libtype=None, sort=None, filters=None, m3ufilepath=None, **kwargs) ### Description Create a playlist. ### Parameters #### Path Parameters * **server** ([`PlexServer`](server.md#plexapi.server.PlexServer)) - Required - Server to create the playlist on. * **title** (str) - Required - Title of the playlist. * **section** ([`LibrarySection`](library.md#plexapi.library.LibrarySection), str) - Optional - Smart playlists and m3u import only, the library section to create the playlist in. * **items** (List) - Optional - Regular playlists only, list of [`Audio`](audio.md#plexapi.audio.Audio), [`Video`](video.md#plexapi.video.Video), or [`Photo`](photo.md#plexapi.photo.Photo) objects to be added to the playlist. * **smart** (bool) - Optional - True to create a smart playlist. Default False. * **limit** (int) - Optional - Smart playlists only, limit the number of items in the playlist. * **libtype** (str) - Optional - Smart playlists only, the specific type of content to filter (movie, show, season, episode, artist, album, track, photoalbum, photo). * **sort** (str or list) - Optional - Smart playlists only, a string of comma separated sort fields or a list of sort fields in the format `column:dir`. See [`search()`](library.md#plexapi.library.LibrarySection.search) for more info. * **filters** (dict) - Optional - Smart playlists only, a dictionary of advanced filters. See [`search()`](library.md#plexapi.library.LibrarySection.search) for more info. * **m3ufilepath** (str) - Optional - Music playlists only, the full file path to an m3u file to import. Note: This will overwrite any playlist previously created from the same m3u file. * **kwargs** (dict) - Optional - Smart playlists only, additional custom filters to apply to the search results. See [`search()`](library.md#plexapi.library.LibrarySection.search) for more info. ### Raises * [**plexapi.exceptions.BadRequest**](exceptions.md#plexapi.exceptions.BadRequest) – When no items are included to create the playlist. * [**plexapi.exceptions.BadRequest**](exceptions.md#plexapi.exceptions.BadRequest) – When mixing media types in the playlist. * [**plexapi.exceptions.BadRequest**](exceptions.md#plexapi.exceptions.BadRequest) – When attempting to import m3u file into non-music library. * [**plexapi.exceptions.BadRequest**](exceptions.md#plexapi.exceptions.BadRequest) – When failed to import m3u file. ### Returns A new instance of the created Playlist. ### Return type [`Playlist`](#plexapi.playlist.Playlist) ``` -------------------------------- ### Get Hubs Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Retrieve a list of hubs across all library sections. ```APIDOC ## hubs(sectionID=None, identifier=None, **kwargs) ### Description Returns a list of [`Hub`](#plexapi.library.Hub) across all library sections. ### Method hubs(sectionID=None, identifier=None, **kwargs) ### Parameters #### Query Parameters - **sectionID** (int or str or list, optional) - IDs of the sections to limit results or “playlists”. - **identifier** (str or list, optional) - Names of identifiers to limit results. Available on Hub instances as the hubIdentifier attribute. Examples: ‘home.continue’ or ‘home.ondeck’ ``` -------------------------------- ### MyPlexUser.history Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get the play history for a user across all shared servers. ```APIDOC ## history(maxresults=None, mindate=None) ### Description Get all Play History for a user in all shared servers. ### Parameters * **maxresults** (*int* *,* *optional*) – Only return the specified number of results. * **mindate** (*datetime*) – Min datetime to return results from. ``` -------------------------------- ### history Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get Play History for all library sections on all servers for the owner. ```APIDOC ## history(maxresults=None, mindate=None) ### Description Get Play History for all library sections on all servers for the owner. ### Parameters #### Query Parameters - **maxresults** (int) - Optional - Only return the specified number of results. - **mindate** (datetime) - Optional - Min datetime to return results from. ``` -------------------------------- ### Create Regular Collection with Items Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Use this to create a regular collection by providing a list of specific media items. Ensure the section is correctly identified. ```python movies = plex.library.section("Movies") movie1 = movies.get("Big Buck Bunny") movie2 = movies.get("Sita Sings the Blues") collection = plex.createCollection( title="Favorite Movies", section=movies, items=[movie1, movie2] ) ``` -------------------------------- ### AccountOptOut.optIn Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Sets the Online Media Source to “Enabled”. ```APIDOC ## optIn() ### Description Sets the Online Media Source to “Enabled”. ``` -------------------------------- ### devices() Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Get a list of all MyPlexDevice objects connected to your Plex account. ```APIDOC ## devices() ### Description Returns a list of all [`MyPlexDevice`](#plexapi.myplex.MyPlexDevice) objects connected to the server. ### Method APIDOC ### Endpoint APIDOC ``` -------------------------------- ### MyPlexPinLogin Initialization Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/myplex.md Initialize the MyPlexPinLogin class, optionally with a custom session, timeout, headers, or by enabling OAuth. ```APIDOC ## MyPlexPinLogin(session=None, requestTimeout=None, headers=None, oauth=False) ### Description Initializes the MyPlexPinLogin class to handle Plex authentication via PIN or OAuth. ### Parameters - **session** (requests.Session, optional) - Use your own session object if you want to cache the http responses from Plex. - **requestTimeout** (int, optional) - Timeout in seconds on initial connect to plex.tv (default config.TIMEOUT). - **headers** (dict, optional) - A dict of X-Plex headers to send with requests. - **oauth** (bool, optional) - True to use Plex OAuth instead of PIN login. ``` -------------------------------- ### isLatest Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/server.md Determines if the installed Plex Media Server version is the latest available. ```APIDOC ## isLatest() ### Description Returns True if the installed version of Plex Media Server is the latest. ``` -------------------------------- ### contextMenu Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/client.md Open the context menu on the client. ```APIDOC ## contextMenu() Open the context menu on the client. ``` -------------------------------- ### Create and Manage Plex Play Queues Source: https://context7.com/pushingkarmaorg/python-plexapi/llms.txt Illustrates creating PlayQueues from single items or lists, shuffling, repeating, retrieving by ID, and playing on a client. Requires PlexServer and PlayQueue imports. ```python from plexapi.server import PlexServer from plexapi.playqueue import PlayQueue plex = PlexServer('http://plexserver:32400', 'token') movies = plex.library.section('Movies') shows = plex.library.section('TV Shows') # Create a PlayQueue from a single movie movie = movies.get('Cars') pq = plex.createPlayQueue(movie) print(f"PlayQueue ID: {pq.playQueueID}, Items: {pq.playQueueTotalCount}") # Create a shuffled PlayQueue from all episodes of a show episodes = shows.get('Breaking Bad').episodes() pq = PlayQueue.create(plex, episodes, shuffle=True, repeat=False) print(f"Shuffled: {pq.playQueueShuffled}") print(f"Selected item: {pq.selectedItem.title}") # Retrieve existing PlayQueue by ID pq2 = PlayQueue.get(plex, pq.playQueueID) for item in pq2.items: print(f" [{item.playQueueItemID}] {item.title}") # Play the queue on a client client = plex.client("Living Room Apple TV") client.playMedia(pq) ``` -------------------------------- ### Get Library Section by Title Source: https://github.com/pushingkarmaorg/python-plexapi/blob/master/docs/modules/library.md Retrieve a specific library section by its title. ```APIDOC ## section(title) ### Description Returns the [`LibrarySection`](#plexapi.library.LibrarySection) that matches the specified title. Note: Multiple library sections with the same title is ambiguous. Use [`sectionByID()`](#plexapi.library.Library.sectionByID) instead for an exact match. ### Method section(title) ### Parameters #### Path Parameters - **title** (str) - Required - Title of the section to return. ### Raises [**NotFound**](exceptions.md#plexapi.exceptions.NotFound) – The library section title is not found on the server. ```