import os import signal import subprocess import sys import time from datetime import datetime BOT_DIR = os.path.expanduser("~/BotDC") GIT_TIMEOUT = 30 BOT_TIMEOUT = 10 def log(msg): print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}", flush=True) def run(cmd, timeout=GIT_TIMEOUT, **kwargs): try: return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout, **kwargs) except subprocess.TimeoutExpired: log(f"Timeout: {cmd}") return None def read_local_version(): try: with open("au.version", "r") as f: return f.readline().strip() except FileNotFoundError: return "0" def read_remote_version(): result = run("git show origin/main:au.version") if result and result.returncode == 0: lines = result.stdout.strip().splitlines() return lines[0] if lines else "0" return "0" def ensure_bot(): result = run("screen -ls") if result is None or result.returncode != 0 or "bot" not in result.stdout: log("Bot nie dziala, uruchamiam...") return subprocess.Popen(["python", "bot.py"], cwd=BOT_DIR) return None def main(): os.chdir(BOT_DIR) bot_proc = None def cleanup(sig=None, frame=None): log("Zatrzymywanie...") if bot_proc and bot_proc.poll() is None: bot_proc.terminate() try: bot_proc.wait(timeout=BOT_TIMEOUT) except subprocess.TimeoutExpired: bot_proc.kill() sys.exit(0) signal.signal(signal.SIGINT, cleanup) signal.signal(signal.SIGTERM, cleanup) local_ver = read_local_version() log(f"Start updatera, aktualna wersja: {local_ver}") log("Bot uruchomiony") bot_proc = subprocess.Popen(["python", "bot.py"], cwd=BOT_DIR) while True: time.sleep(30) result = run("git fetch origin main") if result is None: continue remote_ver = read_remote_version() if remote_ver != local_ver: log(f"Nowa wersja: {local_ver} -> {remote_ver}") run("git pull origin main") au_content = "" try: with open("au.version", "r") as f: au_content = f.read() except FileNotFoundError: pass if "install-packages=true" in au_content: log("Instaluje pakiety...") run("pip install -r requirements.txt", timeout=120) local_ver = read_local_version() log("Restartuje bota po aktualizacji...") if bot_proc and bot_proc.poll() is None: bot_proc.kill() try: bot_proc.wait(timeout=5) except: pass bot_proc = subprocess.Popen(["python", "bot.py"], cwd=BOT_DIR) if bot_proc.poll() is not None: new_proc = ensure_bot() if new_proc: bot_proc = new_proc if __name__ == "__main__": main()