Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/commands/Logging/logging.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export default {
{ name: 'Audit (moderation, messages, members…)', value: 'audit' },
{ name: 'Applications', value: 'applications' },
{ name: 'Reports', value: 'reports' },
{ name: 'Messages (deleted / edited)', value: 'messages' },
{ name: 'Roles (given / removed)', value: 'roles' },
),
)
.addChannelOption((option) =>
Expand Down
2 changes: 2 additions & 0 deletions src/commands/Logging/modules/logging_channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const DESTINATION_LABELS = {
audit: 'Audit Log',
applications: 'Applications',
reports: 'Reports',
messages: 'Messages',
roles: 'Roles',
};

export default {
Expand Down
4 changes: 4 additions & 0 deletions src/commands/Logging/modules/logging_dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export async function buildLoggingDashboardView(interaction, client) {
const auditChannel = await formatChannelMention(interaction.guild, channels.audit);
const applicationsChannel = await formatChannelMention(interaction.guild, channels.applications);
const reportsChannel = await formatChannelMention(interaction.guild, channels.reports);
const messagesChannel = await formatChannelMention(interaction.guild, channels.messages);
const rolesChannel = await formatChannelMention(interaction.guild, channels.roles);
const lifecycleChannel = await formatChannelMention(interaction.guild, guildConfig.ticketLogsChannelId);
const transcriptChannel = await formatChannelMention(interaction.guild, guildConfig.ticketTranscriptChannelId);

Expand Down Expand Up @@ -78,6 +80,8 @@ export async function buildLoggingDashboardView(interaction, client) {
`**Audit:** ${auditChannel}`,
`**Applications:** ${applicationsChannel}`,
`**Reports:** ${reportsChannel}`,
`**Messages:** ${messagesChannel}`,
`**Roles:** ${rolesChannel}`,
].join('\n'),
inline: false,
},
Expand Down
23 changes: 0 additions & 23 deletions src/events/guildMemberRemove.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Events, EmbedBuilder, PermissionFlagsBits } from 'discord.js';
import { getColor, botConfig } from '../config/bot.js';
import { getWelcomeConfig, getUserApplications, deleteApplication } from '../utils/database.js';
import { formatWelcomeMessage } from '../utils/welcome.js';
import { logEvent, EVENT_TYPES } from '../services/loggingService.js';
import { getServerCounters, updateCounter } from '../services/serverstatsService.js';
import { getGuildBirthdays, deleteBirthday } from '../utils/database.js';
import { deleteUserLevelData } from '../services/leveling/leveling.js';
Expand Down Expand Up @@ -78,28 +77,6 @@ export default {
}
}

try {
await logEvent({
client: member.client,
guildId: guild.id,
eventType: EVENT_TYPES.MEMBER_LEAVE,
data: {
title: 'User left',
lines: [
`**User:** ${user.toString()} (${user.tag})`,
`**ID:** \`${user.id}\``,
`**Joined:** <t:${Math.floor((member.joinedTimestamp || Date.now()) / 1000)}:R>`,
`**Members:** ${guild.memberCount}`,
],
quoted: false,
thumbnail: user.displayAvatarURL({ dynamic: true }),
userId: user.id,
}
});
} catch (error) {
logger.debug('Error logging member leave:', error);
}

try {
const counters = await getServerCounters(member.client, guild.id);
for (const counter of counters) {
Expand Down
49 changes: 48 additions & 1 deletion src/events/guildMemberUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,55 @@ export default {
userId: newMember.user.id,
}
});
}

// Role changes (skipped when the old member isn't cached, since we can't diff roles)
if (oldMember.partial) {
logger.warn(
`guildMemberUpdate: old member ${newMember.user?.id} not cached in guild ${newMember.guild.id}; role change cannot be detected`
);
} else {
const guildId = newMember.guild.id;
const changes = [
{
eventType: EVENT_TYPES.MEMBER_ROLE_ADD,
title: 'Role received',
roles: newMember.roles.cache.filter((r) => !oldMember.roles.cache.has(r.id) && r.id !== guildId),
},
{
eventType: EVENT_TYPES.MEMBER_ROLE_REMOVE,
title: 'Role removed',
roles: oldMember.roles.cache.filter((r) => !newMember.roles.cache.has(r.id) && r.id !== guildId),
},
];

return;
for (const { eventType, title, roles } of changes) {
for (const role of roles.values()) {
const sent = await logEvent({
client: newMember.client,
guildId,
eventType,
data: {
title,
lines: [
`**User:** ${newMember.user.toString()} (${newMember.user.tag})`,
`**ID:** \`${newMember.user.id}\``,
`**Role:** ${role.toString()} (${role.name})`,
],
thumbnail: newMember.user.displayAvatarURL({ dynamic: true }),
userId: newMember.user.id,
}
});

if (!sent) {
logger.warn(
`Role alert (${eventType}) for ${newMember.user.id} in guild ${guildId} was not sent. ` +
'Check /logging dashboard: audit log must be enabled, an audit channel set, the Members category on, ' +
'and the bot needs Send Messages + Embed Links in that channel.'
);
}
}
}
}

} catch (error) {
Expand Down
38 changes: 37 additions & 1 deletion src/events/messageCreate.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Events } from 'discord.js';
import { Events, PermissionsBitField } from 'discord.js';
import { logger } from '../utils/logger.js';
import { getLevelingConfig, getUserLevelData } from '../services/leveling/leveling.js';
import { addXp } from '../services/leveling/xpSystem.js';
Expand All @@ -19,6 +19,9 @@ import {
recordCorrectCount,
} from '../services/countingGameService.js';

