Skip to content

Commit bc3e71c

Browse files
committed
trying to get Logs done
1 parent cbd43d9 commit bc3e71c

9 files changed

Lines changed: 410 additions & 4 deletions

File tree

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType } = require("discord.js");
2+
const Database = require("../../utils/database");
3+
4+
module.exports = {
5+
data: new SlashCommandBuilder()
6+
.setName("message-logs")
7+
.setDescription("📝 Configure message logging settings for the server.")
8+
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
9+
.addSubcommand(subcommand =>
10+
subcommand
11+
.setName("set")
12+
.setDescription("Sets the channel for logging messages. Leave empty to disable.")
13+
.addChannelOption(option =>
14+
option.setName("channel")
15+
.setDescription("The text channel to send logs to.")
16+
.addChannelTypes(ChannelType.GuildText)
17+
.setRequired(false) // Not required, to allow disabling
18+
)
19+
)
20+
.addSubcommandGroup(group =>
21+
group
22+
.setName("exempt")
23+
.setDescription("Exempt users or roles from message logging.")
24+
.addSubcommand(subcommand =>
25+
subcommand
26+
.setName("add")
27+
.setDescription("Add a user or role to the exemption list.")
28+
.addUserOption(option => option.setName("user").setDescription("The user to exempt."))
29+
.addRoleOption(option => option.setName("role").setDescription("The role to exempt."))
30+
)
31+
.addSubcommand(subcommand =>
32+
subcommand
33+
.setName("remove")
34+
.setDescription("Remove a user or role from the exemption list.")
35+
.addUserOption(option => option.setName("user").setDescription("The user to un-exempt."))
36+
.addRoleOption(option => option.setName("role").setDescription("The role to un-exempt."))
37+
)
38+
.addSubcommand(subcommand =>
39+
subcommand
40+
.setName("list")
41+
.setDescription("List all exempted users and roles.")
42+
)
43+
),
44+
cooldown: 5,
45+
async execute(interaction, client) {
46+
const db = await Database.getInstance();
47+
const subcommandGroup = interaction.options.getSubcommandGroup();
48+
const subcommand = interaction.options.getSubcommand();
49+
50+
await interaction.deferReply({ ephemeral: true });
51+
52+
if (!subcommandGroup) { // Handling the 'set' subcommand
53+
const channel = interaction.options.getChannel("channel");
54+
try {
55+
await db.updateServerConfig(interaction.guild.id, {
56+
messageLogChannelId: channel ? channel.id : null,
57+
});
58+
const embed = new EmbedBuilder()
59+
.setColor(client.colors.success)
60+
.setTitle("✅ Log Channel Updated")
61+
.setDescription(channel ? `Message logs will now be sent to ${channel}.` : "Message logging has been disabled.")
62+
await interaction.editReply({ embeds: [embed] });
63+
} catch (error) {
64+
console.error("Error in /message-logs set:", error);
65+
await interaction.editReply({ content: "An error occurred while updating the settings." });
66+
}
67+
} else if (subcommandGroup === "exempt") {
68+
const user = interaction.options.getUser("user");
69+
const role = interaction.options.getRole("role");
70+
71+
if (subcommand === "add") {
72+
if (!user && !role) return interaction.editReply({ content: "You must specify a user or a role to add." });
73+
let update = {};
74+
if (user) update.$addToSet = { messageLogExemptUsers: user.id };
75+
if (role) update.$addToSet = { ...update.$addToSet, messageLogExemptRoles: role.id };
76+
77+
await db.updateServerConfig(interaction.guild.id, update);
78+
await interaction.editReply({ content: `Successfully added ${user || ""} ${role || ""} to the exemption list.` });
79+
80+
} else if (subcommand === "remove") {
81+
if (!user && !role) return interaction.editReply({ content: "You must specify a user or a role to remove." });
82+
let update = {};
83+
if (user) update.$pull = { messageLogExemptUsers: user.id };
84+
if (role) update.$pull = { ...update.$pull, messageLogExemptRoles: role.id };
85+
86+
await db.updateServerConfig(interaction.guild.id, update);
87+
await interaction.editReply({ content: `Successfully removed ${user || ""} ${role || ""} from the exemption list.` });
88+
89+
} else if (subcommand === "list") {
90+
const config = await db.serverConfig.findOne({ guildId: interaction.guild.id });
91+
const users = config.messageLogExemptUsers?.map(id => `<@${id}>`).join("\n") || "None";
92+
const roles = config.messageLogExemptRoles?.map(id => `<@&${id}>`).join("\n") || "None";
93+
94+
const embed = new EmbedBuilder()
95+
.setColor(client.colors.primary)
96+
.setTitle("📜 Message Log Exemptions")
97+
.addFields(
98+
{ name: "Exempted Users", value: users, inline: true },
99+
{ name: "Exempted Roles", value: roles, inline: true }
100+
);
101+
await interaction.editReply({ embeds: [embed] });
102+
}
103+
}
104+
},
105+
};

