Python bindings for the Plex Media Server API, enabling programmatic interaction with Plex servers and media libraries.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Control Plex client applications, manage playback, navigate interfaces, and handle media streaming to various devices including specialized Sonos support.
Interface for controlling Plex client applications and media playback.
class PlexClient:
def __init__(self, server=None, data=None, initpath=None, baseurl=None, identifier=None, token=None, connect=True, session=None, timeout=None, parent=None):
"""
Create PlexClient for controlling a Plex player.
Args:
server (PlexServer, optional): Associated server
data (dict, optional): Client data from server
initpath (str, optional): Path used to generate data
baseurl (str, optional): Direct client URL
identifier (str, optional): Resource/machine identifier for specific client
token (str, optional): Authentication token
connect (bool): Whether to connect immediately
session (requests.Session, optional): HTTP session
timeout (int, optional): Request timeout
parent (optional): Parent object
"""
def connect(self, timeout=None):
"""
Establish connection to client.
Args:
timeout (int, optional): Connection timeout
Returns:
PlexClient: Connected client instance
Raises:
Unsupported: If client doesn't support remote control
"""
def proxyThroughServer(self, value=True, server=None):
"""
Route client commands through Plex server.
Args:
value (bool): Enable/disable server proxy
server (PlexServer, optional): Server to proxy through
"""Control client interface navigation and menu interaction.
class PlexClient:
def goBack(self):
"""Navigate back to previous screen."""
def goToHome(self):
"""Navigate to home screen."""
def goToMusic(self):
"""Navigate to music section."""
def moveUp(self):
"""Move selection up."""
def moveDown(self):
"""Move selection down."""
def moveLeft(self):
"""Move selection left."""
def moveRight(self):
"""Move selection right."""
def select(self):
"""Select current item."""
def contextMenu(self):
"""Open context menu for current item."""
def pageUp(self):
"""Page up in current view."""
def pageDown(self):
"""Page down in current view."""Fundamental playback control commands.
class PlexClient:
def play(self, mtype='music'):
"""
Start or resume playback.
Args:
mtype (str): Media type ('music', 'video', 'photo')
"""
def pause(self, mtype='music'):
"""
Pause playback.
Args:
mtype (str): Media type ('music', 'video', 'photo')
"""
def stop(self, mtype='music'):
"""
Stop playback.
Args:
mtype (str): Media type ('music', 'video', 'photo')
"""
def skipNext(self):
"""Skip to next item in queue."""
def skipPrevious(self):
"""Skip to previous item in queue."""
def seekTo(self, offset, mtype='music'):
"""
Seek to specific time position.
Args:
offset (int): Time offset in milliseconds
mtype (str): Media type ('music', 'video', 'photo')
"""Control audio volume and playback modes.
class PlexClient:
def setVolume(self, volume, mtype='music'):
"""
Set playback volume.
Args:
volume (int): Volume level (0-100)
mtype (str): Media type ('music', 'video', 'photo')
"""
def setRepeat(self, repeat, mtype='music'):
"""
Set repeat mode.
Args:
repeat (int): Repeat mode (0=off, 1=repeat-one, 2=repeat-all)
mtype (str): Media type ('music', 'video', 'photo')
"""
def setShuffle(self, shuffle, mtype='music'):
"""
Set shuffle mode.
Args:
shuffle (bool): Enable/disable shuffle mode
mtype (str): Media type ('music', 'video', 'photo')
"""Control playback of specific media items.
class PlexClient:
def playMedia(self, media, offset=0, **params):
"""
Play specific media item.
Args:
media: Media object to play (Movie, Episode, Track, etc.)
offset (int): Start offset in milliseconds
**params: Additional playback parameters
- shuffle (bool): Enable shuffle mode
- repeat (int): Repeat mode
- includeChapters (bool): Include chapter information
- includeRelated (bool): Include related content
"""
def setAudioStream(self):
"""Select audio stream for current media."""
def setSubtitleStream(self):
"""Select subtitle stream for current media."""
def setVideoStream(self):
"""Select video quality stream for current media."""Monitor playback status and timeline information.
class PlexClient:
def timelines(self, wait=0):
"""
Get playback timeline status.
Args:
wait (int): Wait time for timeline updates
Returns:
list: List of ClientTimeline objects for each media type
"""
def isPlayingMedia(self, includePaused=True):
"""
Check if client is playing media.
Args:
includePaused (bool): Include paused media as "playing"
Returns:
bool: True if media is playing/paused
"""
class ClientTimeline:
"""Playback timeline and status information."""
@property
def state(self):
"""str: Playback state ('playing', 'paused', 'stopped')."""
@property
def time(self):
"""int: Current playback time in milliseconds."""
@property
def duration(self):
"""int: Total media duration in milliseconds."""
@property
def ratingKey(self):
"""str: Currently playing media rating key."""
@property
def type(self):
"""str: Media type ('video', 'music', 'photo')."""Control Sonos speakers through Plex integration.
class PlexSonosClient:
"""Specialized client for controlling Sonos speakers."""
def __init__(self, server, data, initpath=None):
"""
Create Sonos client controller.
Args:
server (PlexServer): Associated Plex server
data (dict): Sonos device data
initpath (str, optional): Initialization path
"""
def playMedia(self, media, **kwargs):
"""Play media on Sonos speaker."""
def setVolume(self, volume):
"""Set Sonos speaker volume."""
def play(self):
"""Start/resume Sonos playback."""
def pause(self):
"""Pause Sonos playback."""
def stop(self):
"""Stop Sonos playback."""from plexapi.server import PlexServer
plex = PlexServer('http://localhost:32400', token='your-token')
# Get available clients
clients = plex.clients()
for client in clients:
print(f"Client: {client.title} ({client.product})")
# Connect to specific client
tv_client = plex.client('Living Room TV')
tv_client.connect()
# Basic playback control
tv_client.play()
tv_client.pause()
tv_client.stop()# Get media to play
movie = plex.library.section('Movies').get('The Matrix')
episode = plex.library.section('TV Shows').get('The Office').episode(season=1, episode=1)
# Play media on client
tv_client.playMedia(movie)
tv_client.playMedia(episode, offset=30000) # Start 30 seconds in
# Control playback
tv_client.seekTo(120000) # Seek to 2 minutes
tv_client.skipNext() # Skip to next item# Navigate client interface
tv_client.goToHome()
tv_client.goToMusic()
# Menu navigation
tv_client.moveDown()
tv_client.moveRight()
tv_client.select()
tv_client.contextMenu()
# Page navigation
tv_client.pageDown()
tv_client.goBack()# Volume control
tv_client.setVolume(75) # Set volume to 75%
# Playback modes
tv_client.setRepeat(1) # Repeat current item
tv_client.setShuffle(True) # Enable shuffle
# Stream selection for video
tv_client.setAudioStream() # Cycle audio streams
tv_client.setSubtitleStream() # Cycle subtitle streams# Check if playing
if tv_client.isPlayingMedia():
print("Client is currently playing media")
# Get detailed timeline information
timelines = tv_client.timelines()
for timeline in timelines:
if timeline.state == 'playing':
progress = (timeline.time / timeline.duration) * 100
print(f"Playing: {timeline.type} - {progress:.1f}% complete")
print(f"Time: {timeline.time // 1000}s / {timeline.duration // 1000}s")# Proxy through server for remote clients
tv_client.proxyThroughServer(True, server=plex)
# Play with advanced options
tv_client.playMedia(
movie,
offset=0,
shuffle=False,
repeat=0,
includeChapters=True,
includeRelated=True
)
# Timeline monitoring with updates
import time
while tv_client.isPlayingMedia():
timelines = tv_client.timelines(wait=1000) # Wait 1 second for updates
for timeline in timelines:
if timeline.state == 'playing':
print(f"Current time: {timeline.time // 1000}s")
time.sleep(1)# Find Sonos devices
sonos_clients = [c for c in plex.clients() if 'sonos' in c.product.lower()]
if sonos_clients:
sonos = sonos_clients[0]
# Play music on Sonos
album = plex.library.section('Music').get('Abbey Road')
sonos.playMedia(album)
# Control Sonos playback
sonos.setVolume(50)
sonos.pause()
sonos.play()from plexapi.exceptions import Unsupported, NotFound
try:
# Try to connect to client
client = plex.client('Bedroom TV')
client.connect()
# Try to play media
movie = plex.library.section('Movies').get('Some Movie')
client.playMedia(movie)
except NotFound as e:
print(f"Client or media not found: {e}")
except Unsupported as e:
print(f"Client doesn't support remote control: {e}")# Control multiple clients simultaneously
clients = plex.clients()
connected_clients = []
# Connect to all available clients
for client in clients:
try:
client.connect()
connected_clients.append(client)
print(f"Connected to {client.title}")
except Unsupported:
print(f"{client.title} doesn't support remote control")
# Pause all clients
for client in connected_clients:
if client.isPlayingMedia():
client.pause()
print(f"Paused {client.title}")
# Resume all clients
for client in connected_clients:
client.play()
print(f"Resumed {client.title}")Install with Tessl CLI
npx tessl i tessl/pypi-plex-api