main
Alex 6 months ago
parent 946090ed54
commit c217d44fef

@ -1,26 +1,24 @@
from flask import Flask, request, jsonify
import subprocess
import os
import logging
from flask import Flask, request, jsonify
#from win10toast import ToastNotifier
import asyncio
import subprocess
import signal
import psutil
#from win10toast import ToastNotifier
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
import asyncio
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()
# Telegram bot token
TELEGRAM_BOT_TOKEN = '5103145116:AAE_sVgkx8atxgizMuE38ClwbRLAyDUMSeM'
bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
# File to store subscriber chat IDs
SUBSCRIBERS_FILE = 'telegramm_subscribers.txt'
####
# Constants
####
# Global list to store process handles
processes = []
@ -42,6 +40,39 @@ SCRIPTS = {
]
}
####
# 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:
@ -61,28 +92,9 @@ def is_java_process_running(pid):
return False
return False
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 []
def save_subscriber(chat_id):
"""Save a new subscriber chat ID to the file."""
with open(SUBSCRIBERS_FILE, 'a') as file:
file.write(f"{chat_id}\n")
async def send_telegram_message(message):
"""Send a message to all subscribers."""
subscribers = load_subscribers()
for chat_id in subscribers:
try:
prepped_message = f"[nuc_morroc]{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}")
####
# Flask Functions
####
@app.route('/osiris_execute', methods=['POST'])
def execute_script():
@ -134,7 +146,7 @@ def execute_script():
pid_file = os.path.join(os.path.dirname(path), 'server.pid')
pid = read_pid_file(pid_file)
if is_java_process_running(command):
if is_java_process_running(pid):
logging.info(f"Script {script_name} is already running.")
results.append({
"script": path,
@ -254,6 +266,7 @@ def status_gameservers():
logging.info("Check Status der Server")
global processes_info
running_servers = []
server_list = []
for process in processes_info:
running_servers.append(process['name'])
server_list = "\n - ".join(running_servers)
@ -261,19 +274,10 @@ def status_gameservers():
return jsonify({"message": f"Aktuell laufende Server: {server_list}" })
# Endpoint to add subscribers | Note: aktuell nur händisch mittels Übertrag der ID aus IOBroker heraus
@app.route('/subscribe', methods=['POST'])
def subscribe():
data = request.get_json()
chat_id = data.get('chat_id')
if chat_id:
save_subscriber(chat_id)
return jsonify({'message': 'Subscribed successfully.'})
return jsonify({'error': 'No chat_id provided'}), 400
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)
Loading…
Cancel
Save