MyPlex account services for user authentication, server sharing, managed users, friend invitations, and cloud-based features like watchlists and content discovery.
Primary interface for Plex.tv account services and authentication.
class MyPlexAccount:
def __init__(self, username=None, password=None, token=None, session=None, timeout=None, code=None, remember=True):
"""
Authenticate with MyPlex (Plex.tv) account.
Args:
username (str, optional): Plex username or email
password (str, optional): Account password
token (str, optional): Authentication token
session (requests.Session, optional): HTTP session
timeout (int, optional): Request timeout
code (str, optional): Two-factor authentication code
remember (bool): Remember authentication token
"""
def signout(self):
"""Sign out of Plex account and invalidate tokens."""
def claimToken(self):
"""
Generate claim token for server setup.
Returns:
str: Claim token for new server registration
"""
def createToken(self):
"""
Create new authentication token.
Returns:
str: New authentication token
"""Access Plex servers and resources associated with your account.
class MyPlexAccount:
def resources(self):
"""
Get available Plex servers and resources.
Returns:
list: List of MyPlexResource objects
"""
def resource(self, name):
"""
Get specific server resource by name.
Args:
name (str): Server name to find
Returns:
MyPlexResource: Server resource object
Raises:
NotFound: If server with specified name is not found
"""
def devices(self):
"""
Get registered devices.
Returns:
list: List of MyPlexDevice objects
"""
def device(self, name=None, clientId=None):
"""
Get specific device.
Args:
name (str, optional): Device name
clientId (str, optional): Device client ID
Returns:
MyPlexDevice: Device object
"""
class MyPlexResource:
"""Plex server resource accessible through MyPlex."""
@property
def name(self):
"""str: Server name."""
@property
def product(self):
"""str: Server product type."""
@property
def owned(self):
"""bool: Whether you own this server."""
def connect(self, ssl=None, timeout=None):
"""
Connect to this server resource.
Args:
ssl (bool, optional): Force SSL connection
timeout (int, optional): Connection timeout
Returns:
PlexServer: Connected server instance
"""
class MyPlexDevice:
"""Registered Plex device."""
@property
def name(self):
"""str: Device name."""
@property
def product(self):
"""str: Device product type."""
@property
def clientIdentifier(self):
"""str: Unique device identifier."""Manage home users, friends, and sharing permissions.
class MyPlexAccount:
def users(self):
"""
Get managed users and friends.
Returns:
list: List of MyPlexUser objects
"""
def user(self, username):
"""
Get specific user by username.
Args:
username (str): Username to find
Returns:
MyPlexUser: User object
"""
def createHomeUser(self, user, server, sections=None, allowSync=None, allowCameraUpload=None, allowChannelContent=None, **kwargs):
"""
Create managed home user.
Args:
user (str): Username for new managed user
server (PlexServer): Server to grant access to
sections (list, optional): Library sections to share
allowSync (bool, optional): Allow mobile sync
allowCameraUpload (bool, optional): Allow camera uploads
allowChannelContent (bool, optional): Allow channel content
**kwargs: Additional user settings
Returns:
MyPlexUser: Created user object
"""
def inviteFriend(self, user, server, sections=None, allowSync=None, allowCameraUpload=None, allowChannelContent=None, **kwargs):
"""
Invite friend to share server.
Args:
user (str): Email address to invite
server (PlexServer): Server to share
sections (list, optional): Library sections to share
allowSync (bool, optional): Allow mobile sync
allowCameraUpload (bool, optional): Allow camera uploads
allowChannelContent (bool, optional): Allow channel content
**kwargs: Additional sharing settings
Returns:
MyPlexInvite: Created invitation object
"""
def removeFriend(self, user):
"""
Remove friend access.
Args:
user (str or MyPlexUser): User to remove
"""
def removeHomeUser(self, user):
"""
Remove managed home user.
Args:
user (str or MyPlexUser): User to remove
"""
def switchHomeUser(self, user, pin=None):
"""
Switch to managed home user context.
Args:
user (str or MyPlexUser): User to switch to
pin (str, optional): User PIN if required
Returns:
MyPlexAccount: Account context for the managed user
"""
class MyPlexUser:
"""Plex user account (friend or managed user)."""
@property
def title(self):
"""str: User display name."""
@property
def username(self):
"""str: Username."""
@property
def email(self):
"""str: Email address."""
@property
def friend(self):
"""bool: Whether this is a friend (vs managed user)."""
@property
def home(self):
"""bool: Whether this is a home user."""
class MyPlexInvite:
"""User invitation for server sharing."""
@property
def email(self):
"""str: Invited email address."""
@property
def createdAt(self):
"""datetime: When invitation was sent."""
def delete(self):
"""Cancel this invitation."""Manage personal watchlist across all Plex services.
class MyPlexAccount:
def watchlist(self, filter=None, sort=None, libtype=None, **kwargs):
"""
Get user watchlist items.
Args:
filter (str, optional): Filter criteria
sort (str, optional): Sort order
libtype (str, optional): Media type filter ('movie', 'show')
**kwargs: Additional filter parameters
Returns:
list: List of watchlist media objects
"""
def addToWatchlist(self, items):
"""
Add items to watchlist.
Args:
items (list or single item): Media items to add
"""
def removeFromWatchlist(self, items):
"""
Remove items from watchlist.
Args:
items (list or single item): Media items to remove
"""
def onWatchlist(self, item):
"""
Check if item is on watchlist.
Args:
item: Media item to check
Returns:
bool: True if item is on watchlist
"""Discover new content through Plex's recommendation engine.
class MyPlexAccount:
def searchDiscover(self, query, limit=30, libtype=None, **kwargs):
"""
Search Plex content discovery.
Args:
query (str): Search query
limit (int): Maximum results to return
libtype (str, optional): Media type ('movie', 'show', 'artist')
**kwargs: Additional search parameters
Returns:
list: List of discovered content items
"""Access mobile sync items and account playback history.
class MyPlexAccount:
def syncItems(self, client=None, clientId=None):
"""
Get items available for mobile sync.
Args:
client (str, optional): Client name filter
clientId (str, optional): Client ID filter
Returns:
list: List of SyncItem objects
"""
def history(self, maxresults=None, mindate=None):
"""
Get account playback history.
Args:
maxresults (int, optional): Maximum results to return
mindate (datetime, optional): Earliest date to include
Returns:
list: List of historical playback records
"""
def viewStateSync(self):
"""
Get view state synchronization status.
Returns:
dict: Sync status information
"""Handle PIN-based authentication for device registration.
class MyPlexPinLogin:
"""PIN-based authentication for device registration."""
def __init__(self, oauth=False):
"""
Create PIN login flow.
Args:
oauth (bool): Use OAuth flow vs PIN flow
"""
@property
def pin(self):
"""str: Generated PIN for user entry."""
@property
def authenticated(self):
"""bool: Whether PIN has been authenticated."""
def checkLogin(self, timeout=60):
"""
Check if PIN has been authenticated.
Args:
timeout (int): Maximum time to wait for authentication
Returns:
MyPlexAccount: Authenticated account if successful
"""from plexapi.myplex import MyPlexAccount
# Username/password authentication
account = MyPlexAccount('your-username', 'your-password')
# Token authentication
account = MyPlexAccount(token='your-auth-token')
# Two-factor authentication
account = MyPlexAccount('username', 'password', code='123456')# Get available servers
resources = account.resources()
for resource in resources:
print(f"Server: {resource.name} ({'owned' if resource.owned else 'shared'})")
# Connect to specific server
plex = account.resource('My Plex Server').connect()
# Alternative connection with options
plex = account.resource('My Plex Server').connect(ssl=True, timeout=30)# Get current users
users = account.users()
for user in users:
user_type = "Home" if user.home else "Friend"
print(f"{user_type} User: {user.title} ({user.email})")
# Create managed home user
home_server = account.resource('Home Server').connect()
movie_section = home_server.library.section('Movies')
tv_section = home_server.library.section('TV Shows')
new_user = account.createHomeUser(
user='kid_username',
server=home_server,
sections=[movie_section, tv_section],
allowSync=True,
allowCameraUpload=False
)
# Invite friend
invitation = account.inviteFriend(
user='friend@example.com',
server=home_server,
sections=[movie_section],
allowSync=False
)
# Switch to managed user
kid_account = account.switchHomeUser('kid_username', pin='1234')# Get watchlist
watchlist = account.watchlist()
print(f"Watchlist has {len(watchlist)} items")
# Filter watchlist
movies = account.watchlist(libtype='movie')
shows = account.watchlist(libtype='show')
# Add to watchlist (requires media objects from discovery or shared servers)
discovered = account.searchDiscover('spider-man', libtype='movie')
if discovered:
account.addToWatchlist(discovered[0])
# Check if item is on watchlist
movie = plex.library.section('Movies').get('The Matrix')
if account.onWatchlist(movie):
print("Movie is on watchlist")# Search for content to discover
results = account.searchDiscover('star wars', limit=10)
for item in results:
print(f"Discovered: {item.title} ({item.year})")
# Search by type
movies = account.searchDiscover('action', libtype='movie', limit=20)
shows = account.searchDiscover('comedy', libtype='show', limit=15)# Get registered devices
devices = account.devices()
for device in devices:
print(f"Device: {device.name} ({device.product})")
# Get specific device
phone = account.device(name='iPhone')
if phone:
print(f"Found device: {phone.clientIdentifier}")import datetime
# Get recent history
history = account.history(maxresults=50)
for entry in history:
print(f"Watched: {entry.title} on {entry.viewedAt}")
# Get history since specific date
week_ago = datetime.datetime.now() - datetime.timedelta(days=7)
recent = account.history(mindate=week_ago)# Get sync items
sync_items = account.syncItems()
for item in sync_items:
print(f"Sync available: {item.title}")
# Get sync items for specific client
mobile_sync = account.syncItems(client='iPhone')from plexapi.myplex import MyPlexPinLogin
# Create PIN login
pin_login = MyPlexPinLogin()
print(f"Go to plex.tv/link and enter PIN: {pin_login.pin}")
# Wait for authentication
try:
account = pin_login.checkLogin(timeout=120) # Wait up to 2 minutes
print("Successfully authenticated!")
except Exception as e:
print(f"Authentication failed: {e}")# Create user with detailed permissions
detailed_user = account.createHomeUser(
user='teenager',
server=home_server,
sections=[movie_section, tv_section, music_section],
allowSync=True,
allowCameraUpload=True,
allowChannelContent=False,
filterMovies='PG-13', # Content rating filter
filterTelevision='TV-14'
)
# Update sharing for existing friend
friend = account.user('friend@example.com')
# Note: Specific permission updates require server-level operationsfrom plexapi.exceptions import BadRequest, Unauthorized, TwoFactorRequired
try:
account = MyPlexAccount('username', 'password')
except TwoFactorRequired:
# Handle two-factor authentication
code = input("Enter 2FA code: ")
account = MyPlexAccount('username', 'password', code=code)
except Unauthorized:
print("Invalid credentials")
except BadRequest as e:
print(f"Request error: {e}")