From 4cc1b17984866924e9d1de62989f562759088e3a Mon Sep 17 00:00:00 2001 From: Milo Date: Wed, 11 Mar 2026 13:05:19 +0100 Subject: [PATCH] reduce discord requests --- src/bot/commands/info.js | 2 +- src/bot/commands/inventory.js | 5 +-- src/bot/commands/search.js | 5 +-- src/bot/commands/skins.js | 5 +-- src/bot/commands/timeout.js | 8 ++--- src/bot/components/inventoryNav.js | 5 +-- src/bot/components/searchNav.js | 3 +- src/bot/handlers/messageCreate.js | 6 ++-- src/game/blackjack.js | 4 +-- src/game/elo.js | 7 +++-- src/server/routes/api.js | 50 +++++++++++++++--------------- src/server/routes/blackjack.js | 15 ++++----- src/server/routes/erinyes.js | 3 +- src/server/routes/poker.js | 10 +++--- src/server/socket.js | 29 ++++++++--------- src/utils/index.js | 10 +++++- src/utils/marketNotifs.js | 33 ++++++++++---------- 17 files changed, 109 insertions(+), 91 deletions(-) diff --git a/src/bot/commands/info.js b/src/bot/commands/info.js index a20e729..8a09cf7 100644 --- a/src/bot/commands/info.js +++ b/src/bot/commands/info.js @@ -12,7 +12,7 @@ export async function handleInfoCommand(req, res, client) { try { // Fetch the guild object from the client - const guild = await client.guilds.fetch(guild_id); + const guild = client.guilds.cache.get(guild_id); // Fetch all members to ensure the cache is up to date await guild.members.fetch(); diff --git a/src/bot/commands/inventory.js b/src/bot/commands/inventory.js index 73f73b7..70b5011 100644 --- a/src/bot/commands/inventory.js +++ b/src/bot/commands/inventory.js @@ -8,6 +8,7 @@ import { activeInventories, skins } from "../../game/state.js"; import * as skinService from "../../services/skin.service.js"; import * as csSkinService from "../../services/csSkin.service.js"; import { RarityToColor } from "../../utils/cs.utils.js"; +import { resolveMember } from "../../utils/index.js"; /** * Handles the /inventory slash command. @@ -31,8 +32,8 @@ export async function handleInventoryCommand(req, res, client, interactionId) { const targetUserId = data.options && data.options.length > 0 ? data.options[0].value : commandUserId; try { - const guild = await client.guilds.fetch(guild_id); - const targetMember = await guild.members.fetch(targetUserId); + const guild = client.guilds.cache.get(guild_id); + const targetMember = await resolveMember(guild, targetUserId); // Fetch both Valorant and CS2 inventories const valoSkins = await skinService.getUserInventory(targetUserId); diff --git a/src/bot/commands/search.js b/src/bot/commands/search.js index ab9fe11..102e783 100644 --- a/src/bot/commands/search.js +++ b/src/bot/commands/search.js @@ -6,6 +6,7 @@ import { } from "discord-interactions"; import { activeSearchs, skins } from "../../game/state.js"; import * as skinService from "../../services/skin.service.js"; +import { resolveMember } from "../../utils/index.js"; /** * Handles the /search slash command. @@ -52,7 +53,7 @@ export async function handleSearchCommand(req, res, client, interactionId) { }; // --- 4. Prepare Initial Embed Content --- - const guild = await client.guilds.fetch(guild_id); + const guild = client.guilds.cache.get(guild_id); const currentSkin = resultSkins[0]; const skinData = skins.find((s) => s.uuid === currentSkin.uuid); if (!skinData) { @@ -63,7 +64,7 @@ export async function handleSearchCommand(req, res, client, interactionId) { let ownerText = ""; if (currentSkin.userId) { try { - const owner = await guild.members.fetch(currentSkin.userId); + const owner = await resolveMember(guild, currentSkin.userId); ownerText = `| **@${owner.user.globalName || owner.user.username}** ✅`; } catch (e) { console.warn(`Could not fetch owner for user ID: ${currentSkin.userId}`); diff --git a/src/bot/commands/skins.js b/src/bot/commands/skins.js index 5d221e5..a858cde 100644 --- a/src/bot/commands/skins.js +++ b/src/bot/commands/skins.js @@ -1,5 +1,6 @@ import { InteractionResponseType } from "discord-interactions"; import * as skinService from "../../services/skin.service.js"; +import { resolveMember } from "../../utils/index.js"; /** * Handles the /skins slash command. @@ -14,7 +15,7 @@ export async function handleSkinsCommand(req, res, client) { try { // --- 1. Fetch Data --- const topSkins = await skinService.getTopSkins(); - const guild = await client.guilds.fetch(guild_id); + const guild = client.guilds.cache.get(guild_id); const fields = []; // --- 2. Build Embed Fields Asynchronously --- @@ -25,7 +26,7 @@ export async function handleSkinsCommand(req, res, client) { // If the skin has an owner, fetch their details if (skin.userId) { try { - const owner = await guild.members.fetch(skin.userId); + const owner = await resolveMember(guild, skin.userId); // Use globalName if available, otherwise fallback to username ownerText = `**@${owner.user.globalName || owner.user.username}** ✅`; } catch (e) { diff --git a/src/bot/commands/timeout.js b/src/bot/commands/timeout.js index a3415ca..7a8dc19 100644 --- a/src/bot/commands/timeout.js +++ b/src/bot/commands/timeout.js @@ -5,7 +5,7 @@ import { ButtonStyleTypes, } from "discord-interactions"; -import { formatTime, getOnlineUsersWithRole } from "../../utils/index.js"; +import { formatTime, getOnlineUsersWithRole, resolveMember } from "../../utils/index.js"; import { DiscordRequest } from "../../api/discord.js"; import { activePolls } from "../../game/state.js"; import { getSocketIo } from "../../server/socket.js"; @@ -28,9 +28,9 @@ export async function handleTimeoutCommand(req, res, client) { const time = options[1].value; // Fetch member objects from Discord - const guild = await client.guilds.fetch(guild_id); - const fromMember = await guild.members.fetch(userId); - const toMember = await guild.members.fetch(targetUserId); + const guild = client.guilds.cache.get(guild_id); + const fromMember = await resolveMember(guild, userId); + const toMember = await resolveMember(guild, targetUserId); // --- Validation Checks --- // 1. Check if a poll is already running for the target user diff --git a/src/bot/components/inventoryNav.js b/src/bot/components/inventoryNav.js index 1cb71a9..080bac1 100644 --- a/src/bot/components/inventoryNav.js +++ b/src/bot/components/inventoryNav.js @@ -8,6 +8,7 @@ import { import { DiscordRequest } from "../../api/discord.js"; import { activeInventories } from "../../game/state.js"; import { buildSkinEmbed } from "../commands/inventory.js"; +import { resolveMember } from "../../utils/index.js"; /** * Handles navigation button clicks (Previous/Next) for the inventory embed. @@ -55,8 +56,8 @@ export async function handleInventoryNav(req, res, client) { const currentPage = inventorySession.page; const currentSkin = inventorySkins[currentPage]; - const guild = await client.guilds.fetch(guild_id); - const targetMember = await guild.members.fetch(inventorySession.akhyId); + const guild = client.guilds.cache.get(guild_id); + const targetMember = await resolveMember(guild, inventorySession.akhyId); const totalPrice = inventorySkins.reduce((sum, skin) => { return sum + (skin._type === "cs" ? skin.price || 0 : skin.currentPrice || 0); }, 0); diff --git a/src/bot/components/searchNav.js b/src/bot/components/searchNav.js index 01d371f..007c558 100644 --- a/src/bot/components/searchNav.js +++ b/src/bot/components/searchNav.js @@ -7,6 +7,7 @@ import { import { DiscordRequest } from "../../api/discord.js"; import { activeSearchs, skins } from "../../game/state.js"; +import { resolveUser } from "../../utils/index.js"; /** * Handles navigation button clicks (Previous/Next) for the search results embed. @@ -67,7 +68,7 @@ export async function handleSearchNav(req, res, client) { let ownerText = ""; if (currentSkin.userId) { try { - const owner = await client.users.fetch(currentSkin.userId); + const owner = await resolveUser(client, currentSkin.userId); ownerText = `| **@${owner.globalName || owner.username}** ✅`; } catch (e) { console.warn(`Could not fetch owner for user ID: ${currentSkin.userId}`); diff --git a/src/bot/handlers/messageCreate.js b/src/bot/handlers/messageCreate.js index 95a2da6..8310418 100644 --- a/src/bot/handlers/messageCreate.js +++ b/src/bot/handlers/messageCreate.js @@ -10,7 +10,7 @@ import { MAX_ATTS_PER_MESSAGE, stripMentionsOfBot, } from "../../utils/ai.js"; -import { calculateBasePrice, calculateMaxPrice, formatTime, getAkhys } from "../../utils/index.js"; +import { calculateBasePrice, calculateMaxPrice, formatTime, getAkhys, resolveMember } from "../../utils/index.js"; import { channelPointsHandler, initTodaysSOTD, randomSkinPrice, slowmodesHandler } from "../../game/points.js"; import { activePolls, activeSlowmodes, requestTimestamps, skins } from "../../game/state.js"; import prisma from "../../prisma/client.js"; @@ -106,7 +106,7 @@ async function handleAiMention(message, client, io) { // Apply timeout if warn count is too high if (authorDB.warns > (parseInt(process.env.MAX_WARNS) || 10)) { try { - const member = await message.guild.members.fetch(authorId); + const member = await resolveMember(message.guild, authorId); const time = parseInt(process.env.SPAM_TIMEOUT_TIME); await member.timeout(time, "Spam excessif du bot AI."); message.channel @@ -255,7 +255,7 @@ async function handleAdminCommands(message) { await getAkhys(client); break; case `${prefix}:avatars`: - const guild = await client.guilds.fetch(process.env.GUILD_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); const members = await guild.members.fetch(); const akhys = members.filter((m) => !m.user.bot && m.roles.cache.has(process.env.AKHY_ROLE_ID)); diff --git a/src/game/blackjack.js b/src/game/blackjack.js index 18177b1..8a48603 100644 --- a/src/game/blackjack.js +++ b/src/game/blackjack.js @@ -323,8 +323,8 @@ export async function settleAll(room) { hand.result = res.result; hand.delta = res.delta; try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); const msg = await generalChannel.messages.fetch(p.msgId); const updatedEmbed = new EmbedBuilder() .setDescription(`<@${p.id}> joue au Blackjack.`) diff --git a/src/game/elo.js b/src/game/elo.js index 51a6c65..9c85d25 100644 --- a/src/game/elo.js +++ b/src/game/elo.js @@ -2,6 +2,7 @@ import * as userService from "../services/user.service.js"; import * as gameService from "../services/game.service.js"; import { ButtonStyle, EmbedBuilder } from "discord.js"; import { client } from "../bot/client.js"; +import { resolveUser } from "../utils/index.js"; /** * Handles Elo calculation for a standard 1v1 game. @@ -72,9 +73,9 @@ export async function eloHandler(p1Id, p2Id, p1Score, p2Score, type, scores = nu console.log(`Elo Update (${type}) for ${p1DB.globalName}: ${p1CurrentElo} -> ${finalP1Elo}`); console.log(`Elo Update (${type}) for ${p2DB.globalName}: ${p2CurrentElo} -> ${finalP2Elo}`); try { - const generalChannel = await client.channels.fetch(process.env.BOT_CHANNEL_ID); - const user1 = await client.users.fetch(p1Id); - const user2 = await client.users.fetch(p2Id); + const generalChannel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); + const user1 = await resolveUser(client, p1Id); + const user2 = await resolveUser(client, p2Id); const diff1 = finalP1Elo - p1CurrentElo; const diff2 = finalP2Elo - p2CurrentElo; const embed = new EmbedBuilder() diff --git a/src/server/routes/api.js b/src/server/routes/api.js index e78636f..90fe4b7 100644 --- a/src/server/routes/api.js +++ b/src/server/routes/api.js @@ -15,7 +15,7 @@ import * as csSkinService from "../../services/csSkin.service.js"; import { activePolls, activePredis, activeSlowmodes, skins, activeSnakeGames } from "../../game/state.js"; // --- Utility and API Imports --- -import { formatTime, isMeleeSkin, isVCTSkin, isChampionsSkin, getVCTRegion } from "../../utils/index.js"; +import { formatTime, isMeleeSkin, isVCTSkin, isChampionsSkin, getVCTRegion, resolveUser, resolveMember } from "../../utils/index.js"; import { DiscordRequest } from "../../api/discord.js"; // --- Discord.js Builder Imports --- @@ -64,7 +64,7 @@ export function apiRoutes(client, io) { router.post("/register-user", requireAuth, async (req, res) => { const discordUserId = req.userId; - const discordUser = await client.users.fetch(discordUserId); + const discordUser = await resolveUser(client, discordUserId); try { await userService.insertUser({ @@ -594,7 +594,7 @@ export function apiRoutes(client, io) { router.get("/user/:id/avatar", async (req, res) => { try { - const user = await client.users.fetch(req.params.id); + const user = await resolveUser(client, req.params.id); const avatarUrl = user.displayAvatarURL({ format: "png", size: 256 }); res.json({ avatarUrl }); } catch (error) { @@ -604,7 +604,7 @@ export function apiRoutes(client, io) { router.get("/user/:id/username", async (req, res) => { try { - const user = await client.users.fetch(req.params.id); + const user = await resolveUser(client, req.params.id); res.json({ user }); } catch (error) { res.status(404).json({ error: "User not found." }); @@ -729,8 +729,8 @@ export function apiRoutes(client, io) { router.post("/timedout", requireAuth, async (req, res) => { try { const userId = req.userId; - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const member = await guild.members.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const member = await resolveMember(guild, userId); res.status(200).json({ isTimedOut: member?.isCommunicationDisabled() || false }); } catch (e) { res.status(404).send({ message: "Member not found or guild unavailable." }); @@ -747,8 +747,8 @@ export function apiRoutes(client, io) { if (commandUser.coins < 1000) return res.status(403).json({ message: "Pas assez de FlopoCoins (1000 requis)." }); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const member = await guild.members.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const member = await resolveMember(guild, userId); const old_nickname = member.nickname; await member.setNickname(nickname); @@ -766,7 +766,7 @@ export function apiRoutes(client, io) { console.log(`${commandUserId} change nickname of ${userId}: ${old_nickname} -> ${nickname}`); try { - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a modifié le pseudo de <@${userId}>`) .addFields( @@ -802,7 +802,7 @@ export function apiRoutes(client, io) { if (commandUser.coins < 5000) return res.status(403).json({ message: "Pas assez de coins" }); try { - const discordUser = await client.users.fetch(userId); + const discordUser = await resolveUser(client, userId); await discordUser.send(`<@${userId}>`); @@ -820,8 +820,8 @@ export function apiRoutes(client, io) { await emitDataUpdated({ table: "users", action: "update" }); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a envoyé un spam ping à <@${userId}>`) .setColor("#5865f2") @@ -877,8 +877,8 @@ export function apiRoutes(client, io) { }); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a retiré son slowmode`) .setColor("#5865f2") @@ -920,8 +920,8 @@ export function apiRoutes(client, io) { await emitDataUpdated({ table: "users", action: "update" }); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a mis <@${userId}> en slowmode pendant 1h`) .setColor("#5865f2") @@ -952,8 +952,8 @@ export function apiRoutes(client, io) { if (!user) return res.status(403).send({ message: "Oups petit problème" }); - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const member = await guild.members.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const member = await resolveMember(guild, userId); if (userId === commandUserId) { if ( @@ -988,7 +988,7 @@ export function apiRoutes(client, io) { }); try { - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a retiré son time-out`) .setColor("#5865f2") @@ -1035,7 +1035,7 @@ export function apiRoutes(client, io) { await emitDataUpdated({ table: "users", action: "update" }); try { - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${commandUserId}> a time-out <@${userId}> pour 12h`) .setColor("#5865f2") @@ -1076,8 +1076,8 @@ export function apiRoutes(client, io) { let msgId; try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle(`Prédiction de ${commandUser.username}`) .setDescription(`**${label}**`) @@ -1298,8 +1298,8 @@ export function apiRoutes(client, io) { } try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.GENERAL_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.GENERAL_CHANNEL_ID); const message = await generalChannel.messages.fetch(activePredis[predi].msgId); const updatedEmbed = new EmbedBuilder() .setTitle(`Prédiction de ${commandUser.username}`) @@ -1570,7 +1570,7 @@ export function apiRoutes(client, io) { // Notify user via Discord if possible try { - const discordUser = await client.users.fetch(commandUserId); + const discordUser = await resolveUser(client, commandUserId); await discordUser.send( `✅ Votre achat de ${expectedCoins} FlopoCoins a été confirmé ! Merci pour votre soutien !`, ); diff --git a/src/server/routes/blackjack.js b/src/server/routes/blackjack.js index 5d01d99..4721401 100644 --- a/src/server/routes/blackjack.js +++ b/src/server/routes/blackjack.js @@ -21,6 +21,7 @@ import { client } from "../../bot/client.js"; import { emitToast, emitUpdate, emitPlayerUpdate } from "../socket.js"; import { EmbedBuilder, time } from "discord.js"; import { requireAuth } from "../middleware/auth.js"; +import { resolveUser } from "../../utils/index.js"; export function blackjackRoutes(io) { const router = express.Router(); @@ -126,7 +127,7 @@ export function blackjackRoutes(io) { const userId = req.userId; if (room.players[userId]) return res.status(200).json({ message: "Already here" }); - const user = await client.users.fetch(userId); + const user = await resolveUser(client, userId); const bank = (await userService.getUser(userId))?.coins ?? 0; room.players[userId] = { @@ -155,8 +156,8 @@ export function blackjackRoutes(io) { }; try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setDescription(`<@${userId}> joue au Blackjack`) .addFields( @@ -194,8 +195,8 @@ export function blackjackRoutes(io) { if (!room.players[userId]) return res.status(403).json({ message: "not in room" }); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); const msg = await generalChannel.messages.fetch(room.players[userId].msgId); const updatedEmbed = new EmbedBuilder() .setDescription(`<@${userId}> a quitté la table de Blackjack.`) @@ -226,7 +227,7 @@ export function blackjackRoutes(io) { } else { delete room.players[userId]; emitUpdate("player-left", snapshot(room)); - const user = await client.users.fetch(userId); + const user = await resolveUser(client, userId); emitPlayerUpdate({ id: userId, msg: `${user?.globalName || user?.username} a quitté la table de Blackjack.`, @@ -367,7 +368,7 @@ export function blackjackRoutes(io) { // Remove leavers for (const userId of Object.keys(room.leavingAfterRound)) { delete room.players[userId]; - const user = await client.users.fetch(userId); + const user = await resolveUser(client, userId); emitPlayerUpdate({ id: userId, msg: `${user?.globalName || user?.username} a quitté la table de Blackjack.`, diff --git a/src/server/routes/erinyes.js b/src/server/routes/erinyes.js index d4c5b51..26ab183 100644 --- a/src/server/routes/erinyes.js +++ b/src/server/routes/erinyes.js @@ -2,6 +2,7 @@ import express from "express"; import { v4 as uuidv4 } from "uuid"; import { erinyesRooms } from "../../game/state.js"; import { socketEmit } from "../socket.js"; +import { resolveUser } from "../../utils/index.js"; const router = express.Router(); @@ -35,7 +36,7 @@ export function erinyesRoutes(client, io) { res.status(404).json({ message: "You are already in a room." }); } - const creator = await client.users.fetch(creatorId); + const creator = await resolveUser(client, creatorId); const id = uuidv4(); createRoom({ diff --git a/src/server/routes/poker.js b/src/server/routes/poker.js index f36db1e..2744500 100644 --- a/src/server/routes/poker.js +++ b/src/server/routes/poker.js @@ -16,7 +16,7 @@ import { sleep } from "openai/core"; import { client } from "../../bot/client.js"; import { emitPokerToast, emitPokerUpdate } from "../socket.js"; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js"; -import { formatAmount } from "../../utils/index.js"; +import { formatAmount, resolveUser } from "../../utils/index.js"; import { requireAuth } from "../middleware/auth.js"; const { Hand } = pkg; @@ -53,8 +53,8 @@ export function pokerRoutes(client, io) { return res.status(403).json({ message: "You are already in a poker room." }); } - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const creator = await client.users.fetch(creatorId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const creator = await resolveUser(client, creatorId); const id = uuidv4(); const name = uniqueNamesGenerator({ dictionaries: [adjectives, ["Poker"]], @@ -91,7 +91,7 @@ export function pokerRoutes(client, io) { await emitPokerUpdate({ room: pokerRooms[id], type: "room-created" }); try { - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle("Flopoker 🃏") .setDescription(`<@${creatorId}> a créé une table de poker`) @@ -365,7 +365,7 @@ export function pokerRoutes(client, io) { // --- Helper Functions --- async function joinRoom(roomId, userId, io) { - const user = await client.users.fetch(userId); + const user = await resolveUser(client, userId); const userDB = await userService.getUser(userId); const room = pokerRooms[roomId]; diff --git a/src/server/socket.js b/src/server/socket.js index b222ede..08a0b90 100644 --- a/src/server/socket.js +++ b/src/server/socket.js @@ -17,6 +17,7 @@ import { } from "../game/various.js"; import { eloHandler } from "../game/elo.js"; import { verifyToken } from "./middleware/auth.js"; +import { resolveUser } from "../utils/index.js"; // --- Module-level State --- let io; @@ -319,7 +320,7 @@ async function createGame(client, gameType) { const { queue, activeGames, title } = getGameAssets(gameType); const p1Id = queue.shift(); const p2Id = queue.shift(); - const [p1, p2] = await Promise.all([client.users.fetch(p1Id), client.users.fetch(p2Id)]); + const [p1, p2] = await Promise.all([resolveUser(client, p1Id), resolveUser(client, p2Id)]); let lobby; if (gameType === "tictactoe") { @@ -426,9 +427,9 @@ async function refreshQueuesForUser(userId, client) { if (index > -1) { tictactoeQueue.splice(index, 1); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); - const user = await client.users.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); + const user = await resolveUser(client, userId); const queueMsg = await generalChannel.messages.fetch(queueMessagesEndpoints[userId]); const updatedEmbed = new EmbedBuilder() .setTitle("Tic Tac Toe") @@ -446,9 +447,9 @@ async function refreshQueuesForUser(userId, client) { if (index > -1) { connect4Queue.splice(index, 1); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); - const user = await client.users.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); + const user = await resolveUser(client, userId); const queueMsg = await generalChannel.messages.fetch(queueMessagesEndpoints[userId]); const updatedEmbed = new EmbedBuilder() .setTitle("Puissance 4") @@ -466,9 +467,9 @@ async function refreshQueuesForUser(userId, client) { if (index > -1) { snakeQueue.splice(index, 1); try { - const guild = await client.guilds.fetch(process.env.GUILD_ID); - const generalChannel = await guild.channels.fetch(process.env.BOT_CHANNEL_ID); - const user = await client.users.fetch(userId); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const generalChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); + const user = await resolveUser(client, userId); const queueMsg = await generalChannel.messages.fetch(queueMessagesEndpoints[userId]); const updatedEmbed = new EmbedBuilder() .setTitle("Snake 1v1") @@ -491,7 +492,7 @@ async function emitQueueUpdate(client, gameType) { const { queue, activeGames } = getGameAssets(gameType); const names = await Promise.all( queue.map(async (id) => { - const user = await client.users.fetch(id).catch(() => null); + const user = await resolveUser(client, id).catch(() => null); return user?.globalName || user?.username; }), ); @@ -528,8 +529,8 @@ function getGameAssets(gameType) { async function postQueueToDiscord(client, playerId, title, url) { try { - const generalChannel = await client.channels.fetch(process.env.BOT_CHANNEL_ID); - const user = await client.users.fetch(playerId); + const generalChannel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); + const user = await resolveUser(client, playerId); const embed = new EmbedBuilder() .setTitle(title) .setDescription(`**${user.globalName || user.username}** est dans la file d'attente.`) @@ -552,7 +553,7 @@ async function postQueueToDiscord(client, playerId, title, url) { } async function updateDiscordMessage(client, game, title, resultText = "") { - const channel = await client.channels.fetch(process.env.BOT_CHANNEL_ID).catch(() => null); + const channel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); if (!channel) return null; let description; diff --git a/src/utils/index.js b/src/utils/index.js index 8f693c4..2a2bb2e 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -37,7 +37,7 @@ export async function getAkhys(client) { try { // 1. Fetch Discord Members const initial_akhys = (await userService.getAllUsers()).length; - const guild = await client.guilds.fetch(process.env.GUILD_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); const members = await guild.members.fetch(); const akhys = members.filter((m) => !m.user.bot && m.roles.cache.has(process.env.AKHY_ROLE_ID)); @@ -547,3 +547,11 @@ export function isChampionsSkin(skinName) { const name = skinName.toLowerCase(); return name.includes("champions"); } + +export async function resolveUser(client, userId) { + return client.users.cache.get(userId) || await client.users.fetch(userId); +} + +export async function resolveMember(guild, userId) { + return guild.members.cache.get(userId) || await guild.members.fetch(userId); +} diff --git a/src/utils/marketNotifs.js b/src/utils/marketNotifs.js index b6a27ae..a2aa4a9 100644 --- a/src/utils/marketNotifs.js +++ b/src/utils/marketNotifs.js @@ -3,6 +3,7 @@ import * as skinService from "../services/skin.service.js"; import * as csSkinService from "../services/csSkin.service.js"; import * as marketService from "../services/market.service.js"; import { EmbedBuilder } from "discord.js"; +import { resolveUser } from "./index.js"; /** * Gets the skin display name and icon from an offer, supporting both Valorant and CS2 skins. @@ -24,7 +25,7 @@ export async function handleNewMarketOffer(offerId, client) { if (!offer) return; const { name: skinName, icon: skinIcon } = await getOfferSkinInfo(offer); - const discordUserSeller = await client.users.fetch(offer.sellerId); + const discordUserSeller = await resolveUser(client, offer.sellerId); try { const userSeller = await userService.getUser(offer.sellerId); if (discordUserSeller && userSeller?.isAkhy) { @@ -67,7 +68,7 @@ export async function handleNewMarketOffer(offerId, client) { } try { - const guildChannel = await client.channels.fetch(process.env.BOT_CHANNEL_ID); + const guildChannel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle("🔔 Nouvelle offre") .setDescription(`Une offre pour le skin **${skinName}** a été créée !`) @@ -105,7 +106,7 @@ export async function handleMarketOfferOpening(offerId, client) { const { name: skinName, icon: skinIcon } = await getOfferSkinInfo(offer); try { - const discordUserSeller = await client.users.fetch(offer.sellerId); + const discordUserSeller = await resolveUser(client, offer.sellerId); const userSeller = await userService.getUser(offer.sellerId); if (discordUserSeller && userSeller?.isAkhy) { const embed = new EmbedBuilder() @@ -145,7 +146,7 @@ export async function handleMarketOfferOpening(offerId, client) { } try { - const guildChannel = await client.channels.fetch(process.env.BOT_CHANNEL_ID); + const guildChannel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle("🔔 Début des enchères") .setDescription( @@ -177,7 +178,7 @@ export async function handleMarketOfferClosing(offerId, client) { const { name: skinName, icon: skinIcon } = await getOfferSkinInfo(offer); const bids = await marketService.getOfferBids(offer.id); - const discordUserSeller = await client.users.fetch(offer.sellerId); + const discordUserSeller = await resolveUser(client, offer.sellerId); try { const userSeller = await userService.getUser(offer.sellerId); if (discordUserSeller && userSeller?.isAkhy) { @@ -204,7 +205,7 @@ export async function handleMarketOfferClosing(offerId, client) { ); } else { const highestBid = bids[0]; - const highestBidderUser = await client.users.fetch(highestBid.bidderId); + const highestBidderUser = await resolveUser(client, highestBid.bidderId); embed.addFields( { name: "✅ Enchères terminées avec succès !", @@ -225,8 +226,8 @@ export async function handleMarketOfferClosing(offerId, client) { } try { - const guild = await client.guilds.fetch(process.env.BOT_GUILD_ID); - const guildChannel = await guild.channels?.fetch(process.env.BOT_CHANNEL_ID); + const guild = client.guilds.cache.get(process.env.GUILD_ID); + const guildChannel = guild.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle("🔔 Fin des enchères") .setDescription( @@ -243,12 +244,12 @@ export async function handleMarketOfferClosing(offerId, client) { }); } else { const highestBid = bids[0]; - const highestBidderUser = await client.users.fetch(highestBid.bidderId); + const highestBidderUser = await resolveUser(client, highestBid.bidderId); embed.addFields({ name: "✅ Enchères terminées avec succès !", value: `Le skin de <@${offer.sellerId}> ${discordUserSeller ? "(" + discordUserSeller.username + ")" : ""} a été vendu pour \`${highestBid.offerAmount} coins\` à <@${highestBid.bidderId}> ${highestBidderUser ? "(" + highestBidderUser.username + ")" : ""}.`, }); - const discordUserBidder = await client.users.fetch(highestBid.bidderId); + const discordUserBidder = await resolveUser(client, highestBid.bidderId); const userBidder = await userService.getUser(highestBid.bidderId); if (discordUserBidder && userBidder?.isAkhy) { const bidderEmbed = new EmbedBuilder() @@ -280,9 +281,9 @@ export async function handleNewMarketOfferBid(offerId, bidId, client) { if (!bid) return; const { name: skinName, icon: skinIcon } = await getOfferSkinInfo(offer); - const bidderUser = client.users.fetch(bid.bidderId); + const bidderUser = await resolveUser(client, bid.bidderId); try { - const discordUserSeller = await client.users.fetch(offer.sellerId); + const discordUserSeller = await resolveUser(client, offer.sellerId); const userSeller = await userService.getUser(offer.sellerId); if (discordUserSeller && userSeller?.isAkhy) { @@ -323,7 +324,7 @@ export async function handleNewMarketOfferBid(offerId, bidId, client) { } try { - const discordUserNewBidder = await client.users.fetch(bid.bidderId); + const discordUserNewBidder = await resolveUser(client, bid.bidderId); const userNewBidder = await userService.getUser(bid.bidderId); if (discordUserNewBidder && userNewBidder?.isAkhy) { const embed = new EmbedBuilder() @@ -350,7 +351,7 @@ export async function handleNewMarketOfferBid(offerId, bidId, client) { const offerBids = await marketService.getOfferBids(offer.id); if (offerBids.length < 2) return; - const discordUserPreviousBidder = await client.users.fetch(offerBids[1].bidderId); + const discordUserPreviousBidder = await resolveUser(client, offerBids[1].bidderId); const userPreviousBidder = await userService.getUser(offerBids[1].bidderId); if (discordUserPreviousBidder && userPreviousBidder?.isAkhy) { const embed = new EmbedBuilder() @@ -382,10 +383,10 @@ export async function handleNewMarketOfferBid(offerId, bidId, client) { } export async function handleCaseOpening(caseType, userId, skinUuid, client) { - const discordUser = await client.users.fetch(userId); + const discordUser = await resolveUser(client, userId); const skin = await skinService.getSkin(skinUuid); try { - const guildChannel = await client.channels.fetch(process.env.BOT_CHANNEL_ID); + const guildChannel = client.channels.cache.get(process.env.BOT_CHANNEL_ID); const embed = new EmbedBuilder() .setTitle("🔔 Ouverture de caisse") .setDescription(