-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.py
69 lines (60 loc) · 2.43 KB
/
rpc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from chillhop import live
from pypresence import Presence, DiscordNotFound
from datetime import datetime
import time
index = int(input("""Which stream?
[1] Chillhop Radio
[2] lofi hip hop radio
> """))
ch = live(stream_index=index-1) # since Python list indices start at 0
def time_fmt(num): # the "naive" way
mins = int(num // 60)
secs = int(num % 60)
if secs < 10:
secs = "0" + str(secs) # leading 0 (there's probably a better way)
return f"{str(mins)}:{str(secs)}"
try:
rpc = Presence(ch.streams[ch.stream_index]['appid'])
rpc.connect()
except DiscordNotFound:
print("[warning] Discord not found, disabling rich presence functions.")
rpc_enabled = False
else: rpc_enabled = True
while True:
track = ch.get_track_info() # fetch current track info (returns dict)
time_str = str(int(time.time()))
last_play = datetime.strptime(track['last_play'], '%Y-%m-%d %H:%M:%S').timestamp()
duration = int(track['duration']) / 1000
duration_str = time_fmt(duration)
next_track_time = last_play + duration # converting from ms
if rpc_enabled == True:
# viewers = ch.get_current_views() # BUG: see chillhop.py, line 69 - something with YT or Chillhop's API broke
track_url = f'https://chillhop.com/?p={track["post_id"]}'
rpc.update(
details=f"{track['title']} ({duration_str})",
state=track["artists"],
large_image="radio_1",
# large_text=f"{viewers} viewers",
buttons=[
{"label": "View release", "url": track_url},
{"label": "View artist", "url": f'{track_url}&type=artists'} # well that's convenient!
],
start=time_str
)
else:
pass
timestamp_now = datetime.now().strftime('%H:%M:%S') # get the system timestamp
sleep_duration = (next_track_time - datetime.utcnow().timestamp()) # avoid excessively spamming Discord and Chillhop's APIs :)
try: # text formatting
first_run
except NameError:
first_run = True
duration_str = f"~{time_fmt(sleep_duration)} left" # probably imprecise
if sleep_duration >= 0: print(f"[{timestamp_now}] Now playing on {ch.streams[ch.stream_index]['name']} - {track['title']} by {track['artists']} ({duration_str})")
while True:
try:
time.sleep(sleep_duration)
break
except ValueError:
time.sleep(1) # try again until it works lol
break