discord-bot / app /app.py
Alibrown's picture
Update app/app.py
3faff69 verified
raw
history blame
3.12 kB
from flask import Flask, request, jsonify
import os
import logging
from waitress import serve
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
# Logging konfigurieren
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Konfiguration aus Umgebungsvariablen
PUBLIC_KEY = os.getenv('Public_Key', '').strip() # Strip entfernt Leerzeichen
APPLICATION_ID = os.getenv('Application_ID', '').strip()
app = Flask(__name__)
try:
# Versuche den Public Key zu verifizieren
verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY)) if PUBLIC_KEY else None
logger.info("Successfully initialized verify_key")
except Exception as e:
logger.error(f"Error initializing verify_key: {str(e)}")
verify_key = None
@app.route("/", methods=["GET"])
def health_check():
return jsonify({
"status": "healthy",
"message": "Discord bot is running!",
"public_key_present": bool(PUBLIC_KEY),
"verify_key_initialized": verify_key is not None,
"application_id_present": bool(APPLICATION_ID)
})
@app.route("/debug", methods=["GET"])
def debug():
# Zeige wichtige Informationen (aber keine sensiblen Daten!)
return jsonify({
"public_key_length": len(PUBLIC_KEY) if PUBLIC_KEY else 0,
"application_id_length": len(APPLICATION_ID) if APPLICATION_ID else 0,
"verify_key_status": "initialized" if verify_key else "failed",
"environment_variables": list(os.environ.keys())
})
@app.route("/interactions", methods=["POST"])
def interactions():
logger.info("Received interaction request")
logger.info(f"Headers: {dict(request.headers)}")
if not verify_key:
logger.error("verify_key not initialized")
return "Configuration error", 500
# Verify the request
signature = request.headers.get('X-Signature-Ed25519')
timestamp = request.headers.get('X-Signature-Timestamp')
logger.info(f"Signature present: {bool(signature)}")
logger.info(f"Timestamp present: {bool(timestamp)}")
if not signature or not timestamp:
logger.warning("Missing headers")
return "Invalid request signature", 401
try:
body = request.data.decode('utf-8')
verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
# Process the verified request
data = request.json
if data.get("type") == 1:
logger.info("Responding to ping")
return jsonify({"type": 1})
if data.get("type") == 2:
return jsonify({
"type": 4,
"data": {
"content": "Command received!"
}
})
return jsonify({"error": "Unknown type"}), 400
except Exception as e:
logger.error(f"Error: {str(e)}")
return "Invalid request signature", 401
if __name__ == "__main__":
logger.info("Starting Discord bot...")
serve(app, host="0.0.0.0", port=8080)