Last active
December 23, 2020 03:55
-
-
Save Techno-coder/ef3346a37641170a2974641aa28e878f to your computer and use it in GitHub Desktop.
Apple Music Discord Rich Presence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/opt/[email protected]/bin/python3.8 | |
import objc | |
import time | |
from Foundation import * | |
from PyObjCTools import AppHelper | |
from pypresence import Presence | |
# References image assets | |
client_id = "511368737199357972" | |
class SongRegister(object): | |
def __init__(self): | |
self.client = Presence(client_id) | |
self.client.connect() | |
print("Connected to Discord"); | |
self.client.update(state="Waiting for song change") | |
self.currentSong = None | |
self.resumeTimestamp = 0 | |
self.timeRemaining = 0 | |
self.isPaused = False | |
# For future reference, underscores in the method name correspond to colons in | |
# pyobjc so the selector needs to be explicitly named | |
selector = objc.selector(self.on_song_change_, selector="on_song_change:".encode()) | |
notifications = Foundation.NSDistributedNotificationCenter.defaultCenter() | |
notifications.addObserver_selector_name_object_(self, selector, 'com.apple.Music.playerInfo', None) | |
# Method name ends in underscore to act as selector | |
def on_song_change_(self, song): | |
song = song.userInfo() | |
if "Name" not in song: | |
self.client.clear() | |
return | |
uniqueSongIdentifier = song["PersistentID"] | |
totalTime = song["Total Time"] / 1000; | |
hasReset = (not self.isPaused) and song["Player State"] == "Playing" | |
if self.currentSong != uniqueSongIdentifier or hasReset: | |
self.currentSong = uniqueSongIdentifier | |
self.timeRemaining = totalTime | |
if song["Player State"] == "Playing": | |
self.resumeTimestamp = time.time() | |
self.isPaused = False | |
else: | |
self.timeRemaining -= time.time() - self.resumeTimestamp | |
self.isPaused = True | |
songState = "{}".format(song["Name"][:128]) | |
songDetails = "{}".format(song.get("Artist", "Unknown Artist")[:128]) | |
icon = "icon" | |
songEnd = None | |
smallIcon = None | |
if song["Player State"] == "Playing": | |
songEnd = int(self.resumeTimestamp + self.timeRemaining) | |
smallIcon = "play" | |
else: | |
smallIcon = "pause" | |
self.client.update(state=songState, details=songDetails, end=songEnd, | |
large_image=icon, large_text="Rich Presence built by Technocoder", | |
small_image=smallIcon); | |
register = SongRegister() | |
AppHelper.runConsoleEventLoop() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment