From f0067d72b7964de39d6b645ea8aa34c7384daaa8 Mon Sep 17 00:00:00 2001 From: Aydent Date: Tue, 9 Sep 2025 20:26:40 +0000 Subject: [PATCH] Actualiser bot.js on tente d etendre les methode de reponses possibles. --- bot.js | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/bot.js b/bot.js index 8665ba3..32fa7aa 100644 --- a/bot.js +++ b/bot.js @@ -30,23 +30,70 @@ client.on("messageCreate", async (message) => { if (message.author.bot) return; console.log(`📩 Message from ${message.author.tag} in ${message.guild ? message.guild.name : "DM"}: ${message.content}`); + // envoi vers n8n const res = await fetch(N8N_WEBHOOK, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: message.content, user: message.author.username }) }); - const data = await res.json().catch(() => null); - console.log("↩️ n8n response raw:", data); + const rawText = await res.text(); // récup brut + console.log("↩️ n8n response raw:", rawText); - if (data && data.reply) { + let data; + try { + // cas 1 : réponse directement en JSON + data = JSON.parse(rawText); + } catch { + // cas 2 : n8n a renvoyé du texte avec JSON dedans + const jsonMatch = rawText.match(/```json([\s\S]*?)```/i) || rawText.match(/{[\s\S]*}/); + if (jsonMatch) { + try { + data = JSON.parse(jsonMatch[1] || jsonMatch[0]); + } catch (e) { + console.warn("⚠️ Impossible de parser le JSON extrait :", e); + } + } + } + + // fallback si rien de parsé + if (!data) { + data = { reply: rawText.trim() }; // au moins répondre avec le texte brut + } + + // nettoyer le champ reply si présent + if (data.reply) { + data.reply = data.reply + .replace(/```[\s\S]*?```/g, "") // supprime blocs de code + .replace(/\\n/g, "\n") // normalise retours ligne + .trim(); + } + + // === Envoi de la réponse === + if (data.reply) { await message.reply(data.reply); } else { - // fallback minimal log - console.log("⚠️ No 'reply' field in n8n response."); + await message.reply("⚠️ Sire, je n’ai point reçu de réponse de l’oracle n8n !"); + } + + // === Si action clear_channel demandée === + if (data.action === "clear_channel" && data.channel_id && Array.isArray(data.messages_to_delete)) { + const channel = await client.channels.fetch(data.channel_id); + if (channel && channel.isTextBased()) { + for (const msgId of data.messages_to_delete) { + try { + const msg = await channel.messages.fetch(msgId); + if (msg) await msg.delete(); + } catch (err) { + console.error(`❌ Failed to delete message ${msgId}:`, err); + } + } + console.log(`✅ Deleted ${data.messages_to_delete.length} messages in ${channel.id}`); + } } } catch (err) { console.error("🔴 Error in message handler:", err); + await message.reply("⚠️ Sire, une erreur est survenue lors de ma consultation de n8n !"); } });