From 9bd4205243cf7841d7d5f32295ab53c362022b85 Mon Sep 17 00:00:00 2001 From: VinceC <33974776+VinceC3@users.noreply.github.com> Date: Fri, 18 Oct 2024 10:10:14 -0500 Subject: [PATCH] Update index.js --- index.js | 263 +++++++------------------------------------------------ 1 file changed, 30 insertions(+), 233 deletions(-) diff --git a/index.js b/index.js index 513e3af..5117dc6 100644 --- a/index.js +++ b/index.js @@ -33,6 +33,11 @@ client.login(process.env.BOT_TOKEN).then(() => { console.error('Login failed:', error); }); +// Handle client errors +client.on('error', (error) => { + console.error('The client encountered an error:', error); +}); + // Function to fetch user data from the API async function findUserByUsername(username) { try { @@ -75,249 +80,41 @@ function getBadgeImageUrl(badgeName) { client.on('interactionCreate', async (interaction) => { if (!interaction.isCommand()) return; - const { commandName } = interaction; + try { + const { commandName } = interaction; - if (commandName === 'ping') { - await interaction.reply('Pong!'); - } else if (commandName === 'finduser') { - const username = interaction.options.getString('username'); - const gameFilter = interaction.options.getString('game'); + if (commandName === 'ping') { + await interaction.reply('Pong!'); + } else if (commandName === 'finduser') { + await interaction.deferReply(); // Moved up - await interaction.deferReply(); + const username = interaction.options.getString('username'); + const gameFilter = interaction.options.getString('game'); - // Fetch data from the API using the provided username - const userData = await findUserByUsername(username); + // Fetch data from the API using the provided username + const userData = await findUserByUsername(username); - if (userData && userData.success) { - let playerData; - if (typeof userData.player_data === 'string') { - try { - playerData = JSON.parse(userData.player_data); - } catch (error) { - await interaction.editReply('Error parsing player data.'); - return; - } + if (userData && userData.success) { + // ... [Rest of your existing code for processing and sending the embed] + + await interaction.editReply({ embeds: [embed], components: [row] }); } else { - playerData = userData.player_data; - } - - if (!playerData || !playerData.profile) { await interaction.editReply( - 'User found but profile data is unavailable. They may need to log in to VRBattles to update their profile.' - ); - return; - } - - const user = playerData.profile || {}; - const badgeImageUrl = getBadgeImageUrl(user.current_level_badge); - - // Create the embed builder - const embed = new EmbedBuilder() - .setTitle(`User: ${playerData.username || 'Unknown'}`) - .setDescription(`Bio: ${user.bio || 'No bio available'}`) - .setColor('#0099ff'); - - // Set thumbnail if avatar is available - if (user.avatar) { - embed.setThumbnail( - `https://www.vrbattles.gg/assets/uploads/profile/${user.avatar}` + 'User not found or an error occurred while fetching data.' ); } + } + } catch (error) { + console.error('Error handling interaction:', error); - // Before adding fields to the embed, initialize a counter - let totalFields = 0; - - // Add profile fields dynamically - const profileFields = []; - - if (user.country) - profileFields.push({ - name: 'Country', - value: user.country, - inline: true, - }); - if (user.rank) - profileFields.push({ name: 'Rank', value: user.rank, inline: true }); - if (user.level) - profileFields.push({ - name: 'Level', - value: user.level.toString(), - inline: true, - }); - if (user.prestige) - profileFields.push({ - name: 'Prestige', - value: user.prestige.toString(), - inline: true, - }); - if (user.xp) - profileFields.push({ - name: 'Total XP', - value: user.xp.toString(), - inline: true, - }); - - if (profileFields.length > 0) { - embed.addFields(profileFields); - totalFields += profileFields.length; + try { + if (interaction.deferred || interaction.replied) { + await interaction.followUp({ content: 'An error occurred while processing your request.', ephemeral: true }); + } else { + await interaction.reply({ content: 'An error occurred while processing your request.', ephemeral: true }); } - - // Set badge image if available - if (badgeImageUrl) { - embed.setImage(badgeImageUrl); - } - - // Dynamically add game statistics - const games = playerData.stats?.games; - if (games && Object.keys(games).length > 0 && totalFields < 25) { - if (totalFields + 1 <= 25) { - embed.addFields({ name: '\u200B', value: '**Game Statistics**' }); - totalFields += 1; - } - - for (const [gameName, gameData] of Object.entries(games)) { - if ( - gameFilter && - gameName.toLowerCase() !== gameFilter.toLowerCase() - ) { - continue; // Skip games that don't match the filter - } - - for (const [modeName, modeStats] of Object.entries(gameData)) { - const statsFields = []; - - // Collect stats for the mode - if (modeStats.matches) - statsFields.push({ - name: 'Matches', - value: modeStats.matches.toString(), - inline: true, - }); - if (modeStats.wins) - statsFields.push({ - name: 'Wins', - value: modeStats.wins.toString(), - inline: true, - }); - if (modeStats.losses) - statsFields.push({ - name: 'Losses', - value: modeStats.losses.toString(), - inline: true, - }); - if (modeStats.win_rate) - statsFields.push({ - name: 'Win Rate', - value: modeStats.win_rate, - inline: true, - }); - if (modeStats.mmr) - statsFields.push({ - name: 'MMR', - value: modeStats.mmr.toString(), - inline: true, - }); - - // Calculate the number of fields to be added - const fieldsToAdd = 1 + statsFields.length; // 1 for the section header - - // Check if adding these fields would exceed the limit - if (totalFields + fieldsToAdd > 25) { - // You can choose to skip adding these fields or break the loop - break; // Stops adding more fields - } - - // Add the section header - embed.addFields({ - name: '\u200B', - value: `**${gameName} - ${modeName}**`, - }); - totalFields += 1; - - // Add the stats fields - embed.addFields(statsFields); - totalFields += statsFields.length; - - // Check after each addition - if (totalFields >= 25) { - break; - } - } - - if (totalFields >= 25) { - break; - } - } - } - - // Add teams dynamically - const teams = playerData.teams; - if (teams && Object.keys(teams).length > 0 && totalFields < 25) { - const teamList = Object.values(teams) - .map( - (team) => - `- **${team.team_name}** (${team.game_name} - ${team.game_mode})` - ) - .join('\n'); - - const teamsField = [ - { name: '\u200B', value: '**Teams**' }, - { name: 'Team List', value: teamList || 'No teams available' }, - ]; - - // Check if adding these fields would exceed the limit - const fieldsToAdd = teamsField.length; - if (totalFields + fieldsToAdd <= 25) { - embed.addFields(teamsField); - totalFields += fieldsToAdd; - } - } - - // Add recent matches dynamically - const matches = playerData.matches; - if (matches && Object.keys(matches).length > 0 && totalFields < 25) { - const matchList = Object.values(matches) - .sort((a, b) => new Date(b.start_time) - new Date(a.start_time)) // Sort by date descending - .slice(0, 3) // Limit to recent 3 matches - .map((match) => { - const date = new Date(match.start_time).toLocaleDateString(); - const team1 = match.team1_name || 'Team 1'; - const team2 = match.team2_name || 'Team 2'; - const score = match.score || 'N/A'; - return `- **${team1}** vs **${team2}** on ${date} - Result: ${score}`; - }) - .join('\n'); - - const matchesField = [ - { name: '\u200B', value: '**Recent Matches**' }, - { name: 'Match History', value: matchList || 'No recent matches' }, - ]; - - // Check if adding these fields would exceed the limit - const fieldsToAdd = matchesField.length; - if (totalFields + fieldsToAdd <= 25) { - embed.addFields(matchesField); - totalFields += fieldsToAdd; - } - } - - // Add action buttons - const row = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setLabel('🔵 View Profile') - .setStyle(ButtonStyle.Link) - .setURL(`https://www.vrbattles.gg/profile/${playerData.username}`), - new ButtonBuilder() - .setLabel('🟡 Join Discord') - .setStyle(ButtonStyle.Link) - .setURL('https://discord.gg/j3DKVATPGQ') // Replace with your Discord invite URL - ); - - await interaction.editReply({ embeds: [embed], components: [row] }); - } else { - await interaction.editReply( - 'User not found or an error occurred while fetching data.' - ); + } catch (replyError) { + console.error('Error sending error message:', replyError); } } }); \ No newline at end of file