From 16032df9b5ae3ae288c1efbc77f09b3cfc6e79db Mon Sep 17 00:00:00 2001 From: grayhook Date: Sat, 3 May 2025 16:26:53 +0700 Subject: [PATCH] Init --- Makefile | 2 ++ main.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 Makefile create mode 100644 main.py diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..02e40e3 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +run: + bash -c 'nohup python3 main.py >nohup.out 2>&1 & disown' diff --git a/main.py b/main.py new file mode 100644 index 0000000..0587141 --- /dev/null +++ b/main.py @@ -0,0 +1,61 @@ +import os +import sys +import socket +import time +import subprocess + +CHECK_USERS_CMD = ["/root/mcrcon/mcrcon", "-H", "192.168.0.21", "-p", "password", "list"] +CHECK_INTERVAL = 60 +WASTED_LIMIT = 20 * 60 + +def are_users_there(): + try: + output = subprocess.check_output(CHECK_USERS_CMD) + # Maybe, server isn't running? + except subprocess.CalledProcessError as err: + print(f"Cannot access mcrcon: {err}", flush=True) + return True + header = output.decode().split("\n")[0] + if header.startswith("There are 0 of"): + return False + return True + +def server_shutdown(): + subprocess.run("service minecraft stop".split(" ")) + +def server_startup(): + subprocess.run("service minecraft start".split(" ")) + +def main(): + wasted_cnt_seconds = 0 + while True: + if are_users_there(): + wasted_cnt_seconds = 0 + print("Users ok", flush=True) + time.sleep(CHECK_INTERVAL) + continue + + wasted_cnt_seconds += CHECK_INTERVAL + print(f"No users ({wasted_cnt_seconds})", flush=True) + if wasted_cnt_seconds > WASTED_LIMIT: + print("Wasted limit", flush=True) + server_shutdown() + wait_client() + server_startup() + print("Server started", flush=True) + wasted_cnt_seconds = 0 + + time.sleep(CHECK_INTERVAL) + +def wait_client(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(("0.0.0.0", 25565)) + print("Listening...", flush=True) + sock.listen(0) + connection, address = sock.accept() + print(f"Connection from: {address}", flush=True) + connection.close() + sock.close() + +if __name__ == '__main__': + main()