import os import logging import time from datetime import datetime from flask import Flask, request, jsonify #from win10toast import ToastNotifier #import asyncio import subprocess import signal import psutil import telegram from telegram import Update from telegram.ext import Updater, CommandHandler, CallbackContext, MessageHandler, filters import telegram.error logging.basicConfig(filename='osiris_listener.log', level=logging.DEBUG, format='%(asctime)s %(message)s') app = Flask(__name__) #toaster = ToastNotifier() #### # Constants #### java_minecraft_servers = { "mc_vanilla" : { 'profile_id': 'vanilla', 'server_name': 'Vanilla 1.21', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/' }, "mc_sanderpack" : { 'profile_id': 'sanderpack', 'server_name': 'The 1.12.2 Pack (SanderPack)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/' }, "mc_sanderhorizons" : { 'profile_id': 'sanderhorizons', 'server_name': 'GT New Horizons 2.6.0 (SanderHorizons)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/gt_new_horizons_2.6.0/' }, "mc_sanderhardcore" : { 'profile_id': 'sanderhardcore', 'server_name': 'RLCraft 2.9.3 (SanderHardcore)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/' }, "mc_sandervalley" : { 'profile_id': 'sandervalley', 'server_name': 'Farming Valley (SanderValley)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/farming_valley_1-1-2/' } } #### # Tool Functions #### def read_pid_file(pid_file): """Read the PID from the specified PID file.""" try: with open(pid_file, 'r') as file: pid = int(file.read().strip()) return pid except (FileNotFoundError, ValueError): return None def is_java_process(pid): try: p = psutil.Process(pid) return 'java' in p.name().lower() except psutil.NoSuchProcess: return False #### # Flask Functions #### @app.route('/osiris_execute', methods=['POST']) def execute_script(): logging.info("Commando zur Ausführung erhalten.") data = request.get_json() command = data.get('command') if not command: logging.error("No command provided in request.") return jsonify({'error': 'No command provided'}), 400 logging.debug(f"Commando: {command}") # Hier neue Commands zur Prüfung einpflegen clean_command = command.strip() match clean_command: case 'testcommand': try: #toaster.show_toast("TestCommand", "Verbindung wurde getestet", d)uration=10) #asyncio.run(send_telegram_message("Test command executed.")) return jsonify({'message': 'Test Command abgesetzt und Notification auf bei Host erstellt.'}) except Exception as exc: logging.error(f"Error executing test command: {exc}") #asyncio.run(send_telegram_message(f"Error executing test command: {e}")) return jsonify({'message': f'Error: {str(exc)}'}), 500 case 'shutdown': logging.info("Received request to shutdown.") try: #toaster.show_toast("Shutdown", "Shutdown Command erhalten. Host wird heruntergefahren.", duration=10) os.system("shutdown /s /t 1") #asyncio.run(send_telegram_message("Ich schlafe dann weiter. Bis demnächst :-)")) return jsonify({'message': 'Shutdown command wurde ausgeführt. System fährt herunter.'}) except Exception as e: logging.error(f"Error executing shutdown command: {exc}") #asyncio.run(send_telegram_message(f"Error executing shutdown command: {e}")) return jsonify({"message": "Fehler beim veranlassen des Shutdowns", 'error': str(e)}), 500 @app.route('/status_nuc', methods=['GET']) def status(): logging.info("Status check received.") # Get CPU and RAM usage cpu_usage = psutil.cpu_percent(interval=1) ram_usage = psutil.virtual_memory().percent status = { "cpu": cpu_usage, "ram": ram_usage } return jsonify({'message': f'status = online | CPU = {cpu_usage} | RAM = {ram_usage}'}) @app.route('/status_servers', methods=['GET']) def status_gameservers(): logging.info("Check Status der Server") response_msg = "Status Game Server:" for profile in java_minecraft_servers.keys(): server = java_minecraft_servers[profile] pid_file = os.path.join(server['directory'], 'server.pid') if os.path.exists(pid_file): with open(pid_file, 'r') as file: pid = int(file.read().strip()) if psutil.pid_exists(pid) and is_java_process(pid): response_msg += f"\nServer {server['server_name']} läuft mit PID {pid}." else: response_msg += f"\nServer {server['server_name']} läuft nicht." else: response_msg += f"\nKein PID file für Server {server['server_name']} gefunden." return jsonify({"message": response_msg }) if __name__ == '__main__': #toaster.show_toast("Starte Osiris", "Osiris Listener wurde gestartet. Warte auf Befehle...", duration=30) logging.info("Starte Server.") #asyncio.run(send_telegram_message(f"Nuc_Morroc hier. Bin jetzt wach ;-)")) app.run(host='0.0.0.0', port=9713)