Files
.gitignore
bot.js
commands.js
database.js
package.json
README.md
register.js
Code
7 331
bot.js
require('dotenv').config();
const { Client, GatewayIntentBits, PermissionFlagsBits, EmbedBuilder, AttachmentBuilder, MessageFlags } = require('discord.js');
const db = require('./database');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] });
const colors = { success: 0x2ecc71, error: 0xe74c3c, info: 0x3498db };
const embed = (kind, text) => new EmbedBuilder().setColor(colors[kind]).setDescription(text);
const idPattern = /^\d{17,20}$/;
async function audit(guild, text) {
console.log(`[${guild.id}] ${text}`);
const channelId = db.settings(guild.id).log_channel_id;
if (!channelId) return;
try {
const channel = await guild.channels.fetch(channelId);
if (!channel || !channel.isTextBased() || !channel.isSendable()) throw new Error('Channel not found or not sendable');
await channel.send({ embeds: [embed('info', text.slice(0, 4000))], allowedMentions: { parse: [] } });
} catch (error) { console.error(`[${guild.id}] Could not send audit log:`, error.message); }
}
async function roleCheck(guild, roleId) {
const role = await guild.roles.fetch(roleId);
if (!role) return { error: 'The configured role no longer exists.' };
const me = await guild.members.fetchMe();
if (!me.permissions.has(PermissionFlagsBits.ManageRoles)) return { error: 'The bot lacks Manage Roles.' };
if (role.id === guild.id) return { error: 'The @everyone role cannot be assigned.' };
if (role.managed) return { error: 'This is an integration-managed role and cannot be assigned by the bot.' };
if (me.roles.highest.comparePositionTo(role) <= 0) return { error: 'The bot’s highest role must be above the configured role.' };
return { role };
}
function validateBackup(data, guildId) {
if (!data || data.version !== 1 || data.guild_id !== guildId || !data.settings || !Array.isArray(data.assignments) || !Array.isArray(data.managers)) throw new Error('Invalid backup or backup belongs to another server.');
const { enabled, log_channel_id } = data.settings;
if (![0, 1].includes(enabled) || (log_channel_id !== null && !idPattern.test(log_channel_id))) throw new Error('Invalid backup settings.');
const users = new Set();
for (const row of data.assignments) {
if (!row || !idPattern.test(row.user_id) || !idPattern.test(row.role_id) || !idPattern.test(row.created_by) || typeof row.created_at !== 'string' || !Number.isFinite(Date.parse(row.created_at)) || users.has(row.user_id)) throw new Error('Invalid or duplicate assignment in backup.');
users.add(row.user_id);
}
const managers = new Set();
for (const user of data.managers) {
if (typeof user !== 'string' || !idPattern.test(user) || managers.has(user)) throw new Error('Invalid or duplicate manager in backup.');
managers.add(user);
}
}
async function readBackup(attachment) {
const max = 1024 * 1024;
if (attachment.size > max) throw new Error('Backup exceeds the 1 MB limit.');
const url = new URL(attachment.url);
if (url.protocol !== 'https:' || !['cdn.discordapp.com', 'media.discordapp.net'].includes(url.hostname)) throw new Error('Invalid attachment URL.');
const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(10000) });
if (!response.ok || !response.body) throw new Error('Could not download the backup.');
const chunks = [];
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > max) throw new Error('Backup exceeds the 1 MB limit.');
chunks.push(chunk);
}
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
catch { throw new Error('Backup is not valid JSON.'); }
}
client.once('clientReady', () => {
console.log(`Logged in as ${client.user.tag}`);
console.log('KODARI_READY');
});
client.on('error', error => console.error('Discord client error:', error));
client.on('guildMemberAdd', async member => {
try {
const assignment = db.get(member.guild.id, member.id);
if (!assignment || !db.settings(member.guild.id).enabled) return;
const check = await roleCheck(member.guild, assignment.role_id);
if (check.error) return await audit(member.guild, `Join assignment failed for user ${member.id}, role ${assignment.role_id}: ${check.error}`);
await member.roles.add(check.role, 'Configured user-specific join role');
await audit(member.guild, `Join assignment succeeded: user ${member.id}, role ${assignment.role_id}.`);
} catch (error) {
console.error(`Join assignment failed for ${member.id}:`, error);
await audit(member.guild, `Join assignment failed for user ${member.id}: ${error.message}`).catch(console.error);
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand() || interaction.commandName !== 'joinrole' || !interaction.inGuild()) return;
try {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const guild = interaction.guild;
const guildId = guild.id;
const actor = interaction.user.id;
const owner = actor === guild.ownerId;
const group = interaction.options.getSubcommandGroup(false);
const sub = interaction.options.getSubcommand();
const reply = (kind, text, extra = {}) => interaction.editReply({ embeds: [embed(kind, text)], allowedMentions: { parse: [] }, ...extra });
if (!owner && !db.isManager(guildId, actor)) return await reply('error', 'Only the server owner and authorized managers can use this command.');
if (!owner && (group === 'manager' || sub === 'restore')) return await reply('error', 'Only the server owner can manage managers or restore backups.');
if (group === 'manager') {
const user = interaction.options.getUser('user', true);
const changed = sub === 'add' ? db.addManager(guildId, user.id) : db.removeManager(guildId, user.id);
if (!changed) return await reply('info', sub === 'add' ? 'This user is already a manager.' : 'This user is not a manager.');
await audit(guild, `Manager ${sub}: user ${user.id}, actor ${actor}.`);
return await reply('success', `Manager ${sub === 'add' ? 'authorized' : 'removed'}: <@${user.id}>.`);
}
if (sub === 'add' || sub === 'edit') {
const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true);
const existing = db.get(guildId, user.id);
if (sub === 'add' && existing) return await reply('error', 'This user is already registered. Use `/joinrole edit`.');
if (sub === 'edit' && !existing) return await reply('error', 'This user is not registered. Use `/joinrole add`.');
if (role.id === guildId || role.managed) return await reply('error', 'The @everyone role and integration-managed roles cannot be assigned.');
if (sub === 'add') db.add(guildId, user.id, role.id, actor); else db.edit(guildId, user.id, role.id);
await audit(guild, `Assignment ${sub}: user ${user.id}, role ${role.id}, actor ${actor}.`);
const check = await roleCheck(guild, role.id);
return await reply('success', `Saved <@${user.id}> → <@&${role.id}>.${check.error ? `\nWarning: ${check.error}` : ''}`);
}
if (sub === 'remove') {
const user = interaction.options.getUser('user', true);
if (!db.remove(guildId, user.id)) return await reply('info', 'This user is not registered.');
await audit(guild, `Assignment removed: user ${user.id}, actor ${actor}.`);
return await reply('success', `Removed assignment for <@${user.id}>.`);
}
if (sub === 'check' || sub === 'test') {
const user = interaction.options.getUser('user', true);
const assignment = db.get(guildId, user.id);
if (!assignment) return await reply('info', `No assignment for <@${user.id}>.`);
if (sub === 'check') return await reply('info', `<@${user.id}> → <@&${assignment.role_id}>\nCreated by <@${assignment.created_by}> on ${assignment.created_at}.`);
const check = await roleCheck(guild, assignment.role_id);
if (check.error) return await reply('error', check.error);
return await reply('success', `The bot can assign <@&${assignment.role_id}> to <@${user.id}> when they join.${db.settings(guildId).enabled ? '' : '\nAutomatic assignments are currently disabled.'}`);
}
if (sub === 'list') {
const rows = db.list(guildId);
if (!rows.length) return await reply('info', 'No assignments configured.');
const lines = rows.map(row => `<@${row.user_id}> → <@&${row.role_id}>`);
const pages = [];
let page = '';
for (const line of lines) { if (page.length + line.length + 1 > 3800) { pages.push(page); page = ''; } page += `${line}\n`; }
if (page) pages.push(page);
const file = pages.length > 1 ? [new AttachmentBuilder(Buffer.from(lines.join('\n')), { name: 'assignments.txt' })] : [];
return await reply('info', pages[0] + (pages.length > 1 ? `\nShowing ${pages[0].trim().split('\n').length} of ${rows.length}; full list attached.` : ''), { files: file });
}
if (sub === 'enable' || sub === 'disable') {
db.setEnabled(guildId, sub === 'enable');
await audit(guild, `Automatic assignments ${sub}d by ${actor}.`);
return await reply('success', `Automatic assignments ${sub === 'enable' ? 'enabled' : 'disabled'}.`);
}
if (sub === 'log') {
const channel = interaction.options.getChannel('channel');
const old = db.settings(guildId).log_channel_id;
await audit(guild, `Logging channel changed from ${old || 'none'} to ${channel?.id || 'none'} by ${actor}.`);
db.setLogChannel(guildId, channel?.id || null);
if (channel && channel.id !== old) await audit(guild, `Logging channel set by ${actor}.`);
return await reply('success', channel ? `Logging channel set to <#${channel.id}>. Ensure I can view and send messages there.` : 'Logging channel disabled; events remain in console logs.');
}
if (sub === 'reload') {
db.reload();
await audit(guild, `Configuration reloaded by ${actor}.`);
return await reply('success', 'Configuration reloaded. Settings are read directly from SQLite.');
}
if (sub === 'info') {
const me = await guild.members.fetchMe();
const enabled = db.settings(guildId).enabled;
return await reply('info', `Automatic assignments: **${enabled ? 'enabled' : 'disabled'}**\nManage Roles: **${me.permissions.has(PermissionFlagsBits.ManageRoles) ? 'yes' : 'no'}**\nHighest bot role: <@&${me.roles.highest.id}> (position ${me.roles.highest.position})\nUse \`/joinrole test\` to check a specific role.`);
}
if (sub === 'backup') {
const data = JSON.stringify(db.backup(guildId), null, 2);
return await reply('info', 'Server configuration backup:', { files: [new AttachmentBuilder(Buffer.from(data), { name: 'joinrole-backup.json' })] });
}
if (sub === 'restore') {
const data = await readBackup(interaction.options.getAttachment('file', true));
validateBackup(data, guildId);
await audit(guild, `Configuration restore initiated by ${actor}.`);
db.restore(guildId, data);
await audit(guild, `Configuration restored by ${actor}: ${data.assignments.length} assignments, ${data.managers.length} managers.`);
return await reply('success', `Restored ${data.assignments.length} assignments and ${data.managers.length} managers.`);
}
} catch (error) {
console.error('Joinrole command failed:', error);
const payload = { embeds: [embed('error', 'The command failed. Check the bot logs or verify the provided backup and permissions.')], allowedMentions: { parse: [] } };
try { if (interaction.deferred || interaction.replied) await interaction.editReply(payload); else await interaction.reply({ ...payload, flags: MessageFlags.Ephemeral }); }
catch (replyError) { console.error('Could not send command error:', replyError); }
}
});
if (!process.env.DISCORD_TOKEN) {
console.error('Set DISCORD_TOKEN in .env');
process.exitCode = 1;
} else {
client.login(process.env.DISCORD_TOKEN).catch(error => { console.error('Login failed:', error); process.exitCode = 1; });
}