|
| 1 | +import * as Sentry from "@sentry/bun"; |
| 2 | +import type { Collection, Message, Snowflake, TextBasedChannel } from "discord.js"; |
| 3 | +import ExpiryMap from "expiry-map"; |
| 4 | +import { config } from "../../Config.js"; |
| 5 | +import { logger } from "../../logging.js"; |
| 6 | +import { messageFetcher } from "../../util/ratelimiting.js"; |
| 7 | +import type { EventListener } from "../module.js"; |
| 8 | +import { type CachedMessage, logBulkDeletedMessages, logDeletedMessage } from "./logs.js"; |
| 9 | + |
| 10 | +// Configurable TTL - default 24 hours |
| 11 | +const CACHE_TTL_MS = |
| 12 | + config.deletedMessageLog?.cacheTtlMs ?? 1000 * 60 * 60 * 24; |
| 13 | + |
| 14 | +const messageCache = new ExpiryMap<Snowflake, CachedMessage>(CACHE_TTL_MS); |
| 15 | + |
| 16 | +// Auto-excluded mod channels |
| 17 | +const modChannels = new Set([ |
| 18 | + config.channels.modLog, |
| 19 | + config.channels.auditLog, |
| 20 | + config.modmail.channel, |
| 21 | +]); |
| 22 | + |
| 23 | +function isExcludedChannel(channelId: Snowflake): boolean { |
| 24 | + const additionalExcluded = config.deletedMessageLog?.excludedChannels ?? []; |
| 25 | + return modChannels.has(channelId) || additionalExcluded.includes(channelId); |
| 26 | +} |
| 27 | + |
| 28 | +function cacheMessage(message: Message): void { |
| 29 | + if ( |
| 30 | + message.author.bot || |
| 31 | + !message.inGuild() || |
| 32 | + isExcludedChannel(message.channelId) |
| 33 | + ) |
| 34 | + return; |
| 35 | + |
| 36 | + messageCache.set(message.id, { |
| 37 | + id: message.id, |
| 38 | + content: message.content, |
| 39 | + authorId: message.author.id, |
| 40 | + authorTag: message.author.tag, |
| 41 | + channelId: message.channelId, |
| 42 | + createdTimestamp: message.createdTimestamp, |
| 43 | + attachmentUrls: message.attachments.map((a) => a.url), |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +function cacheMessages(messages: Collection<string, Message>): number { |
| 48 | + for (const message of messages.values()) { |
| 49 | + cacheMessage(message); |
| 50 | + } |
| 51 | + return messages.size; |
| 52 | +} |
| 53 | + |
| 54 | +async function fetchAndCacheMessages( |
| 55 | + channel: TextBasedChannel, |
| 56 | + limit: number |
| 57 | +): Promise<number> { |
| 58 | + let cached = 0; |
| 59 | + let before: Snowflake | undefined; |
| 60 | + |
| 61 | + while (cached < limit) { |
| 62 | + const batch = await channel.messages.fetch({ |
| 63 | + limit: Math.min(100, limit - cached), |
| 64 | + before |
| 65 | + }); |
| 66 | + if (batch.size === 0) break; |
| 67 | + |
| 68 | + cached += cacheMessages(batch); |
| 69 | + before = batch.last()?.id; |
| 70 | + |
| 71 | + if (batch.size < 100) break; |
| 72 | + } |
| 73 | + |
| 74 | + return cached; |
| 75 | +} |
| 76 | + |
| 77 | +export const DeletedMessagesListener: EventListener = { |
| 78 | + async clientReady(client) { |
| 79 | + const guild = await client.guilds.fetch(config.guildId); |
| 80 | + const channels = await guild.channels.fetch(); |
| 81 | + |
| 82 | + for (const channel of channels.values()) { |
| 83 | + if (!channel?.isTextBased() || isExcludedChannel(channel.id)) continue; |
| 84 | + |
| 85 | + await messageFetcher.addToQueue(async () => { |
| 86 | + try { |
| 87 | + const cached = await fetchAndCacheMessages(channel, 200); |
| 88 | + logger.info(`Cached ${cached} messages from #${channel.name}`); |
| 89 | + } catch { |
| 90 | + // Skip channels we can't read (permissions) |
| 91 | + } |
| 92 | + }); |
| 93 | + } |
| 94 | + }, |
| 95 | + |
| 96 | + messageCreate(_, message) { |
| 97 | + if (!message.inGuild()) return; |
| 98 | + cacheMessage(message); |
| 99 | + }, |
| 100 | + |
| 101 | + messageUpdate(_, _oldMessage, newMessage) { |
| 102 | + if (!newMessage.inGuild()) return; |
| 103 | + if (newMessage.partial) return; |
| 104 | + cacheMessage(newMessage); |
| 105 | + }, |
| 106 | + |
| 107 | + async messageDelete(client, message) { |
| 108 | + try { |
| 109 | + if (isExcludedChannel(message.channelId)) return; |
| 110 | + |
| 111 | + const cached = messageCache.get(message.id); |
| 112 | + if (!cached) { |
| 113 | + logger.debug(`Deleted message ${message.id} not in cache`); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + await logDeletedMessage(client, cached); |
| 118 | + messageCache.delete(message.id); |
| 119 | + } catch (error) { |
| 120 | + logger.error("Failed to log deleted message:", error); |
| 121 | + Sentry.captureException(error); |
| 122 | + } |
| 123 | + }, |
| 124 | + |
| 125 | + async messageDeleteBulk(client, messages, channel) { |
| 126 | + try { |
| 127 | + if (isExcludedChannel(channel.id)) return; |
| 128 | + |
| 129 | + const cachedMessages: CachedMessage[] = []; |
| 130 | + for (const [id] of messages) { |
| 131 | + const cached = messageCache.get(id); |
| 132 | + if (cached) { |
| 133 | + cachedMessages.push(cached); |
| 134 | + messageCache.delete(id); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + if (cachedMessages.length === 0) { |
| 139 | + logger.debug(`Bulk deletion in ${channel.id} - no messages in cache`); |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + await logBulkDeletedMessages(client, cachedMessages, channel.id); |
| 144 | + } catch (error) { |
| 145 | + logger.error("Failed to log bulk deleted messages:", error); |
| 146 | + Sentry.captureException(error); |
| 147 | + } |
| 148 | + }, |
| 149 | +}; |
0 commit comments