Files
src
package.json
Code
4 634
src/index.js
import 'dotenv/config';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { tmpdir } from 'node:os';
import path from 'node:path';
import {
ActionRowBuilder,
AttachmentBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
Client,
EmbedBuilder,
GatewayIntentBits,
ModalBuilder,
PermissionFlagsBits,
REST,
Routes,
SlashCommandBuilder,
StringSelectMenuBuilder,
TextInputBuilder,
TextInputStyle
} from 'discord.js';
import {
AudioPlayerStatus,
VoiceConnectionStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
StreamType
} from '@discordjs/voice';
import ffmpegPath from 'ffmpeg-static';
import roleplayQuestions from './questions.js';
import { analyzeVideo, assessApplication, synthesizeSpeech } from './ai.js';
const token = process.env.DISCORD_TOKEN;
const clientId = process.env.CLIENT_ID;
const guildId = process.env.GUILD_ID;
if (!token || !clientId || !guildId) throw new Error('DISCORD_TOKEN, CLIENT_ID und GUILD_ID müssen gesetzt sein.');
const staffRoleName = process.env.STAFF_ROLE_NAME || '----⚒️Staff⚒️----';
const staffRoleId = process.env.STAFF_ROLE_ID;
const configuredApplicationRoleIds = (process.env.APPLICATION_ROLE_IDS || '').split(',').map(value => value.trim()).filter(Boolean).slice(0, 25);
const stateDirectory = path.resolve('data');
const stateFile = path.join(stateDirectory, 'applications.json');
let applications = {};
const voiceSessions = new Map();
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildVoiceStates] });
const commandDefinitions = [
new SlashCommandBuilder().setName('bewerbung').setDescription('Öffnet ein privates RP-Bewerbungsticket mit 50 Fragen.'),
new SlashCommandBuilder().setName('ticket').setDescription('Erstellt ein privates Support-Ticket.'),
new SlashCommandBuilder().setName('analyse-video').setDescription('Analysiert ein Video und meldet mögliche Auffälligkeiten.')
.addAttachmentOption(option => option.setName('video').setDescription('Zu prüfendes Video').setRequired(true)),
new SlashCommandBuilder().setName('kick').setDescription('Entfernt ein Mitglied vom Server.')
.addUserOption(option => option.setName('mitglied').setDescription('Mitglied').setRequired(true))
.addStringOption(option => option.setName('grund').setDescription('Grund').setMaxLength(400).setRequired(true)),
new SlashCommandBuilder().setName('timeout').setDescription('Gibt einem Mitglied einen Timeout.')
.addUserOption(option => option.setName('mitglied').setDescription('Mitglied').setRequired(true))
.addIntegerOption(option => option.setName('minuten').setDescription('Dauer in Minuten').setMinValue(1).setMaxValue(40320).setRequired(true))
.addStringOption(option => option.setName('grund').setDescription('Grund').setMaxLength(400).setRequired(true)),
new SlashCommandBuilder().setName('ban').setDescription('Bannt ein Mitglied vom Server.')
.addUserOption(option => option.setName('mitglied').setDescription('Mitglied').setRequired(true))
.addStringOption(option => option.setName('grund').setDescription('Grund').setMaxLength(400).setRequired(true)),
new SlashCommandBuilder().setName('rolle').setDescription('Gibt einem Mitglied eine Serverrolle.')
.addUserOption(option => option.setName('mitglied').setDescription('Mitglied').setRequired(true))
.addRoleOption(option => option.setName('rolle').setDescription('Zu vergebende Rolle').setRequired(true)),
new SlashCommandBuilder().setName('support-voice').setDescription('Tritt einem Support-Sprachkanal bei, verlässt ihn oder spricht Text.')
.addStringOption(option => option.setName('aktion').setDescription('Aktion').setRequired(true)
.addChoices({ name: 'Beitreten', value: 'join' }, { name: 'Verlassen', value: 'leave' }, { name: 'Sprechen', value: 'say' }))
.addStringOption(option => option.setName('text').setDescription('Gesprochener Text (max. 500 Zeichen)').setMaxLength(500))
].map(command => command.toJSON());
function getStaffRole(guild) {
return (staffRoleId && guild.roles.cache.get(staffRoleId)) || guild.roles.cache.find(role => role.name === staffRoleName);
}
function isStaff(interaction) {
const roles = interaction.member?.roles?.cache;
if (!roles) return false;
return (staffRoleId && roles.has(staffRoleId)) || roles.some(role => role.name === staffRoleName);
}
function safeName(value) {
return value.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 45) || 'mitglied';
}
async function saveApplications() {
await mkdir(stateDirectory, { recursive: true });
await writeFile(stateFile, JSON.stringify(applications, null, 2), 'utf8');
}
async function loadApplications() {
try {
applications = JSON.parse(await readFile(stateFile, 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') console.error('Bewerbungsdaten konnten nicht geladen werden:', error);
applications = {};
}
}
function privateChannelOverwrites(guild, userId) {
const overwrites = [
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: userId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.AttachFiles] },
{ id: client.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.ManageChannels] }
];
const staffRole = getStaffRole(guild);
if (staffRole) overwrites.push({ id: staffRole.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory] });
return overwrites;
}
function roleOptions(guild) {
return configuredApplicationRoleIds.map(id => guild.roles.cache.get(id)).filter(role => role && !role.managed && role.id !== guild.roles.everyone.id);
}
function applicationQuestionModal(index) {
const modal = new ModalBuilder().setCustomId(`application-answer:${index}`).setTitle(`RP-Bewerbung ${index + 1}/50`);
const answer = new TextInputBuilder()
.setCustomId('answer')
.setLabel(`Frage ${index + 1} von ${roleplayQuestions.length}`)
.setStyle(TextInputStyle.Paragraph)
.setPlaceholder(roleplayQuestions[index].slice(0, 100))
.setMinLength(10)
.setMaxLength(1000)
.setRequired(true);
modal.addComponents(new ActionRowBuilder().addComponents(answer));
return modal;
}
async function createApplication(interaction) {
const existing = Object.values(applications).find(app => app.applicantId === interaction.user.id && app.guildId === interaction.guildId);
if (existing) {
const channel = interaction.guild.channels.cache.get(existing.channelId);
if (channel) return interaction.reply({ content: `Du hast bereits eine offene Bewerbung: ${channel}`, ephemeral: true });
delete applications[existing.channelId];
}
const channel = await interaction.guild.channels.create({
name: `bewerbung-${safeName(interaction.user.username)}`,
type: ChannelType.GuildText,
topic: `application-owner:${interaction.user.id}`,
parent: process.env.APPLICATION_CATEGORY_ID || undefined,
permissionOverwrites: privateChannelOverwrites(interaction.guild, interaction.user.id)
});
applications[channel.id] = { applicantId: interaction.user.id, guildId: interaction.guildId, index: 0, answers: [], status: 'pending' };
await saveApplications();
const startButton = new ButtonBuilder().setCustomId('application-start').setLabel('Bewerbung starten').setStyle(ButtonStyle.Primary);
await channel.send({
content: `${interaction.user}, willkommen zur RP-Bewerbung. Beantworte alle 50 Situationen in deinen eigenen Worten. Das Team sieht deine Antworten; die KI erstellt nur eine unverbindliche Empfehlung.`,
components: [new ActionRowBuilder().addComponents(startButton)],
allowedMentions: { users: [interaction.user.id] }
});
await interaction.reply({ content: `Dein privates Bewerbungsticket wurde erstellt: ${channel}`, ephemeral: true });
}
async function createTicket(interaction) {
const existing = interaction.guild.channels.cache.find(channel => channel.type === ChannelType.GuildText && channel.topic === `ticket-owner:${interaction.user.id}`);
if (existing) return interaction.reply({ content: `Du hast bereits ein offenes Ticket: ${existing}`, ephemeral: true });
const channel = await interaction.guild.channels.create({
name: `ticket-${safeName(interaction.user.username)}`,
type: ChannelType.GuildText,
topic: `ticket-owner:${interaction.user.id}`,
parent: process.env.TICKET_CATEGORY_ID || undefined,
permissionOverwrites: privateChannelOverwrites(interaction.guild, interaction.user.id)
});
const close = new ButtonBuilder().setCustomId('ticket-close').setLabel('Ticket schließen').setStyle(ButtonStyle.Danger);
await channel.send({
content: `${interaction.user} — beschreibe dein Anliegen bitte möglichst genau. Ein Staff-Mitglied meldet sich hier.`,
components: [new ActionRowBuilder().addComponents(close)],
allowedMentions: { users: [interaction.user.id] }
});
await interaction.reply({ content: `Dein Support-Ticket wurde erstellt: ${channel}`, ephemeral: true });
}
async function handleApplicationButton(interaction) {
const app = applications[interaction.channelId];
if (!app || app.applicantId !== interaction.user.id || app.status !== 'pending') {
return interaction.reply({ content: 'Diese Bewerbungsaktion ist nicht für dich verfügbar.', ephemeral: true });
}
if (interaction.customId === 'application-start') {
return interaction.showModal(applicationQuestionModal(app.index));
}
return interaction.showModal(applicationQuestionModal(app.index));
}
async function completeApplication(interaction, app) {
app.status = 'review';
await saveApplications();
await interaction.reply({ content: 'Danke! Deine 50 Antworten wurden gespeichert und dem Staff-Team zur Prüfung vorgelegt.', ephemeral: true });
const channel = interaction.channel;
const roles = roleOptions(interaction.guild);
let assessment;
try {
assessment = await assessApplication(app.answers, roles.map(role => role.name));
} catch (error) {
console.error('Bewerbung konnte nicht automatisch eingeschätzt werden:', error);
assessment = {