diff --git a/osiris_listener.py b/osiris_listener.py index 6601c65..ae04a3d 100644 --- a/osiris_listener.py +++ b/osiris_listener.py @@ -23,33 +23,43 @@ app = Flask(__name__) # Constants #### -# Define the scripts and their parameters -java_minecraft_servers = [ - { +java_minecraft_servers = { + "mc_vanilla" : { + 'profile_id': 'vanilla', 'server_name': 'Vanilla 1.21', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/', 'command': ['C:/Program Files/Java/jdk-22/bin/java.exe', '-Xmx1024M', '-Xms1024M', '-jar', 'minecraft_server.1.21.jar', '--nogui', '--bonusChest'], 'wait_time': 30 }, - { + "mc_sanderpack" : { + 'profile_id': 'sanderpack', 'server_name': 'The 1.12.2 Pack (SanderPack)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/', 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-XX:+UseG1GC','-Xms4G', '-Dsun.rmi.dgc.server.gcInterval=2147483646', '-XX:+UnlockExperimentalVMOptions', '-XX:G1NewSizePercent=20', '-XX:G1ReservePercent=20', '-XX:MaxGCPauseMillis=50', '-XX:G1HeapRegionSize=32M', '-Dfml.queryResult=confirm', '-Duser.language=en', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'], 'wait_time': 30 }, - { + "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/', 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx12G', '-Xms4G', '-XX:+UseStringDeduplication', '-XX:+UseCompressedOops', '-XX:+UseCodeCacheFlushing', '-Dfml.readTimeout=180', '-jar', 'forge-1.7.10-10.13.4.1614-1.7.10-universal.jar', '--nogui', '--bonusChest'], 'wait_time': 30 }, - { + "mc_sanderhardcore" : { + 'profile_id': 'sanderhardcore', 'server_name': 'RLCraft 2.9.3 (SanderHardcore)', 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/', 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-Xms4G', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'], 'wait_time': 30 - } -] + }, + "mc_sandervalley" : { + 'profile_id': 'sandervalley', + 'server_name': 'Farming Valley (SanderValley)', + 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/farming_valley_1-1-2/', + 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Dlog4j2.formatMsgNoLookups=true', '-Dlog4j.configurationFile=log4j2.xml', '-Xmx8G', '-Xms2G', '-jar', 'forge-1.10.2-12.18.3.2511-universal.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + } +} #### # Telegramm Functions @@ -140,151 +150,26 @@ def execute_script(): #asyncio.run(send_telegram_message(f"Error executing shutdown command: {e}")) return jsonify({"message": "Fehler beim veranlassen des Shutdowns", 'error': str(e)}), 500 - case 'start_gameservers_minecraft': - logging.info("Received request to start minecraft servers.") - #toaster.show_toast("start_gameservers_minecraft", "Starte Minecraft-Server", duration=10) - response_msg = "Folgende Minecraft-Server wurden bearbeitet:" - for server in java_minecraft_servers: - os.chdir(server['directory']) - pid_file = os.path.join(server['directory'], 'server.pid') - log_file = os.path.join(server['directory'], 'logs', f'server_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log') - #wait_time = server['wait_time'] - - # Create logs directory if it doesn't exist - os.makedirs(os.path.dirname(log_file), exist_ok=True) - - 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 bereits." - continue - else: - os.remove(pid_file) - - #response_msg += f"Server {server['server_name']} wird gestartet." - with open(log_file, 'w') as log: - process = subprocess.Popen( - server['command'], - cwd=server['directory'], - stdout=log, - stderr=log, - creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0 - ) - #time.sleep(wait_time) - with open(pid_file, 'w') as file: - file.write(str(process.pid)) - response_msg += f"\nServer {server['server_name']} wurde mit PID '{process.pid}' gestartet." - return jsonify({"message": f"{response_msg}"}) - #return jsonify({'message': 'Minecraft-Server werden gestartet.'}) - - case 'stop_gameservers_minecraft': - logging.info("Received request to stop minecraft servers.") - response_msg = "Folgende Minecraft-Server wurden bearbeitet:" - for server in java_minecraft_servers: - pid_file = os.path.join(server['directory'], 'server.pid') - wait_time = server['wait_time'] - flag_delete_pid = False - 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): - p = psutil.Process(pid) - if os.name == 'nt': - p.terminate() # Use terminate for Windows - else: - p.send_signal(signal.SIGTERM) - try: - p.wait(timeout=wait_time) - if not psutil.pid_exists(pid): - flag_delete_pid = True - response_msg += f"\nServer {server['server_name']} mit PID {pid} gestoppt." - else: - response_msg += f"\nFehler beim Stoppen des Servers {server['server_name']} mit PID {pid}." - except psutil.TimeoutExpired: - response_msg += f"Timeout während stoppen des Server {server['server_name']} mit PID {pid}." - else: - flag_delete_pid = True - response_msg += f"Stale PID file von Server {server['server_name']} entfernt." - if flag_delete_pid: - os.remove(pid_file) - response_msg += f"PID File gelöscht" - flag_delete_pid = False - else: - response_msg += f"Es existiert kein PID File für Server {server['server_name']}" - #asyncio.run(send_telegram_message("Minecraft-Server wurden heruntergefahren.")) - return jsonify({'message': response_msg}) - case 'start_gameservers_dontstarve': - try: - #toaster.show_toast("start_gameservers_dontstarve", "Starte Dont Starve Together-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'Dont Starve Together-Server werden gestartet.'}) - except Exception as exc: - logging.error(f"Error executing start_gameservers_dontstarve command: {exc}") - return jsonify({'error': str(exc)}), 500 - case 'stop_gameservers_dontstarve': - try: - #toaster.show_toast("stop_gameservers_dontstarve", "Stoppe Dont Starve Together-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'Dont Starve Together-Server wurden angehalten.'}) - except Exception as exc: - logging.error(f"Error executing stop_gameservers_dontstarve command: {exc}") - return jsonify({'error': str(exc)}), 500 - case 'start_gameservers_ragnarokonline': - try: - #toaster.show_toast("start_gameservers_ragnarokonline", "Starte RO-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'RO-Server werden gestartet.'}) - except Exception as exc: - logging.error(f"Error executing start_gameservers_ragnarokonline command: {exc}") - return jsonify({'error': str(exc)}), 500 - case 'stop_gameservers_ragnarokonline': - try: - #toaster.show_toast("stop_gameservers_ragnarokonline", "Stoppe RO-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'RO-Server wurden angehalten.'}) - except Exception as exc: - logging.error(f"Error executing stop_gameservers_ragnarokonline command: {exc}") - return jsonify({'error': str(exc)}), 500 - case 'start_gameservers_wow': - try: - #toaster.show_toast("start_gameservers_wow", "Starte WoW-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'WoW-Server werden gestartet.'}) - except Exception as exc: - logging.error(f"Error executing start_gameservers_wow command: {exc}") - return jsonify({'error': str(exc)}), 500 - case 'stop_gameservers_wow': - try: - #toaster.show_toast("stop_gameservers_wow", "Stoppe WoW-Server", duration=10) - # hier pgm aufrufen - return jsonify({'message': 'WoW-Server wurden angehalten.'}) - except Exception as exc: - logging.error(f"Error executing stop_gameservers_wow command: {exc}") - return jsonify({'error': str(exc)}), 500 - - case _: - try: - result = subprocess.run(['python','-c', command], capture_output=True, text=True, shell=True) - #send_telegram_message(f"Script executed with output: {result.stdout}") - return jsonify({'output': result.stdout, 'error': result.stderr, 'returncode': result.returncode}) - except Exception as exc: - logging.error(f"Error executing command: {exc}") - #send_telegram_message(f"Error executing script: {e}") - return jsonify({'error': str(exc)}), 500 -@app.route('/status', methods=['GET']) +@app.route('/status_nuc', methods=['GET']) def status(): - logging.info("Status Check received.") - #asyncio.run(send_telegram_message(f"Bin da. Wer nohoch?")) - return jsonify({'message': 'status = online'}) + 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 server in java_minecraft_servers: + 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: @@ -295,7 +180,6 @@ def status_gameservers(): response_msg += f"\nServer {server['server_name']} läuft nicht." else: response_msg += f"\nKein PID file für Server {server['server_name']} gefunden." - #asyncio.run(send_telegram_message(f"Aktuell laufende Server: {server_list}")) return jsonify({"message": response_msg }) diff --git a/osiris_listener_telegram.py b/osiris_listener_telegram.py index 32777be..ae73643 100644 --- a/osiris_listener_telegram.py +++ b/osiris_listener_telegram.py @@ -3,6 +3,9 @@ import asyncio from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes import os +import psutil +from datetime import datetime +import subprocess logging.basicConfig(filename='osiris_telegram.log', level=logging.DEBUG, format='%(asctime)s %(message)s') @@ -16,6 +19,48 @@ PASSWORD = '29102021' # Dictionary to store timers timers = {} +#### +# GameServer Konstanten +#### +# Vorhandene Gameserver-Daten +java_minecraft_servers = { + "mc_vanilla" : { + 'profile_id': 'vanilla', + 'server_name': 'Vanilla 1.21', + 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/', + 'command': ['C:/Program Files/Java/jdk-22/bin/java.exe', '-Xmx1024M', '-Xms1024M', '-jar', 'minecraft_server.1.21.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + }, + "mc_sanderpack" : { + 'profile_id': 'sanderpack', + 'server_name': 'The 1.12.2 Pack (SanderPack)', + 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/', + 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-XX:+UseG1GC','-Xms4G', '-Dsun.rmi.dgc.server.gcInterval=2147483646', '-XX:+UnlockExperimentalVMOptions', '-XX:G1NewSizePercent=20', '-XX:G1ReservePercent=20', '-XX:MaxGCPauseMillis=50', '-XX:G1HeapRegionSize=32M', '-Dfml.queryResult=confirm', '-Duser.language=en', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + }, + "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/', + 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx12G', '-Xms4G', '-XX:+UseStringDeduplication', '-XX:+UseCompressedOops', '-XX:+UseCodeCacheFlushing', '-Dfml.readTimeout=180', '-jar', 'forge-1.7.10-10.13.4.1614-1.7.10-universal.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + }, + "mc_sanderhardcore" : { + 'profile_id': 'sanderhardcore', + 'server_name': 'RLCraft 2.9.3 (SanderHardcore)', + 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/', + 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-Xms4G', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + }, + "mc_sandervalley" : { + 'profile_id': 'sandervalley', + 'server_name': 'Farming Valley (SanderValley)', + 'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/farming_valley_1-1-2/', + 'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Dlog4j2.formatMsgNoLookups=true', '-Dlog4j.configurationFile=log4j2.xml', '-Xmx8G', '-Xms2G', '-jar', 'forge-1.10.2-12.18.3.2511-universal.jar', '--nogui', '--bonusChest'], + 'wait_time': 30 + } +} + #### # Nested Menu Bäume @@ -54,7 +99,7 @@ minecraft_menu = [ {"text": "The 1.12.2 Pack (SanderPack)", "callback_data": "minecraft_sanderpack"}, {"text": "GT New Horizons 2.6.0 (SanderHorizons)", "callback_data": "minecraft_sanderhorizon"}, {"text": "RLCraft 2.9.3 (SanderHardcore)", "callback_data": "minecraft_sanderhardcore"}, - {"text": "HarvestMoon (SanderMoon)", "callback_data": "minecraft_sandermoon"}, + {"text": "Farming Valley 1.1.2 (SanderValley)", "callback_data": "minecraft_sandervalley"}, {"text": "<- Zurück", "callback_data": "minecraft_back"} # Add neue Minecraft Commands here ] @@ -92,11 +137,19 @@ mc_sanderhardcore_menu = [ ] ] -mc_sandermoon_menu = [ +mc_sandervalley_menu = [ + [ + {"text": "Start", "callback_data": "mc_sandervalley_start"}, + {"text": "Stop", "callback_data": "mc_sandervalley_stop"}, + {"text": "<- Zurück", "callback_data": "mc_sandervalley_back"} + ] +] + +dont_starve_menu = [ [ - {"text": "Start", "callback_data": "mc_sandermoon_start"}, - {"text": "Stop", "callback_data": "mc_sandermoon_stop"}, - {"text": "<- Zurück", "callback_data": "mc_sandermoon_back"} + {"text": "Start", "callback_data": "dst_start"}, + {"text": "Stop", "callback_data": "dst_stop"}, + {"text": "<- Zurück", "callback_data": "dst_back"} ] ] @@ -132,6 +185,7 @@ async def timer(context: ContextTypes.DEFAULT_TYPE, chat_id: int): #### # User functions #### + def is_registered(user_id): if not os.path.exists(SUBSCRIBERS_FILE): return False @@ -158,13 +212,107 @@ async def verify_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> #### # Utils #### +def start_gameserver(profile: str) -> str: + response_msg = "" + if profile in java_minecraft_servers: + server = java_minecraft_servers[profile] + os.chdir(server['directory']) + pid_file = os.path.join(server['directory'], 'server.pid') + log_file = os.path.join(server['directory'], 'logs', f'server_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log') + #wait_time = server['wait_time'] + + # Create logs directory if it doesn't exist + os.makedirs(os.path.dirname(log_file), exist_ok=True) + + 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"Server {server['server_name']} läuft bereits." + return response_msg + else: + os.remove(pid_file) + + with open(log_file, 'w') as log: + process = subprocess.Popen( + server['command'], + cwd=server['directory'], + stdout=log, + stderr=log, + creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0 + ) + #time.sleep(wait_time) + with open(pid_file, 'w') as file: + file.write(str(process.pid)) + response_msg = f"Server {server['server_name']} wurde mit PID '{process.pid}' gestartet." + + else: + response_msg = f"Server Informationen für Profile {profile} existieren nicht. Bitte prüfen." + return response_msg + +def stop_gameserver(profile: str) -> str: + response_msg = "" + if profile not in java_minecraft_servers: + response_msg = f"Server Informationen für Profile {profile} existieren nicht. Bitte prüfen." + return response_msg + + server = java_minecraft_servers[profile] + pid_file = os.path.join(server['directory'], 'server.pid') + wait_time = server['wait_time'] + flag_delete_pid = False + 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): + p = psutil.Process(pid) + if os.name == 'nt': + p.terminate() # Use terminate for Windows + else: + p.send_signal(signal.SIGTERM) + try: + p.wait(timeout=wait_time) + if not psutil.pid_exists(pid): + flag_delete_pid = True + response_msg = f"Server {server['server_name']} mit PID {pid} gestoppt." + else: + response_msg = f"\nFehler beim Stoppen des Servers {server['server_name']} mit PID {pid}." + except psutil.TimeoutExpired: + response_msg = f"Timeout während stoppen des Server {server['server_name']} mit PID {pid}." + else: + flag_delete_pid = True + response_msg = f"Stale PID file von Server {server['server_name']} entfernt." + if flag_delete_pid: + os.remove(pid_file) + response_msg += " PID File gelöscht." + flag_delete_pid = False + else: + response_msg = f"Es existiert kein PID File für Server {server['server_name']}" + + return response_msg + +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 + # Function to send the main menu async def send_main_menu(context: ContextTypes.DEFAULT_TYPE, chat_id: int): - keyboard = [ - [InlineKeyboardButton("Option 1", callback_data='1')], - [InlineKeyboardButton("Option 2", callback_data='2')], - ] - reply_markup = InlineKeyboardMarkup(keyboard) + # keyboard = [ + # [InlineKeyboardButton("Option 1", callback_data='1')], + # [InlineKeyboardButton("Option 2", callback_data='2')], + # ] + reply_markup = InlineKeyboardMarkup(main_menu) await context.bot.send_message(chat_id=chat_id, text='Bitte wählen:', reply_markup=reply_markup) # Broadcast message function @@ -173,14 +321,13 @@ async def broadcast_message(application: Application, message: str): for chat_id in subscribers: try: await application.bot.send_message(chat_id=chat_id, text=message) + await application.bot.send_message(chat_id=chat_id, text='Bitte Themengebiet wählen:', reply_markup=InlineKeyboardMarkup(main_menu)) except Exception as e: logging.error(f"Failed to send message to {chat_id}: {e}") - async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: await update.message.reply_text('Use /start to test this bot.') - def read_subscribers(): if not os.path.exists(SUBSCRIBERS_FILE): return [] @@ -192,125 +339,198 @@ def save_subscriber(chat_id): with open(SUBSCRIBERS_FILE, 'a') as file: file.write(f"{chat_id}\n") +def get_status_nuc() -> dict: + 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 status + +def get_status_gameservers() -> str: + 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 response_msg + #### # Initialize Bot #### async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_id = update.message.chat_id if update.message else update.callback_query.message.chat_id - if is_registered(user_id): - keyboard = [ - [InlineKeyboardButton("Option 1", callback_data='1')], - [InlineKeyboardButton("Option 2", callback_data='2')], - ] - reply_markup = InlineKeyboardMarkup(keyboard) + if is_registered(user_id): + reply_markup = InlineKeyboardMarkup(main_menu) if update.message: - await update.message.reply_text('Bitte wählen:', reply_markup=reply_markup) + await update.message.reply_text('Bitte Themengebiet wählen:', reply_markup=reply_markup) elif update.callback_query: - await update.callback_query.message.reply_text('Bitte wählen:', reply_markup=reply_markup) + await update.callback_query.message.reply_text('Bitte Themengebiet wählen:', reply_markup=reply_markup) else: await update.message.reply_text('Bitte das Zugriffspassword eingeben.') +async def on_startup(application): + await broadcast_message(application,"Moin, Nuc Morroc hier. Bin jetzt wach!") #### # Command-Verarbeitung -#### - -""" -def handle_callback(update: Update, context: CallbackContext) -> None: +#### +async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query + await query.answer() + await start_timer(context, query.message.chat_id) data = query.data - match data: + match data: # Main case "tools": - query.edit_message_text("Wähle eine Tool Funktion:", reply_markup=telegram.InlineKeyboardMarkup(tools_menu)) + await query.message.reply_text("Wähle eine Tool Funktion:", reply_markup=InlineKeyboardMarkup(tools_menu)) case "game_servers": - query.edit_message_text("Wähle einen Gameserver Typ:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu)) - + await query.message.reply_text("Wähle einen Gameserver Typ:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) # Tools case "nuc_satus": - pass + status = get_status_nuc() + await query.message.reply_text(f"Nuc Morroc Status (Auslastungen) \nCPU:{status["cpu"]}\nRAM:{status["ram"]}") case "nuc_shutdown": - pass + logging.info("Received request to shutdown.") + try: + os.system("shutdown /s /t 1") + await query.message.reply_text(f"Nuc Morroc wird heruntergefahren") + except Exception as exc: + logging.error(f"Error executing shutdown command: {exc}") + await query.message.reply_text(f"Fehler beim herunterfahren des Nuc Morroc.") case "nuc_back": - query.edit_message_text("Wähle ein Themengebiet aus:", reply_markup=telegram.InlineKeyboardMarkup(main_menu)) - + await send_main_menu(context, query.message.chat_id) # Game Servers case "gameservers_status": - pass + logging.info("Received request for gameserver status.") + status_msg = get_status_gameservers() + await query.message.reply_text(f"{status_msg}") case "gameservers_minecraft": - pass + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + case "gameservers_dontstarve": + await query.message.reply_text("Wähle eine Aktion für den Dont Starve Server:", reply_markup=InlineKeyboardMarkup(dont_starve_menu)) case "gameservers_ragnarok_online": - pass + await query.message.reply_text("Wähle eine Aktion für den Ragnarok Online Server:", reply_markup=InlineKeyboardMarkup(ragnarok_online_menu)) case "gameservers_wow": - pass + await query.message.reply_text("Wähle einen Aktion für den World of Warcraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) case "gameservers_back": - query.edit_message_text("Wähle ein Themengebiet aus:", reply_markup=telegram.InlineKeyboardMarkup(main_menu)) - - # Minecraft + await send_main_menu(context, query.message.chat_id) + # Minecraft Servers + case "minecraft_vanilla": + await query.message.reply_text("Wähle einen Aktion für den Minecraft Vanilla Server:", reply_markup=InlineKeyboardMarkup(mc_vanilla_menu)) + case "minecraft_sanderpack": + await query.message.reply_text("Wähle einen Aktion für den Minecraft SanderPack Server:", reply_markup=InlineKeyboardMarkup(mc_sanderpack_menu)) + case "minecraft_sanderhorizon": + await query.message.reply_text("Wähle einen Aktion für den Minecraft SanderHorizon Server:", reply_markup=InlineKeyboardMarkup(mc_sanderhorizon_menu)) + case "minecraft_sanderhardcore": + await query.message.reply_text("Wähle einen Aktion für den Minecraft SanderHardcore Server:", reply_markup=InlineKeyboardMarkup(mc_sanderhardcore_menu)) + case "minecraft_sandervalley": + await query.message.reply_text("Wähle einen Aktion für den Minecraft Vanilla Server:", reply_markup=InlineKeyboardMarkup(mc_sandervalley_menu)) case "minecraft_back": - query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu)) - - # Ragnarok Online + await query.message.reply_text("Wähle einen Gameserver Typ:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) + # MC Vanilla + case "mc_vanilla_start": + msg = start_gameserver("mc_vanilla") + await query.message.reply_text(f"{msg}") + case "mc_vanilla_stop": + msg = stop_gameserver("mc_vanilla") + await query.message.reply_text(f"{msg}") + case "mc_vanilla_back": + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + # MC Sanderpack (The 1.12.2 Pack) + case "mc_sanderpack_start": + msg = start_gameserver("mc_sanderpack") + await query.message.reply_text(f"{msg}") + case "mc_sanderpack_stop": + msg = stop_gameserver("mc_sanderpack") + await query.message.reply_text(f"{msg}") + case "mc_sanderpack_back": + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + # MC Sanderhorizons (GT New Horizons) + case "mc_sanderhorizon_start": + msg = start_gameserver("mc_sanderhorizons") + await query.message.reply_text(f"{msg}") + case "mc_sanderhorizon_stop": + msg = stop_gameserver("mc_sanderhorizons") + await query.message.reply_text(f"{msg}") + case "mc_sanderhorizon_back": + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + # MC Sanderhardcore (RLCraft) + case "mc_sanderhardcore_start": + msg = start_gameserver("mc_sanderhardcore") + await query.message.reply_text(f"{msg}") + case "mc_sanderhardcore_stop": + msg = stop_gameserver("mc_sanderhardcore") + await query.message.reply_text(f"{msg}") + case "mc_sanderhardcore_back": + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + # MC Sandervalley (FarmingValley) + case "mc_sandervalley_start": + msg = start_gameserver("mc_sandervalley") + await query.message.reply_text(f"{msg}") + case "mc_sandervalley_stop": + msg = stop_gameserver("mc_sandervalley") + await query.message.reply_text(f"{msg}") + case "mc_sandervalley_back": + await query.message.reply_text("Wähle einen Minecraft Server:", reply_markup=InlineKeyboardMarkup(minecraft_menu)) + # Dont Starve Server + case "dst_start": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) + case "dst_stop": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) + case "dst_back": + await query.message.reply_text("Wähle einen Gameserver Typ:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) + # Ragnarok Online Server + case "ro_start": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) + case "ro_stop": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) case "ro_back": - query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu)) - # World of Warcraft + await query.message.reply_text("Wähle einen Gameserver Typ:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) + # World of Warcraft Server + case "wow_start": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) + case "wow_stop": + msg = "Not Implemented yet" + await query.message.reply_text(f"{msg}") + await send_main_menu(context, query.message.chat_id) case "wow_back": - query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu)) - - # Default Case - case _: - print() -""" -async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: - query = update.callback_query - await query.answer() - await start_timer(context, query.message.chat_id) - data = query.data - - match data: - case "tools": - query.message.reply_text("Wähle eine Tool Funktion:", reply_markup=InlineKeyboardMarkup(tools_menu)) - - match query.data_: == '1': #todo cases einbauen +finalisieren - # Nested menu for Option 1 - gameserver_menu = [ - [InlineKeyboardButton("Game 1", callback_data='game1')], - [InlineKeyboardButton("Game 2", callback_data='game2')], - [InlineKeyboardButton("Back", callback_data='start')], - ] - await query.message.reply_text(text="Wähle ein Game aus:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) - elif query.data == '2': - # Nested menu for Option 2 - other_menu = [ - [InlineKeyboardButton("Service 1", callback_data='service1')], - [InlineKeyboardButton("Service 2", callback_data='service2')], - [InlineKeyboardButton("Back", callback_data='start')], - ] - await query.message.reply_text(text="Wähle einen Service aus:", reply_markup=InlineKeyboardMarkup(other_menu)) - elif query.data == 'start': - await start(update, context) - elif query.data.startswith('game'): - await query.message.reply_text(f"You selected {query.data}") - elif query.data.startswith('service'): - await query.message.reply_text(f"You selected {query.data}") - -async def on_startup(application: Application): - # Broadcast message on startup - await broadcast_message(application, "Nuc-Morroc hier. Bin jetzt wach :)") - - -if __name__ == '__main__': + await query.message.reply_text("Wähle einen Gameserver Typ:", reply_markup=InlineKeyboardMarkup(gameserver_menu)) + +if __name__ == '__main__': logging.info("Starte Telegram-Bot") - application = Application.builder().token(TELEGRAM_BOT_TOKEN).build() + application = Application.builder().token(TELEGRAM_BOT_TOKEN).post_init(on_startup).build() application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, verify_password)) application.add_handler(CallbackQueryHandler(handle_callback)) application.add_handler(CommandHandler("help", help_command)) - - # Set up the startup handler - application.post_init(on_startup) - + + # Run the bot application.run_polling() + + \ No newline at end of file