Première version de la mise à jour du suivie des bugs
This commit is contained in:
parent
fd9251fc6e
commit
d155ebfcb0
2 changed files with 235 additions and 49 deletions
101
serveur_flask.py
Normal file
101
serveur_flask.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import os, subprocess, threading, requests
|
||||
from flask import Flask, request, abort
|
||||
from datetime import datetime, timezone
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# --- CONFIGURATION ---
|
||||
PROJECT_PATH = "/home/discord/Bot/Kuby_V2"
|
||||
WEBHOOK_SECRET = "Nois1"
|
||||
PROCESS_NAME = "kuby-bot"
|
||||
DISCORD_LOG_URL = "https://discord.com/api/webhooks/1482148910888652910/IA9CcOWtjGswbuxMaOu_6uaclv5zojZo4ttxtV6RYyZzJ9gW7BF7xp_Zv3oPIjYEuh8o"
|
||||
|
||||
# Bot Local Proxy
|
||||
BOT_LOCAL_URL = "http://127.0.0.1:5001/bot_event"
|
||||
|
||||
def send_discord_log(status, message, color, author=None, commit_msg=None):
|
||||
embed = {
|
||||
"title": f"🚀 Kuby V2 : {status}",
|
||||
"description": message,
|
||||
"color": color,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"fields": []
|
||||
}
|
||||
|
||||
if author:
|
||||
embed["fields"].append({"name": "👤 Auteur", "value": author, "inline": True})
|
||||
if commit_msg:
|
||||
embed["fields"].append({"name": "📝 Commit", "value": commit_msg, "inline": True})
|
||||
|
||||
payload = {"embeds": [embed]}
|
||||
try:
|
||||
requests.post(DISCORD_LOG_URL, json=payload, timeout=5)
|
||||
except Exception as e:
|
||||
print(f"[!] Erreur envoi Discord : {e}")
|
||||
|
||||
def run_mep_logic(author, commit_msg):
|
||||
start_time = datetime.now()
|
||||
send_discord_log("EN COURS", "Déploiement lancé sur la machine de guerre...", 3447003, author, commit_msg)
|
||||
|
||||
try:
|
||||
os.chdir(PROJECT_PATH)
|
||||
|
||||
# 1. GIT
|
||||
subprocess.run(["git", "fetch", "origin"], check=True)
|
||||
subprocess.run(["git", "reset", "--hard", "origin/main"], check=True)
|
||||
|
||||
# 2. PM2
|
||||
subprocess.run(f"pm2 restart {PROCESS_NAME}", shell=True, check=True, capture_output=True)
|
||||
|
||||
duration = (datetime.now() - start_time).total_seconds()
|
||||
msg = f"✅ **Déploiement réussi en {duration:.2f}s**\nLe bot est à jour et redémarré."
|
||||
send_discord_log("TERMINÉ", msg, 3066993, author, commit_msg)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"❌ **ERREUR de déploiement**\n```python\n{str(e)}\n```"
|
||||
send_discord_log("ÉCHEC", error_msg, 15158332, author, commit_msg)
|
||||
|
||||
@app.route('/deploy', methods=['POST'])
|
||||
def deploy():
|
||||
# Sécurité
|
||||
if request.headers.get('X-Gitlab-Token') != WEBHOOK_SECRET:
|
||||
abort(403)
|
||||
|
||||
# Extraction des infos GitLab
|
||||
data = request.json
|
||||
author = "Inconnu"
|
||||
commit_msg = "Pas de message"
|
||||
|
||||
if data and 'commits' in data and len(data['commits']) > 0:
|
||||
author = data['commits'][0].get('author', {}).get('name', 'Inconnu')
|
||||
commit_msg = data['commits'][0].get('message', 'Pas de message')
|
||||
|
||||
# Threading pour répondre vite à GitLab
|
||||
threading.Thread(target=run_mep_logic, args=(author, commit_msg)).start()
|
||||
|
||||
return {"status": "accepted"}, 202
|
||||
|
||||
@app.route('/gitlab_webhook', methods=['POST'])
|
||||
def gitlab_webhook():
|
||||
# Protection stricte Anti-Crawler
|
||||
user_agent = request.headers.get('User-Agent', '')
|
||||
if 'GitLab' not in user_agent:
|
||||
abort(404) # Retourne une 404 pour simuler que la page n'existe pas
|
||||
|
||||
if request.headers.get('X-Gitlab-Token') != WEBHOOK_SECRET:
|
||||
abort(404)
|
||||
|
||||
# Transférer la payload au bot Discord localement sur le port 5001
|
||||
payload = request.json
|
||||
try:
|
||||
# Timeout très court car c'est en local
|
||||
requests.post(BOT_LOCAL_URL, json=payload, timeout=2)
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"[!] Erreur de relais vers le bot Discord : {e}")
|
||||
# On renvoie 200 à GitLab quand même car GitLab n'a pas à savoir l'état interne
|
||||
|
||||
return {"status": "received"}, 200
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(f"[*] Webhook opérationnel. En attente de push ou d'events...")
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
Loading…
Add table
Add a link
Reference in a new issue