const EVERYONE_PING_WARNING_COOLDOWN_MS = 30000;
const everyonePingWarnings = new Map();

const MESSAGE_XP_RATE_LIMIT_ATTEMPTS = 12;
const MESSAGE_XP_RATE_LIMIT_WINDOW_MS = 10000;

Expand All @@ -30,6 +33,8 @@ export default {

logger.debug(`Message received from ${message.author.tag}: ${message.content}`);

await handleEveryonePing(message);

const countingProcessed = await handleCountingGame(message, client);
if (countingProcessed) {
return;
Expand All @@ -44,6 +49,37 @@ export default {
}
};

async function handleEveryonePing(message) {
try {
if (!/@(everyone|here)\b/i.test(message.content || '')) return;

// Staff are allowed to ping everyone
const perms = message.member?.permissions;
if (perms?.has(PermissionsBitField.Flags.Administrator) || perms?.has(PermissionsBitField.Flags.ManageMessages)) {
return;
}

const key = `${message.guild.id}:${message.author.id}`;
const now = Date.now();
if (now - (everyonePingWarnings.get(key) || 0) < EVERYONE_PING_WARNING_COOLDOWN_MS) return;
everyonePingWarnings.set(key, now);

// Keep the map from growing forever
if (everyonePingWarnings.size > 1000) {
for (const [k, t] of everyonePingWarnings) {
if (now - t > EVERYONE_PING_WARNING_COOLDOWN_MS) everyonePingWarnings.delete(k);
}
}

await message.channel.send({
content: `${message.author}, the result of mass pinging will result in quarantine.`,
allowedMentions: { users: [message.author.id] },
});
} catch (error) {
logger.warn('Failed to send everyone-ping warning:', error);
}
}

async function handlePrefixCommand(message, client) {
try {
const guildConfig = await getGuildConfig(client, message.guild.id);
Expand Down
9 changes: 9 additions & 0 deletions src/events/ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ export default {
startupLog(`Serving ${client.guilds.cache.size} guild(s)`);
startupLog(`Loaded ${client.commands.size} commands`);

// Cache members so guildMemberUpdate receives a full "old" member (needed to detect role changes)
for (const guild of client.guilds.cache.values()) {
try {
await guild.members.fetch();
} catch (error) {
logger.warn(`Could not cache members for guild ${guild.id}: ${error.message}`);
}
}

if (client.config?.features?.music) {
initRiffyAfterReady(client);
}
Expand Down
2 changes: 2 additions & 0 deletions src/handlers/loggingButtons.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const DESTINATION_LABELS = {
audit: 'Audit Log',
applications: 'Applications',
reports: 'Reports',
messages: 'Messages',
roles: 'Roles',
};

export default {
Expand Down
28 changes: 24 additions & 4 deletions src/services/loggingService.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
splitComparisonFields,
} from '../utils/logging/logEmbeds.js';

const LOG_DESTINATIONS = ['audit', 'applications', 'reports'];
const LOG_DESTINATIONS = ['audit', 'applications', 'reports', 'messages', 'roles'];

const EVENT_TYPES = {
MODERATION_BAN: 'moderation.ban',
Expand Down Expand Up @@ -41,6 +41,8 @@ const EVENT_TYPES = {
MEMBER_JOIN: 'member.join',
MEMBER_LEAVE: 'member.leave',
MEMBER_NAME_CHANGE: 'member.namechange',
MEMBER_ROLE_ADD: 'member.roleadd',
MEMBER_ROLE_REMOVE: 'member.roleremove',

REACTION_ROLE_ADD: 'reactionrole.add',
REACTION_ROLE_REMOVE: 'reactionrole.remove',
Expand Down Expand Up @@ -86,6 +88,8 @@ const EVENT_COLORS = {
'member.join': 0x2ecc71,
'member.leave': 0xe74c3c,
'member.namechange': 0x3498db,
'member.roleadd': 0x2ecc71,
'member.roleremove': 0xe74c3c,
'reactionrole.add': 0x2ecc71,
'reactionrole.remove': 0xe74c3c,
'reactionrole.create': 0x3498db,
Expand Down Expand Up @@ -126,6 +130,8 @@ const EVENT_ICONS = {
'member.join': '👋',
'member.leave': '👋',
'member.namechange': '🏷️',
'member.roleadd': '🎖️',
'member.roleremove': '🚫',
'reactionrole.add': '✅',
'reactionrole.remove': '❌',
'reactionrole.create': '🎭',
Expand All @@ -145,6 +151,13 @@ const EVENT_ICONS = {
const CATEGORY_DESTINATION = {
application: 'applications',
report: 'reports',
message: 'messages',
};

// Specific events that go to their own destination, overriding the category
const EVENT_DESTINATION = {
'member.roleadd': 'roles',
'member.roleremove': 'roles',
};

export function resolveLogChannel(config, destination) {
Expand Down Expand Up @@ -191,8 +204,15 @@ function getLogChannelForEvent(config, eventType, overrideChannelId = null) {
}

const category = eventType?.split('.')[0];
const destination = CATEGORY_DESTINATION[category] || 'audit';
return resolveLogChannel(config, destination);
const destination = EVENT_DESTINATION[eventType] || CATEGORY_DESTINATION[category] || 'audit';
const channelId = resolveLogChannel(config, destination);

// Message and role logs fall back to the audit channel until their own channel is set
if (!channelId && (destination === 'messages' || destination === 'roles')) {
return resolveLogChannel(config, 'audit');
}

return channelId;
}

export async function logEvent({
Expand Down Expand Up @@ -355,7 +375,7 @@ export async function getLoggingStatus(client, guildId) {

return {
enabled: logging.enabled || false,
channels: logging.channels || { audit: null, applications: null, reports: null },
channels: logging.channels || { audit: null, applications: null, reports: null, messages: null, roles: null },
channelId: logging.channels?.audit ?? null,
ignore: getIgnoreList(config),
enabledEvents: logging.enabledEvents || {},
Expand Down
2 changes: 1 addition & 1 deletion src/utils/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const DEFAULT_GUILD_CONFIG = {
autoRole: null,
logging: {
enabled: false,
channels: { audit: null, applications: null, reports: null },
channels: { audit: null, applications: null, reports: null, messages: null, roles: null },
ignore: { users: [], channels: [] },
enabledEvents: {},
},
Expand Down
18 changes: 18 additions & 0 deletions src/utils/logging/loggingUi.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ export function createLoggingMainMenuSelect() {
.setDescription('User reports filed via /report')
.setValue('set:reports')
.setEmoji('🚨'),
new StringSelectMenuOptionBuilder()
.setLabel('Set Messages Channel')
.setDescription('Deleted, edited and bulk-deleted messages')
.setValue('set:messages')
.setEmoji('💬'),
new StringSelectMenuOptionBuilder()
.setLabel('Set Roles Channel')
.setDescription('Roles given to or removed from members')
.setValue('set:roles')
.setEmoji('🎖️'),
new StringSelectMenuOptionBuilder()
.setLabel('Clear Audit Channel')
.setValue('clear:audit')
Expand All @@ -121,6 +131,14 @@ export function createLoggingMainMenuSelect() {
.setLabel('Clear Reports Channel')
.setValue('clear:reports')
.setEmoji('🗑️'),
new StringSelectMenuOptionBuilder()
.setLabel('Clear Messages Channel')
.setValue('clear:messages')
.setEmoji('🗑️'),
new StringSelectMenuOptionBuilder()
.setLabel('Clear Roles Channel')
.setValue('clear:roles')
.setEmoji('🗑️'),
new StringSelectMenuOptionBuilder()
.setLabel('Event Categories')
.setDescription('Toggle which log types are sent')
Expand Down
8 changes: 6 additions & 2 deletions src/utils/schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ export const LoggingChannelsSchema = z
audit: z.string().nullable().optional(),
applications: z.string().nullable().optional(),
reports: z.string().nullable().optional(),
messages: z.string().nullable().optional(),
roles: z.string().nullable().optional(),
})
.default({ audit: null, applications: null, reports: null });
.default({ audit: null, applications: null, reports: null, messages: null, roles: null });

export const LoggingConfigSchema = z
.object({
Expand Down Expand Up @@ -102,7 +104,7 @@ export const EconomyDataSchema = z

const DEFAULT_LOGGING = {
enabled: false,
channels: { audit: null, applications: null, reports: null },
channels: { audit: null, applications: null, reports: null, messages: null, roles: null },
ignore: { users: [], channels: [] },
enabledEvents: {},
};
Expand Down Expand Up @@ -151,6 +153,8 @@ function migrateLoggingConfig(raw = {}, legacy = {}) {
audit: auditChannel,
applications: applicationsChannel,
reports: reportsChannel,
messages: base.channels?.messages ?? null,
roles: base.channels?.roles ?? null,
},
ignore,
enabledEvents: base.enabledEvents ?? {},
Expand Down