You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
7.9 KiB
Python

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/',
'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
####
# Telegram bot token
TELEGRAM_BOT_TOKEN = '6984289827:AAHNUM4F_U6233oa75nX5jXyQY6vC0NlZvw'
# Create an Bot with a larger connection pool and longer pool timeout
bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
# File to store subscriber chat IDs
SUBSCRIBERS_FILE = 'telegramm_subscribers.txt'
def load_subscribers():
"""Load subscriber chat IDs from the file."""
if os.path.exists(SUBSCRIBERS_FILE):
with open(SUBSCRIBERS_FILE, 'r') as file:
return [line.strip() for line in file.readlines()]
return []
async def send_telegram_message(message):
"""Send a message to all subscribers."""
subscribers = load_subscribers()
for chat_id in subscribers:
try:
prepped_message = f"{message}"
await bot.send_message(chat_id=chat_id, text=prepped_message)
except telegram.error.TelegramError as e:
logging.error(f"Error sending message to {chat_id}: {e}")
####
# 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)