Files
frielith_discord_bot/bot.js
2025-09-06 12:42:15 +00:00

65 lines
1.8 KiB
JavaScript

import { Client, GatewayIntentBits } from "discord.js";
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({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.once("ready", () => {
console.log(`✅ Ready! Logged in as ${client.user.tag}`);
});
client.on("messageCreate", async (message) => {
try {
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",
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);
if (data && data.reply) {
await message.reply(data.reply);
} else {
// fallback minimal log
console.log("⚠️ No 'reply' field in n8n response.");
}
} catch (err) {
console.error("🔴 Error in message handler:", err);
}
});
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);
});