modified: app.py
modified: templates/server_selection.html
This commit is contained in:
139
app.py
139
app.py
@@ -1,12 +1,11 @@
|
|||||||
__version__ = "dev-0.4.6"
|
__version__ = "dev-0.4.7"
|
||||||
__all__ = ["Discordbot-chatai-webpanel (Discord)"]
|
__all__ = ["Discordbot-chatai-webpanel (Discord)"]
|
||||||
__author__ = "SimolZimol"
|
__author__ = "SimolZimol"
|
||||||
|
|
||||||
from flask import Flask, render_template, redirect, url_for, request, session, jsonify, send_file, flash
|
from flask import Flask, render_template, redirect, url_for, request, session, jsonify, flash
|
||||||
from requests_oauthlib import OAuth2Session
|
from requests_oauthlib import OAuth2Session
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import psutil
|
|
||||||
import mysql.connector
|
import mysql.connector
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@@ -15,49 +14,27 @@ app.secret_key = os.getenv("FLASK_SECRET_KEY")
|
|||||||
|
|
||||||
LOG_FILE_PATH = os.path.join("logs", f"{datetime.now().strftime('%Y-%m-%d')}.log")
|
LOG_FILE_PATH = os.path.join("logs", f"{datetime.now().strftime('%Y-%m-%d')}.log")
|
||||||
|
|
||||||
# Verwende Umgebungsvariablen für die Datenbankverbindung
|
# Datenbankverbindung
|
||||||
DB_HOST = os.getenv("DB_HOST")
|
DB_HOST = os.getenv("DB_HOST")
|
||||||
DB_PORT = os.getenv("DB_PORT")
|
DB_PORT = os.getenv("DB_PORT")
|
||||||
DB_USER = os.getenv("DB_USER")
|
DB_USER = os.getenv("DB_USER")
|
||||||
DB_PASS = os.getenv("DB_PASSWORD")
|
DB_PASS = os.getenv("DB_PASSWORD")
|
||||||
DB_NAME = os.getenv("DB_DATABASE")
|
DB_NAME = os.getenv("DB_DATABASE")
|
||||||
|
|
||||||
|
# Discord OAuth2-Konfiguration
|
||||||
DISCORD_CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
|
DISCORD_CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
|
||||||
DISCORD_CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
|
DISCORD_CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
|
||||||
DISCORD_REDIRECT_URI = os.getenv("DISCORD_REDIRECT_URI")
|
DISCORD_REDIRECT_URI = os.getenv("DISCORD_REDIRECT_URI")
|
||||||
DISCORD_OAUTH2_URL = "https://discord.com/api/oauth2/authorize"
|
DISCORD_OAUTH2_URL = "https://discord.com/api/oauth2/authorize"
|
||||||
DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token"
|
DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token"
|
||||||
DISCORD_API_URL = "https://discord.com/api/users/@me"
|
DISCORD_API_URL = "https://discord.com/api/users/@me"
|
||||||
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
|
DISCORD_GUILDS_URL = "https://discord.com/api/users/@me/guilds"
|
||||||
|
|
||||||
# Speichern der Prozess-ID
|
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # nur für Entwicklungszwecke
|
||||||
|
|
||||||
|
# Bot-Status
|
||||||
bot_process = None
|
bot_process = None
|
||||||
|
|
||||||
def bot_status():
|
|
||||||
"""Überprüft, ob der Bot läuft."""
|
|
||||||
global bot_process
|
|
||||||
if bot_process is None:
|
|
||||||
return False
|
|
||||||
return bot_process.poll() is None # None bedeutet, dass der Prozess noch läuft
|
|
||||||
|
|
||||||
def start_bot():
|
|
||||||
"""Startet den Bot."""
|
|
||||||
global bot_process
|
|
||||||
if not bot_status():
|
|
||||||
bot_process = subprocess.Popen(["python", "bot.py"], cwd=os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
else:
|
|
||||||
print("Bot läuft bereits.")
|
|
||||||
|
|
||||||
def stop_bot():
|
|
||||||
"""Stoppt den Bot."""
|
|
||||||
global bot_process
|
|
||||||
if bot_process and bot_status():
|
|
||||||
bot_process.terminate()
|
|
||||||
bot_process.wait() # Warten, bis der Prozess beendet ist
|
|
||||||
bot_process = None
|
|
||||||
else:
|
|
||||||
print("Bot läuft nicht.")
|
|
||||||
|
|
||||||
def get_db_connection():
|
def get_db_connection():
|
||||||
"""Stellt eine Verbindung zur MySQL-Datenbank her."""
|
"""Stellt eine Verbindung zur MySQL-Datenbank her."""
|
||||||
return mysql.connector.connect(
|
return mysql.connector.connect(
|
||||||
@@ -69,26 +46,33 @@ def get_db_connection():
|
|||||||
)
|
)
|
||||||
|
|
||||||
def make_discord_session(token=None, state=None):
|
def make_discord_session(token=None, state=None):
|
||||||
|
"""Erstellt eine Discord OAuth2-Session."""
|
||||||
return OAuth2Session(
|
return OAuth2Session(
|
||||||
DISCORD_CLIENT_ID,
|
DISCORD_CLIENT_ID,
|
||||||
token=token,
|
token=token,
|
||||||
state=state,
|
state=state,
|
||||||
redirect_uri=DISCORD_REDIRECT_URI,
|
redirect_uri=DISCORD_REDIRECT_URI,
|
||||||
scope=["identify", "guilds"] # Hinzufügen des "guilds"-Scopes
|
scope=["identify", "guilds"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def fetch_discord_guilds(discord_session):
|
||||||
|
"""Lädt die Gilden des Benutzers von der Discord-API."""
|
||||||
|
try:
|
||||||
|
return discord_session.get(DISCORD_GUILDS_URL).json()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Fehler beim Abrufen der Gilden: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
def is_bot_admin():
|
def is_bot_admin():
|
||||||
"""Überprüft, ob der Benutzer globale Admin-Rechte hat."""
|
"""Überprüft, ob der Benutzer globale Admin-Rechte hat."""
|
||||||
if "discord_user" in session:
|
if "discord_user" in session:
|
||||||
user_info = session["discord_user"]
|
user_info = session["discord_user"]
|
||||||
user_id = user_info["id"]
|
user_id = user_info["id"]
|
||||||
|
|
||||||
connection = get_db_connection()
|
connection = get_db_connection()
|
||||||
cursor = connection.cursor(dictionary=True)
|
cursor = connection.cursor(dictionary=True)
|
||||||
cursor.execute("SELECT global_permission FROM bot_data WHERE user_id = %s", (user_id,))
|
cursor.execute("SELECT global_permission FROM bot_data WHERE user_id = %s", (user_id,))
|
||||||
user_data = cursor.fetchone()
|
user_data = cursor.fetchone()
|
||||||
|
|
||||||
cursor.close()
|
cursor.close()
|
||||||
connection.close()
|
connection.close()
|
||||||
|
|
||||||
@@ -100,12 +84,11 @@ def is_server_admin(guild_id):
|
|||||||
if "discord_user" in session:
|
if "discord_user" in session:
|
||||||
user_info = session["discord_user"]
|
user_info = session["discord_user"]
|
||||||
user_id = user_info["id"]
|
user_id = user_info["id"]
|
||||||
|
|
||||||
connection = get_db_connection()
|
connection = get_db_connection()
|
||||||
cursor = connection.cursor(dictionary=True)
|
cursor = connection.cursor(dictionary=True)
|
||||||
cursor.execute("SELECT permission FROM user_data WHERE user_id = %s AND guild_id = %s", (user_id, guild_id))
|
cursor.execute("SELECT permission FROM user_data WHERE user_id = %s AND guild_id = %s", (user_id, guild_id))
|
||||||
user_data = cursor.fetchone()
|
user_data = cursor.fetchone()
|
||||||
|
|
||||||
cursor.close()
|
cursor.close()
|
||||||
connection.close()
|
connection.close()
|
||||||
|
|
||||||
@@ -135,62 +118,35 @@ def callback():
|
|||||||
client_secret=DISCORD_CLIENT_SECRET,
|
client_secret=DISCORD_CLIENT_SECRET,
|
||||||
authorization_response=request.url,
|
authorization_response=request.url,
|
||||||
)
|
)
|
||||||
|
|
||||||
session['oauth_token'] = token
|
|
||||||
|
|
||||||
# User-Informationen von Discord abrufen
|
|
||||||
user_info = discord.get(DISCORD_API_URL).json()
|
|
||||||
session['discord_user'] = user_info
|
|
||||||
|
|
||||||
# Hole die Gilden (Server), auf denen der Benutzer ist
|
session['oauth_token'] = token
|
||||||
guilds = discord.get('https://discord.com/api/users/@me/guilds').json()
|
session['discord_user'] = discord.get(DISCORD_API_URL).json()
|
||||||
session['discord_guilds'] = guilds # Speichere die Gilden im Session
|
|
||||||
|
# Gilden (Server) nur einmal laden und in der Session speichern
|
||||||
|
session['discord_guilds'] = fetch_discord_guilds(discord)
|
||||||
|
|
||||||
return redirect(url_for("server_selection"))
|
return redirect(url_for("server_selection"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/server_selection")
|
@app.route("/server_selection")
|
||||||
def server_selection():
|
def server_selection():
|
||||||
"""Zeigt dem Benutzer eine Liste aller Server an, auf denen er sich befindet."""
|
"""Zeigt dem Benutzer eine Liste aller Server an, auf denen er sich befindet."""
|
||||||
if "discord_user" in session:
|
if "discord_user" in session:
|
||||||
user_info = session["discord_user"]
|
guilds = session.get('discord_guilds', [])
|
||||||
user_id = user_info["id"]
|
|
||||||
|
if not guilds:
|
||||||
connection = get_db_connection()
|
flash("Es wurden keine Server gefunden.", "danger")
|
||||||
cursor = connection.cursor(dictionary=True)
|
return redirect(url_for("landing_page"))
|
||||||
|
|
||||||
# Abfrage aller Server (guilds), auf denen der Benutzer ist
|
|
||||||
cursor.execute("SELECT DISTINCT guild_id FROM user_data WHERE user_id = %s", (user_id,))
|
|
||||||
guilds = cursor.fetchall()
|
|
||||||
|
|
||||||
cursor.close()
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
if len(guilds) == 1:
|
if len(guilds) == 1:
|
||||||
# Wenn der Benutzer nur auf einem Server ist, leiten wir direkt dorthin weiter
|
return redirect(url_for("user_dashboard", guild_id=guilds[0]['id']))
|
||||||
return redirect(url_for("user_dashboard", guild_id=guilds[0]['guild_id']))
|
|
||||||
else:
|
else:
|
||||||
return render_template("server_selection.html", guilds=guilds)
|
return render_template("server_selection.html", guilds=guilds)
|
||||||
|
|
||||||
return redirect(url_for("login"))
|
return redirect(url_for("login"))
|
||||||
|
|
||||||
@app.route("/admin_dashboard")
|
|
||||||
def admin_dashboard():
|
|
||||||
"""Zeigt das Bot-Admin-Dashboard an (nur für globale Admins)."""
|
|
||||||
if is_bot_admin():
|
|
||||||
return render_template("admin_dashboard.html", bot_running=bot_status())
|
|
||||||
return redirect(url_for("landing_page"))
|
|
||||||
|
|
||||||
@app.route("/server_admin_dashboard/<int:guild_id>")
|
|
||||||
def server_admin_dashboard(guild_id):
|
|
||||||
"""Zeigt das Server-Admin-Dashboard an (nur für Server-Admins)."""
|
|
||||||
if is_server_admin(guild_id):
|
|
||||||
return render_template("server_admin_dashboard.html", guild_id=guild_id)
|
|
||||||
return redirect(url_for("landing_page"))
|
|
||||||
|
|
||||||
@app.route("/user_dashboard/<int:guild_id>")
|
@app.route("/user_dashboard/<int:guild_id>")
|
||||||
def user_dashboard(guild_id):
|
def user_dashboard(guild_id):
|
||||||
"""Zeigt das User-Dashboard für einen spezifischen Server (guild_id) an."""
|
"""Zeigt das User-Dashboard für den ausgewählten Server an."""
|
||||||
if "discord_user" in session:
|
if "discord_user" in session:
|
||||||
user_info = session["discord_user"]
|
user_info = session["discord_user"]
|
||||||
user_id = user_info["id"]
|
user_id = user_info["id"]
|
||||||
@@ -198,7 +154,6 @@ def user_dashboard(guild_id):
|
|||||||
connection = get_db_connection()
|
connection = get_db_connection()
|
||||||
cursor = connection.cursor(dictionary=True)
|
cursor = connection.cursor(dictionary=True)
|
||||||
|
|
||||||
# Hole Benutzerinformationen für den ausgewählten Server
|
|
||||||
cursor.execute("SELECT * FROM user_data WHERE user_id = %s AND guild_id = %s", (user_id, guild_id))
|
cursor.execute("SELECT * FROM user_data WHERE user_id = %s AND guild_id = %s", (user_id, guild_id))
|
||||||
user_data = cursor.fetchone()
|
user_data = cursor.fetchone()
|
||||||
|
|
||||||
@@ -208,8 +163,9 @@ def user_dashboard(guild_id):
|
|||||||
if user_data:
|
if user_data:
|
||||||
return render_template("user_dashboard.html", user_info=user_info, user_data=user_data, guild_id=guild_id)
|
return render_template("user_dashboard.html", user_info=user_info, user_data=user_data, guild_id=guild_id)
|
||||||
else:
|
else:
|
||||||
return "User data not found", 404
|
flash("Keine Daten für diesen Server gefunden.", "danger")
|
||||||
|
return redirect(url_for("server_selection"))
|
||||||
|
|
||||||
return redirect(url_for("login"))
|
return redirect(url_for("login"))
|
||||||
|
|
||||||
@app.route("/logout")
|
@app.route("/logout")
|
||||||
@@ -218,20 +174,17 @@ def logout():
|
|||||||
session.clear()
|
session.clear()
|
||||||
return redirect(url_for("landing_page"))
|
return redirect(url_for("landing_page"))
|
||||||
|
|
||||||
# Bot Management Routes
|
# Verbesserte Fehlerbehandlung: Automatisches Logout bei ungültigem Token
|
||||||
@app.route("/start_bot")
|
@app.before_request
|
||||||
def start():
|
def check_oauth_token():
|
||||||
if is_bot_admin():
|
if "oauth_token" in session:
|
||||||
start_bot()
|
discord = make_discord_session(token=session["oauth_token"])
|
||||||
return redirect(url_for("admin_dashboard"))
|
try:
|
||||||
return redirect(url_for("landing_page"))
|
discord.get(DISCORD_API_URL) # Test-API-Aufruf, um Token zu validieren
|
||||||
|
except Exception:
|
||||||
@app.route("/stop_bot")
|
session.clear()
|
||||||
def stop():
|
flash("Deine Sitzung ist abgelaufen. Bitte erneut einloggen.", "warning")
|
||||||
if is_bot_admin():
|
return redirect(url_for("login"))
|
||||||
stop_bot()
|
|
||||||
return redirect(url_for("admin_dashboard"))
|
|
||||||
return redirect(url_for("landing_page"))
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
app.run(host="0.0.0.0", port=5000, debug=True)
|
||||||
|
|||||||
@@ -4,13 +4,18 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Server Selection</title>
|
<title>Server Selection</title>
|
||||||
|
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Select a Server</h1>
|
<div class="container">
|
||||||
<ul>
|
<h1 class="mt-5">Wähle einen Server</h1>
|
||||||
{% for guild in session['discord_guilds'] %}
|
<ul class="list-group mt-3">
|
||||||
<li><a href="{{ url_for('user_dashboard', guild_id=guild['id']) }}">{{ guild['name'] }}</a></li>
|
{% for guild in guilds %}
|
||||||
{% endfor %}
|
<li class="list-group-item">
|
||||||
</ul>
|
<a href="{{ url_for('user_dashboard', guild_id=guild['id']) }}">{{ guild['name'] }}</a>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user