Actualiser bot.js

This commit is contained in:
2025-09-06 12:42:15 +00:00
parent 6aa356f532
commit 56376c92f4

48
bot.js
View File

@ -1,6 +1,18 @@
import { Client, GatewayIntentBits } from "discord.js"; import { Client, GatewayIntentBits } from "discord.js";
import fetch from "node-fetch"; import fetch from "node-fetch";
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const N8N_WEBHOOK = process.env.N8N_WEBHOOK;
if (!DISCORD_TOKEN) {
console.error("❌ DISCORD_TOKEN is missing. Set the env var DISCORD_TOKEN.");
process.exit(1);
}
if (!N8N_WEBHOOK) {
console.error("❌ N8N_WEBHOOK is missing. Set the env var N8N_WEBHOOK.");
process.exit(1);
}
const client = new Client({ const client = new Client({
intents: [ intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
@ -9,28 +21,44 @@ const client = new Client({
] ]
}); });
const DISCORD_TOKEN = process.env.DISCORD_TOKEN; client.once("ready", () => {
const N8N_WEBHOOK = process.env.N8N_WEBHOOK; console.log(`✅ Ready! Logged in as ${client.user.tag}`);
});
client.on("messageCreate", async (message) => { client.on("messageCreate", async (message) => {
if (message.author.bot) return;
try { try {
const response = await fetch(N8N_WEBHOOK, { if (message.author.bot) return;
console.log(`📩 Message from ${message.author.tag} in ${message.guild ? message.guild.name : "DM"}: ${message.content}`);
const res = await fetch(N8N_WEBHOOK, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: message.content, user: message.author.username }) body: JSON.stringify({ text: message.content, user: message.author.username })
}); });
const data = await response.json(); const data = await res.json().catch(() => null);
console.log("↩️ n8n response raw:", data);
if (data.reply) { if (data && data.reply) {
await message.reply(data.reply); await message.reply(data.reply);
} else {
// fallback minimal log
console.log("⚠️ No 'reply' field in n8n response.");
} }
} catch (err) { } catch (err) {
console.error("Erreur:", err); console.error("🔴 Error in message handler:", err);
message.reply("⚠️ Erreur avec le chatbot.");
} }
}); });
client.login(DISCORD_TOKEN); process.on("unhandledRejection", (r) => {
console.error("UnhandledRejection:", r);
});
process.on("uncaughtException", (err) => {
console.error("UncaughtException:", err);
process.exit(1);
});
client.login(DISCORD_TOKEN).catch(err => {
console.error("Failed to login to Discord:", err);
process.exit(1);
});