-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
67 lines (53 loc) · 2.01 KB
/
classes.py
File metadata and controls
67 lines (53 loc) · 2.01 KB
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
import requests
import threading
import time
import json
class MinecraftServerStatus:
def __init__(self, server_name: str, update_interval: float=10):
self.server_name: str = server_name
self.api_url: str = f"https://api.mcsrvstat.us/2/{self.server_name}"
self.update_interval = update_interval
self.data: json = None
self._online: bool = False
self._players: int = 0
self._max_players = 0
self.lock = threading.Lock()
t = threading.Thread(target=self._update_loop, daemon=True)
t.start()
def _update_loop(self):
while True:
self.update_status()
time.sleep(self.update_interval)
def update_status(self) -> None:
try:
response = requests.get(self.api_url, timeout=5)
response.raise_for_status()
data: json = response.json()
with self.lock:
self.data: json = data
self._update_online_status()
self._players = data.get("players", dict).get("online", int) if self._online else 0
self._max_players = data.get("players", dict).get("max", int) if self._online else 0
except requests.RequestException as e:
with self.lock:
self._online = False
self._players = 0
def _update_online_status(self) -> None:
motd_clean = self.data.get("motd", dict).get("clean", str or list)
if isinstance(motd_clean, list):
motd_text = " ".join(motd_clean)
elif isinstance(motd_clean, str):
motd_text = motd_clean
else:
motd_text = ""
self._online = not "offline" in motd_text.lower()
return self._online
def is_online(self) -> bool:
with self.lock:
return self._online
def current_players(self) -> int:
with self.lock:
return self._players
def max_players(self) -> int:
with self.lock:
return self._max_players