commands/server-logs/userlogs.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType } = require("discord.js");
2+
const Database = require("../../utils/database");
3+
4+
module.exports = {
5+
data: new SlashCommandBuilder()
6+
.setName("user-logs")
7+
.setDescription("👤 Set the channel for logging user joins and leaves.")
8+
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
9+
.addChannelOption(option =>
10+
option.setName("channel")
11+
.setDescription("The text channel to send user logs to. Leave empty to disable.")
12+
.addChannelTypes(ChannelType.GuildText)
13+
.setRequired(false)
14+
),
15+
cooldown: 10,
16+
async execute(interaction, client) {
17+
await interaction.deferReply({ ephemeral: true });
18+
19+
const db = await Database.getInstance();
20+
const channel = interaction.options.getChannel("channel");
21+
22+
try {
23+
// This method seems to work for updating, so we'll keep it.
24+
// The error was in reading the config, not writing it.
25+
await db.updateServerConfig(interaction.guild.id, {
26+
userLogChannelId: channel ? channel.id : null,
27+
});
28+
29+
const embed = new EmbedBuilder()
30+
.setColor(client.colors.success)
31+
.setTitle("✅ User Log Channel Updated")
32+
.setDescription(channel
33+
? `User join and leave logs will now be sent to ${channel}.`
34+
: "User logging has been disabled."
35+
)
36+
.setTimestamp();
37+
38+
await interaction.editReply({ embeds: [embed] });
39+
40+
} catch (error) {
41+
console.error("Error setting user log channel:", error);
42+
const errorEmbed = new EmbedBuilder()
43+
.setColor(client.colors.error)
44+
.setTitle("❌ Database Error")
45+
.setDescription("Failed to update the user log channel settings.");
46+
47+
await interaction.editReply({ embeds: [errorEmbed] });
48+
}
49+
},
50+
};

events/guildMemberAdd.js

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const { Events, EmbedBuilder, AttachmentBuilder } = require("discord.js");
22
const Database = require("../utils/database");
33
const { checkRaidDetection } = require("../commands/antimodules/antiraid");
4+
const { addToQueue } = require("../utils/logQueue"); // <-- ADD THIS LINE
45

56
module.exports = {
67
name: Events.GuildMemberAdd,
@@ -20,9 +21,12 @@ module.exports = {
2021
console.error("❌ Error checking anti-raid:", error);
2122
}
2223

24+
// This variable will hold the config to be reused
25+
let config;
26+
const db = Database.getInstance();
27+
2328
// 🎂 Check for birthday today
2429
try {
25-
const db = Database.getInstance();
2630
const today = new Date();
2731
const birthdayUsers = await db.Birthday.find({
2832
guildId: member.guild.id,
@@ -39,7 +43,7 @@ module.exports = {
3943

4044
if (todaysBirthdays.length > 0) {
4145
// Check if birthday announcements are enabled
42-
const config = await db.ServerConfig.findOne({
46+
config = await db.ServerConfig.findOne({
4347
guildId: member.guild.id,
4448
});
4549
if (config?.birthdayEnabled && config?.birthdayChannelId) {
@@ -150,9 +154,41 @@ module.exports = {
150154
}
151155
}
152156

153-
// 📊 Log member join
157+
// --- USER LOG LOGIC ---
158+
try {
159+
// Fetch config if it hasn't been fetched yet
160+
if (!config) {
161+
// CORRECTED LINE: Used 'db.serverConfig' with a lowercase 's'
162+
config = await db.serverConfig.findOne({ guildId: member.guild.id });
163+
}
164+
165+
if (config && config.userLogChannelId) {
166+
const logChannel = await member.guild.channels.fetch(config.userLogChannelId).catch(() => null);
167+
if (logChannel) {
168+
const accountAge = Math.floor(member.user.createdAt.getTime() / 1000);
169+
const logEmbed = new EmbedBuilder()
170+
.setColor(client.colors.success)
171+
.setAuthor({ name: member.user.tag, iconURL: member.user.displayAvatarURL() })
172+
.setTitle("📥 Member Joined")
173+
.setDescription(`${member.user} has joined the server.`)
174+
.addFields(
175+
{ name: 'Account Created', value: `<t:${accountAge}:R>`, inline: true },
176+
{ name: 'Total Members', value: `${member.guild.memberCount}`, inline: true }
177+
)
178+
.setFooter({ text: `User ID: ${member.user.id}` })
179+
.setTimestamp();
180+
181+
addToQueue(logChannel, logEmbed, client);
182+
}
183+
}
184+
} catch (error) {
185+
console.error("❌ Error sending user join log:", error);
186+
}
187+
188+
189+
// 📊 Log member join to console
154190
console.log(
155191
`👋 ${member.user.tag} joined ${member.guild.name} (${member.guild.memberCount} members)`
156192
);
157193
},
158-
};
194+
};

events/guildMemberRemove.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
const { Events, EmbedBuilder, AuditLogEvent } = require("discord.js");
2+
const Database = require("../utils/database");
3+
const { addToQueue } = require("../utils/logQueue");
4+
5+
module.exports = {
6+
name: Events.GuildMemberRemove,
7+
async execute(member, client) {
8+
if (!member.guild) return;
9+
10+
try {
11+
const db = await Database.getInstance();
12+
// CORRECTED LINE: Used 'db.serverConfig'
13+
const config = await db.serverConfig.findOne({ guildId: member.guild.id });
14+
15+
if (!config || !config.userLogChannelId) return;
16+
17+
const logChannel = await member.guild.channels.fetch(config.userLogChannelId).catch(() => null);
18+
if (!logChannel) return;
19+
20+
let reason = "left the server.";
21+
let moderator = "N/A";
22+
23+
const fetchedLogs = await member.guild.fetchAuditLogs({
24+
limit: 1,
25+
type: AuditLogEvent.MemberKick,
26+
}).catch(() => null);
27+
28+
const kickLog = fetchedLogs?.entries.first();
29+
30+
if (kickLog && kickLog.target.id === member.id && kickLog.createdAt > Date.now() - 5000) {
31+
reason = `was kicked. Reason: ${kickLog.reason || "Not specified."}`;
32+
moderator = kickLog.executor.tag;
33+
}
34+
35+
const logEmbed = new EmbedBuilder()
36+
.setColor(client.colors.error)
37+
.setAuthor({ name: member.user.tag, iconURL: member.user.displayAvatarURL() })
38+
.setTitle("📤 Member Left")
39+
.setDescription(`${member.user} ${reason}`)
40+
.addFields({ name: 'Moderator', value: moderator, inline: true })
41+
.setFooter({ text: `User ID: ${member.user.id}` })
42+
.setTimestamp();
43+
44+
addToQueue(logChannel, logEmbed, client);
45+
46+
} catch (error) {
47+
console.error("Error logging member leave:", error);
48+
}
49+
},
50+
};

events/messageDelete.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const { Events, EmbedBuilder } = require("discord.js");
2+
const Database = require("../utils/database");
3+
const { addToQueue } = require("../utils/logQueue"); // Import the queue utility
4+
5+
module.exports = {
6+
name: Events.MessageDelete,
7+
async execute(message, client) {
8+
if (!message.guild || message.author?.bot) return;
9+
10+
try {
11+
const db = await Database.getInstance();
12+
const config = await db.serverConfig.findOne({ guildId: message.guild.id });
13+
14+
if (!config.messageLogChannelId) return;
15+
16+
const member = await message.guild.members.fetch(message.author.id).catch(() => null);
17+
if (member) {
18+
if (config.messageLogExemptUsers?.includes(message.author.id)) return;
19+
if (member.roles.cache.some(role => config.messageLogExemptRoles?.includes(role.id))) return;
20+
}
21+
22+
const logChannel = await message.guild.channels.fetch(config.messageLogChannelId).catch(() => null);
23+
if (!logChannel) return;
24+
25+
const content = message.content ? (message.content.length > 1024 ? message.content.substring(0, 1021) + "..." : message.content) : "*No message content.*";
26+
27+
const logEmbed = new EmbedBuilder()
28+
.setColor(client.colors.error)
29+
.setAuthor({ name: message.author.tag, iconURL: message.author.displayAvatarURL() })
30+
.setTitle("🗑️ Message Deleted")
31+
.setDescription(`A message from ${message.author} was deleted in ${message.channel}.`)
32+
.addFields({ name: "Content", value: content })
33+
.setFooter({ text: `User ID: ${message.author.id}` })
34+
.setTimestamp();
35+
36+
// Use the queue instead of sending directly
37+
addToQueue(logChannel, logEmbed, client);
38+
39+
if (message.embeds.length > 0) {
40+
const embedLogEmbed = new EmbedBuilder()
41+
.setColor(client.colors.error)
42+
.setAuthor({ name: message.author.tag, iconURL: message.author.displayAvatarURL() })
43+
.setTitle("🗑️ Deleted Embeds")
44+
.setDescription(`Below are the embeds from the deleted message by ${message.author}.`);
45+
46+
addToQueue(logChannel, embedLogEmbed, client);
47+
48+
for(const embed of message.embeds.slice(0, 4)){
49+
addToQueue(logChannel, embed, client);
50+
}
51+
}
52+
53+
} catch (error) {
54+
console.error("Error preparing message deletion log:", error);
55+
}
56+
},
57+
};

0 commit comments

Comments
 (0)