Files
.gitignore
bot-hosting.json
bot.js
config.json
package.json
README.md
Code
6 384
bot.js
require('dotenv').config();
const crypto = require('node:crypto');
const express = require('express');
const {
Client,
GatewayIntentBits,
PermissionsBitField,
SlashCommandBuilder
} = require('discord.js');
const {
entersState,
getVoiceConnection,
joinVoiceChannel,
VoiceConnectionStatus
} = require('@discordjs/voice');
const config = require('./config.json');
if (!process.env.DISCORD_TOKEN) {
throw new Error('DISCORD_TOKEN is required. Set it in your environment or .env file.');
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates
]
});
const recentMessages = new Map();
const commands = [
new SlashCommandBuilder()
.setName('faq')
.setDescription('Find an answer in the configured FAQ.')
.addStringOption(option => option
.setName('question')
.setDescription('What would you like to know?')
.setRequired(true)
.setMaxLength(150)),
new SlashCommandBuilder()
.setName('ask')
.setDescription('Ask the AI assistant a server-related question.')
.addStringOption(option => option
.setName('question')
.setDescription('What would you like to know?')
.setRequired(true)
.setMaxLength(500)),
new SlashCommandBuilder()
.setName('voice')
.setDescription('Manage the bot’s silent voice connection.')
.addSubcommand(subcommand => subcommand
.setName('join')
.setDescription('Join your current voice channel silently.'))
.addSubcommand(subcommand => subcommand
.setName('leave')
.setDescription('Leave the voice channel.'))
].map(command => command.toJSON());
client.once('clientReady', async () => {
try {
await client.application.commands.set(commands);
console.info(`Logged in as ${client.user.tag}; slash commands registered.`);
} catch (error) {
console.error('Could not register slash commands:', error);
}
console.log('KODARI_READY');
});
client.on('guildMemberAdd', async member => {
const roleId = process.env.DEFAULT_ROLE_ID?.trim();
if (!roleId) return;
try {
const role = await member.guild.roles.fetch(roleId);
if (!role) {
console.warn(`Configured default role ${roleId} was not found in ${member.guild.name}.`);
return;
}
await member.roles.add(role, 'Default role for new members');
} catch (error) {
console.error(`Could not assign the default role to ${member.user.tag}:`, error);
}
});
client.on('messageCreate', async message => {
if (!message.guild || message.author.bot) return;
const content = message.content.toLowerCase();
const containsBlockedWord = (config.badWords || []).some(word => {
const normalizedWord = String(word).trim().toLowerCase();
return normalizedWord && content.includes(normalizedWord);
});
const containsInvite = /(?:https?:\/\/)?(?:www\.)?(?:discord\.gg|discord(?:app)?\.com\/invite)\/[a-z0-9-]+/i.test(message.content);
if (containsBlockedWord || containsInvite) {
try {
await message.delete();
console.info(`Removed filtered message from ${message.author.tag} in ${message.guild.name}.`);
} catch (error) {
console.error('Could not remove a filtered message. Check Manage Messages permission:', error);
}
return;
}
const key = `${message.guild.id}:${message.author.id}`;
const now = Date.now();
const recent = (recentMessages.get(key) || []).filter(entry => now - entry.time < 8000);
recent.push({ time: now, content });
recentMessages.set(key, recent);
if (recent.length >= 6) {
recentMessages.delete(key);
try {
await message.delete();
if (message.member?.moderatable) {
await message.member.timeout(10 * 60 * 1000, 'Automatic spam protection');
}
console.info(`Applied spam protection to ${message.author.tag} in ${message.guild.name}.`);
} catch (error) {
console.error('Could not apply spam protection. Check Manage Messages and Moderate Members permissions:', error);
}
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
try {
if (interaction.commandName === 'faq') {
const question = interaction.options.getString('question', true).toLowerCase();
const match = (config.faqs || []).find(faq =>
(faq.keywords || []).some(keyword => question.includes(String(keyword).toLowerCase()))
);
await interaction.reply({
content: match?.answer || 'I could not find a matching FAQ. Try `/ask` or contact a moderator.',
ephemeral: true
});
return;
}
if (interaction.commandName === 'ask') {
await interaction.deferReply();
const answer = await askGemini(interaction.options.getString('question', true));
await interaction.editReply(answer);
return;
}
if (interaction.commandName === 'voice') {
if (!interaction.guild) {
await interaction.reply({ content: 'This command can only be used in a server.', ephemeral: true });
return;
}
if (interaction.options.getSubcommand() === 'join') {
const channel = interaction.member.voice?.channel;
if (!channel) {
await interaction.reply({ content: 'Join a voice channel first, then run `/voice join`.', ephemeral: true });
return;
}
if (!channel.permissionsFor(client.user)?.has(PermissionsBitField.Flags.Connect)) {
await interaction.reply({ content: 'I need the Connect permission for that voice channel.', ephemeral: true });
return;
}
getVoiceConnection(interaction.guild.id)?.destroy();
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
selfDeaf: true,
selfMute: true
});
connection.on('error', error => console.error('Voice connection error:', error));
await entersState(connection, VoiceConnectionStatus.Ready, 15_000);
await interaction.reply({ content: 'Joined silently. No audio is played or received.', ephemeral: true });
return;
}
const connection = getVoiceConnection(interaction.guild.id);
if (!connection) {
await interaction.reply({ content: 'I am not in a voice channel.', ephemeral: true });
return;
}
connection.destroy();
await interaction.reply({ content: 'Left the voice channel.', ephemeral: true });
}
} catch (error) {
console.error(`Error handling /${interaction.commandName}:`, error);
const response = { content: 'Something went wrong. Please try again later.', ephemeral: true };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(response).catch(() => {});
} else {
await interaction.reply(response).catch(() => {});
}
}
});