Last active 1670065441

A script to report what people are watching on your Plex server

plexnp.py Raw
1from plexapi.server import PlexServer
2import sys
3plex = PlexServer("http://172.16.17.10:32400")
4now_playing = plex.query("/status/sessions")
5if not now_playing:
6 print("Nobody's watching anything")
7 sys.exit(0)
8sessions = []
9def hms(mil):
10 s,mil = divmod(int(mil), 1000)
11 m,s = divmod(s, 60)
12 h,m = divmod(m, 60)
13 return h,m,s,mil
14for item in now_playing:
15 data = {
16 "title": item.attrib["title"],
17 "user": item.find(".//User").attrib["title"],
18 "product": ("on a " + item.find(".//Player").attrib["device"]) if
19 item.find(".//Session").attrib["location"] == "cellular" else
20 ("using " + item.find(".//Player").attrib["product"]),
21 "offset": "{}:{:02d}:{:02d}.{:03d}".format(*hms(item.attrib["viewOffset"]))
22 }
23 if item.tag == "Track":
24 data.update({"artist": item.attrib["grandparentTitle"]})
25 sessions.append("{user} is listening to {title} by {artist} {product} ({offset})".format(**data))
26 elif item.tag == "Video":
27 data.update({"year": item.attrib["year"]})
28 if "grandparentTitle" in item.attrib:
29 data.update({"show": item.attrib["grandparentTitle"]})
30 sessions.append("{user} is watching {show}: {title} {product} ({offset})".format(**data))
31 else:
32 sessions.append("{user} is watching {title} ({year}) {product} ({offset})".format(**data))
33 else:
34 continue
35if len(sessions) > 2:
36 print(", ".join(sessions[:-1]) + ", and " + sessions[-1])
37else:
38 print(", and ".join(sessions))