Actualiser bot.js

on tente d etendre les methode de reponses possibles.
This commit is contained in:
2025-09-09 20:26:40 +00:00
parent 74223f6eb8
commit f0067d72b7

57
bot.js
View File

@ -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 nai point reçu de réponse de loracle 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 !");
}
});