Files
scripts
src
.gitignore
index.js
package.json
README.md
Code
16 1,490
index.js
require('dotenv').config();
const fs = require('node:fs');
const path = require('node:path');
const { Client, GatewayIntentBits, Partials, AuditLogEvent, PermissionFlagsBits } = require('discord.js');
const store = require('./src/store');
const requiredToken = process.env.DISCORD_TOKEN;
if (!requiredToken) {
console.error('Configure DISCORD_TOKEN no ambiente antes de iniciar o bot.');
process.exit(1);
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.MessageContent
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction]
});
const commandFiles = fs.readdirSync(path.join(__dirname, 'src', 'commands'))
.filter(file => file.endsWith('.js'))
.sort();
const commands = commandFiles.map(file => require(path.join(__dirname, 'src', 'commands', file)));
const registeredCommands = commands.flatMap(module => Array.isArray(module.data)
? module.data.map(data => ({ ...module, data }))
: [module]);
const commandMap = new Map(registeredCommands.map(command => [command.data.name, command]));
client.once('clientReady', async readyClient => {
try {
await readyClient.application.commands.set(registeredCommands.map(command => command.data));
console.log(`GUARD BOT conectado como ${readyClient.user.tag}; ${registeredCommands.length} comandos publicados.`);
} catch (error) {
console.error('Falha ao registrar os comandos Slash:', error);
}
console.log('KODARI_READY');
});
client.on('interactionCreate', async interaction => {
try {
if (interaction.isChatInputCommand()) {
const command = commandMap.get(interaction.commandName);
if (!command) {
await interaction.reply({ content: 'Este comando não está disponível.', ephemeral: true });
return;
}
await command.execute(interaction, client);
if (interaction.deferred && !interaction.replied) {
await interaction.editReply({ content: 'O comando não enviou uma resposta. Tente novamente.' });
} else if (!interaction.replied) {
await interaction.reply({ content: 'O comando não enviou uma resposta. Tente novamente.', ephemeral: true });
}
return;
}
if (interaction.isButton() || interaction.isStringSelectMenu() || interaction.isModalSubmit()) {
let handled = false;
for (const command of commands) {
if (command.handleComponent && await command.handleComponent(interaction, client)) {
handled = true;
break;
}
}
if (interaction.deferred && !interaction.replied) {
await interaction.editReply({ content: 'A ação não enviou uma resposta. Tente novamente.' });
} else if (!interaction.replied) {
await interaction.reply({
content: handled ? 'A ação não enviou uma resposta. Tente novamente.' : 'Esta interação não está mais disponível.',
ephemeral: true
});
}
}
} catch (error) {
console.error(`Erro em interação ${interaction.commandName || interaction.customId}:`, error);
const message = { content: 'Ocorreu um erro ao processar esta ação. Tente novamente.', ephemeral: true };
if (interaction.deferred || interaction.replied) await interaction.followUp(message).catch(() => {});
else await interaction.reply(message).catch(() => {});
}
});
client.on('guildMemberAdd', async member => {
const settings = store.getGuild(member.guild.id);
const welcomeChannel = settings.welcomeChannel && member.guild.channels.cache.get(settings.welcomeChannel);
if (welcomeChannel?.isTextBased()) {
const { infoEmbed } = require('./src/ui');
await welcomeChannel.send({ embeds: [infoEmbed(`Bem-vindo(a), ${member.user.username}!`, `Seja bem-vindo(a) a **${member.guild.name}**.`)] }).catch(() => {});
}
const autoRole = settings.autoRole && member.guild.roles.cache.get(settings.autoRole);
if (autoRole) await member.roles.add(autoRole, 'Cargo automático configurado').catch(() => {});
await logEvent(member.guild, settings, `📥 ${member.user.tag} entrou no servidor.`);
});
client.on('guildMemberRemove', async member => {
const settings = store.getGuild(member.guild.id);
const leaveChannel = settings.leaveChannel && member.guild.channels.cache.get(settings.leaveChannel);
if (leaveChannel?.isTextBased()) await leaveChannel.send({ content: `👋 **${member.user.tag}** saiu do servidor.` }).catch(() => {});
await logEvent(member.guild, settings, `📤 ${member.user.tag} saiu do servidor.`);
});
const destructiveActions = new Set([
AuditLogEvent.ChannelDelete,
AuditLogEvent.RoleDelete,
AuditLogEvent.MemberBanAdd,
AuditLogEvent.MemberKick
]);
const auditLabels = new Map([
[AuditLogEvent.ChannelCreate, 'canal criado'],
[AuditLogEvent.ChannelUpdate, 'canal alterado'],
[AuditLogEvent.ChannelDelete, 'canal apagado'],
[AuditLogEvent.RoleCreate, 'cargo criado'],
[AuditLogEvent.RoleUpdate, 'cargo alterado'],
[AuditLogEvent.RoleDelete, 'cargo apagado'],
[AuditLogEvent.MemberBanAdd, 'membro banido'],
[AuditLogEvent.MemberKick, 'membro expulso'],
[AuditLogEvent.MemberRoleUpdate, 'cargos de membro alterados'],
[AuditLogEvent.MemberUpdate, 'membro atualizado']
]);
const auditBuckets = new Map();
client.on('guildAuditLogEntryCreate', async (entry, guild) => {
const settings = store.getGuild(guild.id);
const executorId = entry.executorId;
const label = auditLabels.get(entry.action);
if (label) await logEvent(guild, settings, `📋 Registro administrativo: ${label}${executorId ? ` por <@${executorId}>` : ''}.`);
if (!settings.antinuke.enabled || !destructiveActions.has(entry.action)) return;
if (!executorId || executorId === guild.ownerId || executorId === client.user.id || settings.antinuke.whitelist.includes(executorId)) return;
const key = `${guild.id}:${executorId}`;
const now = Date.now();
const recent = (auditBuckets.get(key) || []).filter(item => now - item.at < 10000 && item.id !== entry.id);
recent.push({ id: entry.id, at: now });
auditBuckets.set(key, recent);
if (recent.length < 4) return;
auditBuckets.delete(key);
try {
const executor = await guild.members.fetch(executorId);
if (executor.bannable && guild.members.me?.permissions.has(PermissionFlagsBits.BanMembers)) {
await guild.members.ban(executorId, { reason: 'GUARD BOT AntiNuke: 4 ações destrutivas em 10 segundos.' });
await logEvent(guild, settings, `🚨 AntiNuke: ${executor.user.tag} foi banido após 4 ações administrativas destrutivas em 10 segundos.`);
} else {
await logEvent(guild, settings, `🚨 AntiNuke detectou 4 ações destrutivas de <@${executorId}>, mas não conseguiu aplicar o banimento. Confira permissões e hierarquia.`);
}
} catch (error) {
console.error('Falha na resposta AntiNuke:', error);
await logEvent(guild, settings, `🚨 AntiNuke detectou atividade destrutiva de <@${executorId}>, mas a ação de proteção falhou.`);
}
});
client.on('messageDelete', async message => {
if (!message.guild || message.author?.bot) return;
const settings = store.getGuild(message.guild.id);
await logEvent(message.guild, settings, `🗑️ Mensagem apagada de ${message.author?.tag || 'usuário desconhecido'} em <#${message.channel.id}>${message.content ? `: ${message.content.slice(0, 1200)}` : '.'}`);
});
client.on('messageUpdate', async (before, after) => {
if (!after.guild || after.author?.bot || before.content === after.content) return;
const settings = store.getGuild(after.guild.id);
await logEvent(after.guild, settings, `✏️ Mensagem editada por ${after.author?.tag || 'usuário'} em <#${after.channel.id}>. [Abrir mensagem](${after.url})`);
});
async function updateReactionRole(reaction, user, adding) {
if (user.bot) return;
if (reaction.partial) reaction = await reaction.fetch().catch(() => null);
if (!reaction?.message.guild) return;
const guild = reaction.message.guild;
const settings = store.getGuild(guild.id);
const emojiKey = reaction.emoji.id || reaction.emoji.name;
const roleId = settings.reactionRoles?.[`${reaction.message.channel.id}:${reaction.message.id}:${emojiKey}`];
const role = roleId && guild.roles.cache.get(roleId);
if (!role?.editable) return;
const member = guild.members.cache.get(user.id) || await guild.members.fetch(user.id).catch(() => null);
if (!member) return;
if (adding && !member.roles.cache.has(role.id)) await member.roles.add(role, 'Cargo por reação').catch(() => {});
if (!adding && member.roles.cache.has(role.id)) await member.roles.remove(role, 'Cargo por reação removida').catch(() => {});
}
client.on('messageReactionAdd', (reaction, user) => updateReactionRole(reaction, user, true));
client.on('messageReactionRemove', (reaction, user) => updateReactionRole(reaction, user, false));
const spamBuckets = new Map();
client.on('messageCreate', async message => {
if (!message.guild || message.author.bot || !message.member) return;
const settings = store.getGuild(message.guild.id);
const automod = settings.automod;
if (message.member.permissions.has('ManageMessages')) return;
if (automod.enabled) {
const now = Date.now();
const key = `${message.guild.id}:${message.author.id}`;
const bucket = (spamBuckets.get(key) || []).filter(time => now - time < 6000);
bucket.push(now);
spamBuckets.set(key, bucket);
if (automod.spam && bucket.length >= automod.spamLimit) {
await message.delete().catch(() => {});
await message.channel.send({ content: `${message.author}, reduza a frequência das mensagens.` }).then(msg => setTimeout(() => msg.delete().catch(() => {}), 5000)).catch(() => {});