Skip to content

Instantly share code, notes, and snippets.

@Secret-Rabbit
Last active January 6, 2026 22:14
Show Gist options
  • Select an option

  • Save Secret-Rabbit/c1362b56d48abe566e56ab377a9bd571 to your computer and use it in GitHub Desktop.

Select an option

Save Secret-Rabbit/c1362b56d48abe566e56ab377a9bd571 to your computer and use it in GitHub Desktop.
When you first run the script, if there are already players on the server, the message that "sleep is blocked" is now displayed
# Prevents the PC with the Minecraft server from falling asleep if there are players on the server
# Не даёт ПК с сервером Minecraft уснуть, если на сервере есть игроки
# Working conditions | Условия работы
# 1. server.properties: enable-query=true
# 2. Dependenciesm | Зависимости: pip install mcstatus
import time
import platform
import subprocess
import ctypes
from mcstatus import JavaServer
SERVER = "127.0.0.1:25565"
CHECK_INTERVAL = 30 # секунд | seconds
# ------------------------------
# Красивый формат даты и времени
# ------------------------------
def cdt():
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%d.%m.%Y %H:%M:%S")
return formatted
# ------------------------------
# Механизм удержания сна
# ------------------------------
class SleepBlocker:
def __init__(self):
self.proc = None
self.os = platform.system()
def block(self):
if self.os == "Windows":
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
elif self.os == "Linux":
if self.proc is None:
self.proc = subprocess.Popen(
[
"systemd-inhibit",
"--why=MC server active",
"--mode=block",
"sleep",
"999999",
]
)
elif self.os == "Darwin":
if self.proc is None:
self.proc = subprocess.Popen(["caffeinate"])
def unblock(self):
if self.os == "Windows":
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
else:
if self.proc:
self.proc.terminate()
self.proc = None
# ------------------------------
# Основной цикл
# ------------------------------
def main():
server = JavaServer.lookup(SERVER)
blocker = SleepBlocker()
sleep_is_allowed = True # Изначально считаем, что сон разрешён
first_check = True # Флаг первого опроса
print(f"Мониторинг Minecraft Query на {SERVER}")
while True:
try:
status = server.query()
players = status.players.online
except Exception:
players = 0 # сервер недоступен → считаем, что игроков нет
if players > 0:
if sleep_is_allowed or first_check:
print(f"{cdt()} Игроков: {players} — сон заблокирован.")
blocker.block()
sleep_is_allowed = False
else:
if not sleep_is_allowed or first_check:
print(f"{cdt()} Игроков нет — сон разрешён.")
blocker.unblock()
sleep_is_allowed = True
first_check = False # После первого цикла флаг сбрасывается
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment