Files
src
deploy-commands.js
package.json
Code
5 1,366
src/index.js
require('dotenv').config();
const http = require('node:http');
const crypto = require('node:crypto');
const {
Client,
Events,
GatewayIntentBits,
PermissionFlagsBits
} = require('discord.js');
const { loadGuild, saveGuild } = require('./storage');
const { handleCommand, handleButton, UserError } = require('./commands');
if (!process.env.DISCORD_TOKEN) throw new Error('DISCORD_TOKEN fehlt.');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.once(Events.ClientReady, readyClient => {
console.log(`Eingeloggt als ${readyClient.user.tag} · ${readyClient.guilds.cache.size} Server`);
});
client.on(Events.GuildMemberAdd, async member => {
try {
const data = loadGuild(member.guild.id);
const roleId = data.settings.roles.autorolle;
if (data.settings.autoroleEnabled && roleId) {
const role = await member.guild.roles.fetch(roleId).catch(() => null);
if (role && member.guild.members.me?.permissions.has(PermissionFlagsBits.ManageRoles)) {
await member.roles.add(role, 'Konfigurierte Autorolle');
}
}
} catch (error) {
console.error(`Autorolle für ${member.user.tag} fehlgeschlagen:`, error.message);
}
});
client.on(Events.InteractionCreate, async interaction => {
try {
if (interaction.isButton()) {
await handleButton(interaction);
return;
}
if (!interaction.isChatInputCommand()) return;
await handleCommand(interaction);
} catch (error) {
const message = error instanceof UserError ? error.message : 'Beim Ausführen ist ein Fehler aufgetreten. Prüfe Bot-Berechtigungen und Konfiguration.';
if (!(error instanceof UserError)) console.error('Command-Fehler:', error);
const payload = { content: `⚠️ ${message}`, ephemeral: true };
if (interaction.deferred || interaction.replied) await interaction.followUp(payload).catch(() => {});
else await interaction.reply(payload).catch(() => {});
}
});
function tokenMatches(request) {
const expected = process.env.DASHBOARD_TOKEN;
const supplied = request.headers.authorization?.replace(/^Bearer\s+/i, '');
if (!expected || !supplied) return false;
const expectedBuffer = Buffer.from(expected);
const suppliedBuffer = Buffer.from(supplied);
return expectedBuffer.length === suppliedBuffer.length && crypto.timingSafeEqual(expectedBuffer, suppliedBuffer);
}
function sendJson(response, status, body) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
response.end(JSON.stringify(body));
}
function readBody(request) {
return new Promise((resolve, reject) => {
let body = '';
request.on('data', chunk => {
body += chunk;
if (body.length > 65536) reject(new Error('Request body too large'));
});
request.on('end', () => {
try { resolve(JSON.parse(body || '{}')); } catch { reject(new Error('Invalid JSON')); }
});
request.on('error', reject);
});
}
const dashboardFields = {
channels: new Set(['logs', 'status', 'applications', 'support', 'announcements', 'feedback', 'meetings', 'events']),
roles: new Set(['team', 'support', 'management', 'autorolle']),
texts: new Set(['rules', 'announcement_title', 'servernews_title', 'wartung_title', 'support_title'])
};
async function updateDashboardSettings(guildId, body) {
if (!body || typeof body !== 'object' || !body.settings || typeof body.settings !== 'object') {
throw new Error('Erwartet wird ein Objekt mit settings.');
}
const data = loadGuild(guildId);
const incoming = body.settings;
for (const section of ['channels', 'roles', 'texts']) {
if (incoming[section] === undefined) continue;
if (!incoming[section] || typeof incoming[section] !== 'object' || Array.isArray(incoming[section])) throw new Error(`Ungültiger Abschnitt: ${section}`);
for (const [key, value] of Object.entries(incoming[section])) {
if (!dashboardFields[section].has(key)) throw new Error(`Nicht unterstütztes Feld: ${section}.${key}`);
if (typeof value !== 'string' && value !== null) throw new Error(`${section}.${key} muss Text oder null sein.`);
if (typeof value === 'string' && value.length > 1000) throw new Error(`${section}.${key} ist zu lang.`);
data.settings[section][key] = value;
}
}
if (incoming.embedColor !== undefined) {
if (typeof incoming.embedColor !== 'string' || !/^#[0-9a-f]{6}$/i.test(incoming.embedColor)) throw new Error('embedColor muss ein Hex-Farbwert wie #5865F2 sein.');
data.settings.embedColor = incoming.embedColor;
}
if (incoming.status !== undefined) {
if (!incoming.status || typeof incoming.status !== 'object' || Array.isArray(incoming.status)) throw new Error('status muss ein Objekt sein.');
for (const key of ['title', 'text', 'owner', 'playerCount', 'serverCode']) {
if (incoming.status[key] === undefined) continue;
if (typeof incoming.status[key] !== 'string' || incoming.status[key].length > 1000) throw new Error(`status.${key} muss Text mit höchstens 1000 Zeichen sein.`);
data.settings.status[key] = incoming.status[key];
}
}
saveGuild(guildId, data);
return data.settings;
}
function startDashboardApi() {
const server = http.createServer(async (request, response) => {
const url = new URL(request.url, 'http://localhost');
if (url.pathname === '/health' && request.method === 'GET') return sendJson(response, 200, { online: true, botReady: client.isReady() });
const match = url.pathname.match(/^\/api\/guild\/(\d+)\/config$/);
if (!match) return sendJson(response, 404, { error: 'Not found' });
if (!tokenMatches(request)) return sendJson(response, 401, { error: 'Unauthorized' });
const guildId = match[1];
try {
if (request.method === 'GET') {
const guild = await client.guilds.fetch(guildId).catch(() => null);
if (!guild) return sendJson(response, 404, { error: 'Guild not found' });
return sendJson(response, 200, { guildId, settings: loadGuild(guildId).settings });
}
if (request.method === 'PATCH' || request.method === 'PUT') {
const body = await readBody(request);
const settings = await updateDashboardSettings(guildId, body);
const data = loadGuild(guildId);
data.actionHistory.unshift({ id: crypto.randomUUID().slice(0, 8), command: 'dashboard/api', details: 'Dashboard-Konfiguration aktualisiert', actor: { id: 'dashboard', tag: 'Dashboard API' }, at: new Date().toISOString() });
saveGuild(guildId, data);
return sendJson(response, 200, { guildId, settings });
}
response.setHeader('Allow', 'GET, PATCH, PUT');
return sendJson(response, 405, { error: 'Method not allowed' });
} catch (error) {
return sendJson(response, error.message === 'Invalid JSON' ? 400 : 400, { error: error.message });
}
});
const port = Number(process.env.PORT || process.env.API_PORT || 3000);
server.listen(port, '0.0.0.0', () => console.log(`Dashboard-API hört auf Port ${port}`));
server.on('error', error => console.error('Dashboard-API-Fehler:', error));
}
startDashboardApi();
client.login(process.env.DISCORD_TOKEN);