|
| 1 | +import { |
| 2 | + SlashCommandBuilder, |
| 3 | + ChatInputCommandInteraction, |
| 4 | + EmbedBuilder, |
| 5 | + MessageFlags, |
| 6 | + PermissionFlagsBits, |
| 7 | + ChannelType, |
| 8 | +} from 'discord.js'; |
| 9 | +import { backfillManager } from '../database/backfillManager'; |
| 10 | +import { backfillChannelHistory } from '../handlers/backfillHandler'; |
| 11 | +import logger from '../utils/logger'; |
| 12 | + |
| 13 | +export const data = new SlashCommandBuilder() |
| 14 | + .setName('backfill') |
| 15 | + .setDescription('Backfill message history to find and redeem missed codes') |
| 16 | + .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages) |
| 17 | + .addChannelOption((option) => |
| 18 | + option |
| 19 | + .setName('channel') |
| 20 | + .setDescription('The channel to backfill (defaults to current channel)') |
| 21 | + .setRequired(false) |
| 22 | + ); |
| 23 | + |
| 24 | +export async function execute(interaction: ChatInputCommandInteraction) { |
| 25 | + try { |
| 26 | + logger.info(`[BACKFILL CMD] Started by ${interaction.user.tag}`); |
| 27 | + |
| 28 | + // Check permissions |
| 29 | + if (!interaction.memberPermissions?.has(PermissionFlagsBits.ManageMessages)) { |
| 30 | + const embed = new EmbedBuilder() |
| 31 | + .setColor(0xff0000) |
| 32 | + .setTitle('❌ Permission Denied') |
| 33 | + .setDescription('You need the "Manage Messages" permission to run backfill.'); |
| 34 | + |
| 35 | + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + // Check if backfill is already in progress |
| 40 | + if (backfillManager.isBackfillInProgress()) { |
| 41 | + const embed = new EmbedBuilder() |
| 42 | + .setColor(0xffaa00) |
| 43 | + .setTitle('⚠️ Backfill In Progress') |
| 44 | + .setDescription( |
| 45 | + 'A backfill operation is already running. Please wait for it to complete.' |
| 46 | + ); |
| 47 | + |
| 48 | + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + // Check rate limiting |
| 53 | + const canInitiate = await backfillManager.canUserInitiateBackfill(interaction.user.id); |
| 54 | + if (!canInitiate) { |
| 55 | + const embed = new EmbedBuilder() |
| 56 | + .setColor(0xffaa00) |
| 57 | + .setTitle('⏱️ Rate Limited') |
| 58 | + .setDescription( |
| 59 | + 'You can only initiate a backfill once per hour. Please try again later.' |
| 60 | + ); |
| 61 | + |
| 62 | + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + // Get the target channel |
| 67 | + let targetChannel: any = interaction.options.getChannel('channel'); |
| 68 | + if (!targetChannel) { |
| 69 | + targetChannel = interaction.channel; |
| 70 | + } |
| 71 | + |
| 72 | + if (!targetChannel || targetChannel.type !== ChannelType.GuildText) { |
| 73 | + const embed = new EmbedBuilder() |
| 74 | + .setColor(0xff0000) |
| 75 | + .setTitle('❌ Error') |
| 76 | + .setDescription('Invalid channel - must be a text channel in this server.'); |
| 77 | + |
| 78 | + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + // Defer the reply (backfill can take a while) |
| 83 | + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); |
| 84 | + |
| 85 | + // Start the backfill operation |
| 86 | + const operationId = await backfillManager.startBackfill(interaction.user.id); |
| 87 | + logger.info(`[BACKFILL CMD] Operation ${operationId} started for channel ${targetChannel.name}`); |
| 88 | + |
| 89 | + // Create progress tracker |
| 90 | + let progressMessage = ''; |
| 91 | + const updateProgress = (message: string) => { |
| 92 | + progressMessage = message; |
| 93 | + logger.info(`[BACKFILL] ${message}`); |
| 94 | + }; |
| 95 | + |
| 96 | + // Run the backfill |
| 97 | + const stats = await backfillChannelHistory(targetChannel, updateProgress); |
| 98 | + |
| 99 | + // Update operation status |
| 100 | + await backfillManager.updateBackfill( |
| 101 | + operationId, |
| 102 | + stats.codesFound, |
| 103 | + stats.codesRedeemed, |
| 104 | + stats.errors.length === 0 ? 'completed' : 'failed' |
| 105 | + ); |
| 106 | + |
| 107 | + // Create result embed |
| 108 | + const embed = new EmbedBuilder() |
| 109 | + .setColor(stats.errors.length === 0 ? 0x00aa00 : 0xffaa00) |
| 110 | + .setTitle('✅ Backfill Complete') |
| 111 | + .setDescription( |
| 112 | + [ |
| 113 | + `**Codes Found:** ${stats.codesFound}`, |
| 114 | + `**Codes Redeemed:** ${stats.codesRedeemed}`, |
| 115 | + `**Pending Codes:** ${stats.pendingCodes}`, |
| 116 | + ].join('\n') |
| 117 | + ); |
| 118 | + |
| 119 | + if (stats.errors.length > 0) { |
| 120 | + embed.addFields({ |
| 121 | + name: '⚠️ Errors', |
| 122 | + value: stats.errors.slice(0, 5).join('\n'), // Show first 5 errors |
| 123 | + }); |
| 124 | + } |
| 125 | + |
| 126 | + embed.setFooter({ |
| 127 | + text: `Operation ID: ${operationId}`, |
| 128 | + }); |
| 129 | + |
| 130 | + await interaction.editReply({ embeds: [embed] }); |
| 131 | + |
| 132 | + logger.info( |
| 133 | + `[BACKFILL CMD] Operation ${operationId} completed: found=${stats.codesFound}, redeemed=${stats.codesRedeemed}` |
| 134 | + ); |
| 135 | + } catch (error) { |
| 136 | + logger.error('[BACKFILL CMD] Command error:', error); |
| 137 | + |
| 138 | + try { |
| 139 | + const embed = new EmbedBuilder() |
| 140 | + .setColor(0xff0000) |
| 141 | + .setTitle('❌ Error') |
| 142 | + .setDescription( |
| 143 | + `An error occurred during backfill: ${error instanceof Error ? error.message : String(error)}` |
| 144 | + ); |
| 145 | + |
| 146 | + if (interaction.deferred) { |
| 147 | + await interaction.editReply({ embeds: [embed] }); |
| 148 | + } else { |
| 149 | + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); |
| 150 | + } |
| 151 | + } catch (replyError) { |
| 152 | + logger.error('[BACKFILL CMD] Failed to send error reply:', replyError); |
| 153 | + } |
| 154 | + } |
| 155 | +} |
0 commit comments