Mise à jour : migration vers ForgeJo
This commit is contained in:
parent
d8ef20ba8c
commit
c2bcd5a2f2
2 changed files with 124 additions and 74 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import disnake
|
||||
from disnake.ext import commands
|
||||
from utils.gitlab_client import gitlab_client
|
||||
from utils.forgejo_client import gitlab_client
|
||||
from aiohttp import web
|
||||
import logging
|
||||
import json
|
||||
|
|
@ -10,12 +10,46 @@ from typing import Dict, Any, Optional
|
|||
|
||||
kuby_logger = logging.getLogger("KubyBot")
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# ⚡ NOUVEAU: Utilise le même fichier que gitlab_integration.py
|
||||
TRACKING_FILE = os.path.join(BASE_DIR, "commandes", "gitlab_issues.json")
|
||||
LEGACY_REPORTS_FILE = os.path.join(BASE_DIR, "data", "gitlab_reports.json")
|
||||
|
||||
|
||||
def classify_webhook_event(payload: Dict[str, Any]) -> Optional[str]:
|
||||
"""Détermine si un webhook correspond à une issue ou à un commentaire."""
|
||||
object_kind = payload.get("object_kind")
|
||||
if object_kind in {"issue", "note"}:
|
||||
return object_kind
|
||||
|
||||
action = str(payload.get("action", "")).lower()
|
||||
if "comment" in action or "comment" in payload:
|
||||
return "note"
|
||||
|
||||
if "issue" in payload or "object_attributes" in payload or payload.get("issue"):
|
||||
return "issue"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def extract_issue_iid(payload: Dict[str, Any]) -> Optional[str]:
|
||||
"""Extrait l’identifiant d’issue depuis plusieurs formats Forgejo/GitLab."""
|
||||
candidates = [
|
||||
payload.get("object_attributes", {}).get("iid"),
|
||||
payload.get("object_attributes", {}).get("id"),
|
||||
payload.get("object_attributes", {}).get("number"),
|
||||
payload.get("issue", {}).get("iid"),
|
||||
payload.get("issue", {}).get("number"),
|
||||
payload.get("issue", {}).get("id"),
|
||||
payload.get("comment", {}).get("issue_id"),
|
||||
payload.get("comment", {}).get("issue_number"),
|
||||
]
|
||||
|
||||
for candidate in candidates:
|
||||
if candidate is not None:
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def load_tracking():
|
||||
"""Charge le tracking depuis gitlab_issues.json (avec migration automatique)"""
|
||||
tracking = {}
|
||||
|
|
@ -255,31 +289,29 @@ class BugReport(commands.Cog):
|
|||
self.bot.loop.create_task(cleanup())
|
||||
|
||||
async def handle_bot_event(self, request):
|
||||
"""Gère les webhooks GitLab (notifications instantanées)"""
|
||||
"""Gère les webhooks (adapté pour GitLab ET Forgejo)"""
|
||||
try:
|
||||
if not self.bot.is_ready():
|
||||
kuby_logger.info("Webhook received but bot is not ready yet. Waiting up to 10s...")
|
||||
try:
|
||||
await asyncio.wait_for(self.bot.wait_until_ready(), timeout=10.0)
|
||||
except asyncio.TimeoutError:
|
||||
kuby_logger.warning("Bot still not ready after 10s. Proceeding anyway (best effort).")
|
||||
kuby_logger.warning("Bot still not ready after 10s. Proceeding anyway.")
|
||||
|
||||
payload = await request.json()
|
||||
event_type = payload.get("object_kind")
|
||||
|
||||
# 🕵️ 1. DÉTECTION DU TYPE (Compatibilité Forgejo vs GitLab)
|
||||
event_type = classify_webhook_event(payload)
|
||||
if event_type not in ["issue", "note"]:
|
||||
kuby_logger.info("Webhook ignoré : type d’événement non reconnu")
|
||||
return web.json_response({"status": "ignored"}, status=200)
|
||||
|
||||
# Récupère l'IID de l'issue
|
||||
issue_iid = str(
|
||||
payload.get("object_attributes", {}).get("iid") or
|
||||
payload.get("issue", {}).get("iid")
|
||||
)
|
||||
|
||||
# 🕵️ 2. RÉCUPÉRATION DE L'ID DU TICKET
|
||||
issue_iid = extract_issue_iid(payload)
|
||||
if not issue_iid:
|
||||
kuby_logger.warning("Webhook ignoré : aucun identifiant d’issue trouvé dans le payload")
|
||||
return web.json_response({"status": "no issue id"}, status=200)
|
||||
|
||||
# Vérifie si l'issue est trackée
|
||||
issue_data = self.issue_data.get(issue_iid)
|
||||
if not issue_data:
|
||||
return web.json_response({"status": "untracked issue"}, status=200)
|
||||
|
|
@ -294,66 +326,52 @@ class BugReport(commands.Cog):
|
|||
user = await self.bot.fetch_user(user_id)
|
||||
except:
|
||||
return web.json_response({"status": "user not found"}, status=200)
|
||||
|
||||
app_info = await self.bot.application_info()
|
||||
dev = app_info.owner
|
||||
issue_title = payload.get("object_attributes", {}).get("title", f"#{issue_iid}")
|
||||
|
||||
# 🕵️ 3. RÉCUPÉRATION DU TITRE
|
||||
issue_title = (
|
||||
payload.get("object_attributes", {}).get("title") or
|
||||
payload.get("issue", {}).get("title", f"#{issue_iid}")
|
||||
)
|
||||
|
||||
if event_type == "note":
|
||||
# ⚡ NOUVEAU: Notifie les commentaires via le webhook (instantané)
|
||||
note_attr = payload.get("object_attributes", {})
|
||||
is_system = note_attr.get("system", False)
|
||||
|
||||
if not is_system:
|
||||
# 🕵️ 4. EXTRACTION DU COMMENTAIRE FORGEJO / GITLAB
|
||||
if "comment" in payload:
|
||||
# Mode Forgejo
|
||||
note_body = payload["comment"].get("body", "")
|
||||
author_name = payload.get("sender", {}).get("username", "Développeur")
|
||||
is_system = False
|
||||
else:
|
||||
# Mode GitLab
|
||||
note_attr = payload.get("object_attributes", {})
|
||||
is_system = note_attr.get("system", False)
|
||||
note_body = (
|
||||
note_attr.get("note") or
|
||||
note_attr.get("body") or
|
||||
payload.get("note", "") or
|
||||
""
|
||||
payload.get("note", "") or ""
|
||||
)
|
||||
author_name = payload.get("user", {}).get("name", "Développeur")
|
||||
|
||||
if note_body:
|
||||
try:
|
||||
embed = disnake.Embed(
|
||||
title="💬 Nouveau commentaire sur votre signalement",
|
||||
description=f"Le développeur a répondu à votre rapport **{issue_title}** :\n\n>>> {note_body}\n\n✍️ **Par :** {author_name}",
|
||||
color=disnake.Color.orange()
|
||||
)
|
||||
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
|
||||
await user.send(embed=embed)
|
||||
kuby_logger.info(f"Commentaire GitLab envoyé à {user} pour l'issue #{issue_iid}")
|
||||
except (disnake.Forbidden, disnake.HTTPException) as e:
|
||||
kuby_logger.warning(f"Impossible d'envoyer le DM à {user}: {e}")
|
||||
if dev and dev.id != user.id:
|
||||
try:
|
||||
await dev.send(f"⚠️ [DM BLOQUÉ] Impossible d'envoyer le commentaire à {user} pour l'issue #{issue_iid}")
|
||||
except:
|
||||
pass
|
||||
|
||||
elif event_type == "issue":
|
||||
# Notifie les changements d'état/label
|
||||
action = payload.get("object_attributes", {}).get("action")
|
||||
changes = payload.get("changes", {})
|
||||
state = payload.get("object_attributes", {}).get("state")
|
||||
|
||||
if "labels" in changes:
|
||||
curr_labels = [l.get("title") for l in changes["labels"].get("current", []) if l.get("title")]
|
||||
display_labels = [l for l in curr_labels if not l.startswith("Priority::") and l not in ["bug", "manual-report", "manual-suggestion"]]
|
||||
current_labels_str = ", ".join(display_labels) if display_labels else "Mis à jour"
|
||||
|
||||
if not is_system and note_body:
|
||||
try:
|
||||
embed = disnake.Embed(
|
||||
title="🛠️ Mise à jour de votre signalement !",
|
||||
description=f"Le statut de votre rapport **{issue_title}** a été mis à jour par l'équipe.\n\n📌 **Nouveaux Labels / Statuts :** {current_labels_str}",
|
||||
color=disnake.Color.blue()
|
||||
title="💬 Nouveau commentaire sur votre signalement",
|
||||
description=f"L'équipe a répondu à votre rapport **{issue_title}** :\n\n>>> {note_body}\n\n✍️ **Par :** {author_name}",
|
||||
color=disnake.Color.orange()
|
||||
)
|
||||
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
|
||||
if self.bot.user.display_avatar:
|
||||
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
|
||||
await user.send(embed=embed)
|
||||
except Exception as e:
|
||||
kuby_logger.error(f"Erreur notification label: {e}")
|
||||
kuby_logger.info(f"Commentaire envoyé à {user} pour l'issue #{issue_iid}")
|
||||
except (disnake.Forbidden, disnake.HTTPException) as e:
|
||||
kuby_logger.warning(f"Impossible d'envoyer le DM à {user}: {e}")
|
||||
|
||||
elif event_type == "issue":
|
||||
# 🕵️ 5. GESTION DES CLÔTURES (Optionnel : si tu fermes le ticket sur Forgejo)
|
||||
action = payload.get("object_attributes", {}).get("action") or payload.get("action")
|
||||
state = payload.get("object_attributes", {}).get("state") or payload.get("issue", {}).get("state")
|
||||
|
||||
is_closing_now = action in ["close", "closed"] or state == "closed"
|
||||
|
||||
is_closing_now = action == "close" or (state == "closed" and "state_id" in changes)
|
||||
if is_closing_now:
|
||||
try:
|
||||
embed = disnake.Embed(
|
||||
|
|
@ -361,7 +379,8 @@ class BugReport(commands.Cog):
|
|||
description=f"Bonne nouvelle ! Votre signalement **{issue_title}** a été marqué comme terminé ou résolu.\n\n🚀 **Prochaine étape :** La mise à jour arrive prochainement !\n✨ Merci pour votre aide !",
|
||||
color=disnake.Color.green()
|
||||
)
|
||||
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
|
||||
if self.bot.user.display_avatar:
|
||||
embed.set_thumbnail(url=self.bot.user.display_avatar.url)
|
||||
await user.send(embed=embed)
|
||||
except Exception as e:
|
||||
kuby_logger.error(f"Erreur notification clôture: {e}")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue