Caching hotfix

This commit is contained in:
yeongaori
2025-08-24 20:25:45 +09:00
parent 045b6c88f0
commit c31187c2ee
4 changed files with 61 additions and 21 deletions

View File

@@ -13,9 +13,9 @@ const { createProgressBar, getNameById } = require('../../utils/discordUtils');
const { binarySearch, addSpace } = require('../../utils/helpers'); const { binarySearch, addSpace } = require('../../utils/helpers');
// Core logic for getting discharge info // Core logic for getting discharge info
function getDischargeInfo(client, targetUserId, targetUserName, decimal, usedFullInfo) { async function getDischargeInfo(client, targetUserId, targetUserName, decimal, usedFullInfo) {
try { try {
const ipdaeDatas = getIpdaeData(); const ipdaeDatas = await getIpdaeData();
const userNameForEmbed = (targetUserName && targetUserName.trim() !== `Unknown User (${targetUserId})` && targetUserName.trim() !== '') ? `${targetUserName}` : `사용자 (${targetUserId})님`; const userNameForEmbed = (targetUserName && targetUserName.trim() !== `Unknown User (${targetUserId})` && targetUserName.trim() !== '') ? `${targetUserName}` : `사용자 (${targetUserId})님`;
const index = binarySearch(ipdaeDatas, targetUserId); const index = binarySearch(ipdaeDatas, targetUserId);
if (index === -1) { if (index === -1) {
@@ -115,7 +115,7 @@ async function execute(interaction) {
const targetUserName = getNameById(interaction.client, targetUserId, interaction.guild); const targetUserName = getNameById(interaction.client, targetUserId, interaction.guild);
logger.info(`Processing /전역일 for ${targetUserName} (${targetUserId}), requested by ${interaction.user.username} (${interaction.user.id})`); logger.info(`Processing /전역일 for ${targetUserName} (${targetUserId}), requested by ${interaction.user.username} (${interaction.user.id})`);
await interaction.deferReply(); await interaction.deferReply();
const resultEmbed = getDischargeInfo(interaction.client, targetUserId, targetUserName, decimalArg, fullInfoArg); const resultEmbed = await getDischargeInfo(interaction.client, targetUserId, targetUserName, decimalArg, fullInfoArg);
await interaction.editReply({ embeds: [resultEmbed] }); await interaction.editReply({ embeds: [resultEmbed] });
} }
@@ -145,7 +145,7 @@ const legacy = {
} }
const targetUserName = getNameById(client, targetUserId, guild); const targetUserName = getNameById(client, targetUserId, guild);
const resultEmbed = getDischargeInfo(client, targetUserId, targetUserName, decimal, false); const resultEmbed = await getDischargeInfo(client, targetUserId, targetUserName, decimal, false);
await channel.send({ embeds: [resultEmbed] }); await channel.send({ embeds: [resultEmbed] });
} }
}; };

View File

@@ -64,7 +64,7 @@ const commandData = new SlashCommandBuilder()
.setDescription('입대일을 설정합니다') .setDescription('입대일을 설정합니다')
.setContexts(InteractionContextType.Guild, InteractionContextType.BotDM, InteractionContextType.PrivateChannel) .setContexts(InteractionContextType.Guild, InteractionContextType.BotDM, InteractionContextType.PrivateChannel)
.setIntegrationTypes(ApplicationIntegrationType.GuildInstall, ApplicationIntegrationType.UserInstall) .setIntegrationTypes(ApplicationIntegrationType.GuildInstall, ApplicationIntegrationType.UserInstall)
.addStringOption(option => option.setName('날짜').setDescription('형식: YYYY-MM-DD').setRequired(true)) .addStringOption(option => option.setName('입대일').setDescription('형식: YYYY-MM-DD').setRequired(true))
.addStringOption(option => option.setName('복무형태').setDescription('복무 형태').setRequired(true) .addStringOption(option => option.setName('복무형태').setDescription('복무 형태').setRequired(true)
.addChoices( .addChoices(
{ name: '육군', value: '육군' }, { name: '육군', value: '육군' },
@@ -75,7 +75,7 @@ const commandData = new SlashCommandBuilder()
)); ));
async function execute(interaction) { async function execute(interaction) {
const slashStartDateArg = interaction.options.getString('날짜'); const slashStartDateArg = interaction.options.getString('입대일');
const slashStartTypeArg = interaction.options.getString('복무형태'); const slashStartTypeArg = interaction.options.getString('복무형태');
logger.info(`Processing /입대일 for ${interaction.user.username} (${interaction.user.id}) with date: ${slashStartDateArg}, type: ${slashStartTypeArg}`); logger.info(`Processing /입대일 for ${interaction.user.username} (${interaction.user.id}) with date: ${slashStartDateArg}, type: ${slashStartTypeArg}`);
await interaction.deferReply(); await interaction.deferReply();
@@ -103,4 +103,4 @@ module.exports = {
data: commandData, data: commandData,
execute, execute,
legacy, legacy,
}; };

View File

@@ -88,8 +88,8 @@ async function loadCelebrationConfig() {
} }
async function migrateData() { async function migrateData() {
let ipdaeData = getIpdaeData(); let ipdaeData = await getIpdaeData();
let notificationHistory = getNotificationHistory(); let notificationHistory = await getNotificationHistory();
let ipdaeDataNeedsSave = false; let ipdaeDataNeedsSave = false;
let notificationHistoryNeedsSave = false; let notificationHistoryNeedsSave = false;
@@ -124,19 +124,19 @@ async function saveData(type) {
try { try {
switch (type) { switch (type) {
case 'ipdae': case 'ipdae':
const ipdaeData = getIpdaeData(); const ipdaeData = await getIpdaeData();
await fs.writeFile(ipdaeDataDirectory, JSON.stringify(ipdaeData, null, 4), 'utf8'); await fs.writeFile(ipdaeDataDirectory, JSON.stringify(ipdaeData, null, 4), 'utf8');
cacheManager.set('ipdaeData', ipdaeData, CACHE_TTL); cacheManager.set('ipdaeData', ipdaeData, CACHE_TTL);
logger.info('ipdaeData.json saved and cache updated.'); logger.info('ipdaeData.json saved and cache updated.');
break; break;
case 'config': case 'config':
const celebrationConfig = getCelebrationConfig(); const celebrationConfig = await getCelebrationConfig();
await fs.writeFile(celebrationConfigPath, JSON.stringify(celebrationConfig, null, 4), 'utf8'); await fs.writeFile(celebrationConfigPath, JSON.stringify(celebrationConfig, null, 4), 'utf8');
cacheManager.set('celebrationConfig', celebrationConfig, CACHE_TTL); cacheManager.set('celebrationConfig', celebrationConfig, CACHE_TTL);
logger.info('celebrationConfig.json saved and cache updated.'); logger.info('celebrationConfig.json saved and cache updated.');
break; break;
case 'history': case 'history':
const notificationHistory = getNotificationHistory(); const notificationHistory = await getNotificationHistory();
await fs.writeFile(notificationHistoryPath, JSON.stringify(notificationHistory, null, 4), 'utf8'); await fs.writeFile(notificationHistoryPath, JSON.stringify(notificationHistory, null, 4), 'utf8');
cacheManager.set('notificationHistory', notificationHistory, CACHE_TTL); cacheManager.set('notificationHistory', notificationHistory, CACHE_TTL);
logger.info('notificationHistory.json saved and cache updated.'); logger.info('notificationHistory.json saved and cache updated.');
@@ -149,39 +149,39 @@ async function saveData(type) {
} }
} }
function getIpdaeData() { async function getIpdaeData() {
let data = cacheManager.get('ipdaeData'); let data = cacheManager.get('ipdaeData');
if (!data) { if (!data) {
logger.info("ipdaeData not in cache or expired, reloading from file."); logger.info("ipdaeData not in cache or expired, reloading from file.");
loadIpdaeData(); await loadIpdaeData();
data = cacheManager.get('ipdaeData'); data = cacheManager.get('ipdaeData');
} }
return data || []; return data || [];
} }
function getCelebrationConfig() { async function getCelebrationConfig() {
let data = cacheManager.get('celebrationConfig'); let data = cacheManager.get('celebrationConfig');
if (!data) { if (!data) {
logger.info("celebrationConfig not in cache or expired, reloading from file."); logger.info("celebrationConfig not in cache or expired, reloading from file.");
loadCelebrationConfig(); await loadCelebrationConfig();
data = cacheManager.get('celebrationConfig'); data = cacheManager.get('celebrationConfig');
} }
return data || {}; return data || {};
} }
function getNotificationHistory() { async function getNotificationHistory() {
let data = cacheManager.get('notificationHistory'); let data = cacheManager.get('notificationHistory');
if (!data) { if (!data) {
logger.info("notificationHistory not in cache or expired, reloading from file."); logger.info("notificationHistory not in cache or expired, reloading from file.");
loadNotificationHistory(); await loadNotificationHistory();
data = cacheManager.get('notificationHistory'); data = cacheManager.get('notificationHistory');
} }
return data || {}; return data || {};
} }
async function updateEnlistmentData(userId, date, type) { async function updateEnlistmentData(userId, date, type) {
let ipdaeDatas = getIpdaeData(); let ipdaeDatas = await getIpdaeData();
let notificationHistory = getNotificationHistory(); let notificationHistory = await getNotificationHistory();
let notificationHistoryModified = false; let notificationHistoryModified = false;
const index = binarySearch(ipdaeDatas, userId); const index = binarySearch(ipdaeDatas, userId);

View File

@@ -1,10 +1,48 @@
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const { ActivityType } = require('discord.js');
const logger = require('../../modules/colorfulLogger'); const logger = require('../../modules/colorfulLogger');
const { handleCommandError } = require('../../utils/errorHandler'); const { handleCommandError } = require('../../utils/errorHandler');
const { checkAndSendCelebrationMessages, scheduleDailyCelebrationCheck } = require('../commands/military/celebration'); const { checkAndSendCelebrationMessages, scheduleDailyCelebrationCheck } = require('../commands/military/celebration');
const { ActivityType } = require('discord.js');
const { initializeRPC } = require('../handlers/rpcHandler'); const { initializeRPC } = require('../handlers/rpcHandler');
const { initializeKoreanbotsUpdate } = require('../handlers/koreanbotsHandler'); const { initializeKoreanbotsUpdate } = require('../handlers/koreanbotsHandler');
async function registerSlashCommands(client) {
const commands = [];
const commandFolders = fs.readdirSync(path.join(__dirname, '..', 'commands'));
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(path.join(__dirname, '..', 'commands', folder)).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
try {
const filePath = path.join(__dirname, '..', 'commands', folder, file);
const command = require(filePath);
if (command.data) {
commands.push(command.data.toJSON());
}
} catch (error) {
logger.error(`Error loading command from ${file}:`, error);
}
}
}
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
try {
logger.info('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: commands },
);
logger.info('Successfully reloaded application (/) commands.');
} catch (error) {
logger.error('Failed to reload application (/) commands:', error);
}
}
module.exports = { module.exports = {
name: 'ready', name: 'ready',
once: true, once: true,
@@ -12,6 +50,8 @@ module.exports = {
try { try {
logger.info(`Logged in as ${client.user.tag}`); logger.info(`Logged in as ${client.user.tag}`);
await registerSlashCommands(client);
initializeRPC(client); initializeRPC(client);
initializeKoreanbotsUpdate(client); initializeKoreanbotsUpdate(client);