Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.3 kB
2
Indexable
Never
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ['Guilds', 'GuildMessages'] });
const axios = require('axios');
require('dotenv').config();
const {  EmbedBuilder  } = require('discord.js');

async function getGuildMembers() {
    try {
        const response = await axios.get('https://stats.pika-network.net/api/clans/THEBOIS');
        const guildData = response.data;

        if (!guildData || !guildData.members || !Array.isArray(guildData.members)) {
            console.error('Invalid guild data format');
            return [];
        }

        const memberUsernames = guildData.members.map(member => member.user.username);
        return memberUsernames;
    } catch (error) {
        console.error('Error fetching guild members:', error.message);
        return [];
    }
}

async function getPlayerStats(playerIGN) {
    try {
        const response = await axios.get(`https://stats.pika-network.net/api/profile/${playerIGN}/leaderboard?type=bedwars&interval=weekly&mode=all_modes`);
        return response.data;
    } catch (error) {
        console.error(`Error fetching stats for ${playerIGN}:`, error.message);
        return null;
    }
}

async function main() {
    const memberUsernames = await getGuildMembers();
    if (memberUsernames.length === 0) {
        console.error('No guild members found.');
        return { memberStats: [], failedMembers: [] };
    }

    const memberStats = [];
    const failedMembers = [];

    for (const username of memberUsernames) {
        try {
            // Introduce a delay between API requests to avoid rate-limiting
            await new Promise(resolve => setTimeout(resolve, 500));

            const stats = await getPlayerStats(username);
            if (stats) {
                const memberStat = {
                    username,
                    wins: 0
                };
                if (stats['Wins'] && stats['Wins'].entries && stats['Wins'].entries.length > 0) {
                    const entry = stats['Wins'].entries.find(entry => entry.id === username);
                    if (entry) {
                        memberStat['wins'] = entry.value || 0;
                    }
                }
                memberStats.push(memberStat);
            } else {
                console.log(`Unable to retrieve stats for ${username}. Their API may be turned off.`);
                failedMembers.push(username);
            }
        } catch (error) {
            console.error(`Error fetching stats for ${username}:`, error.message);
            failedMembers.push(username);
        }
    }

    // Sort memberStats by wins in descending order
    memberStats.sort((a, b) => b.wins - a.wins);

    return { memberStats, failedMembers };
}

client.once('ready', () => {
    console.log('Bot is ready!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    if (interaction.commandName === 'gstats') {
        await interaction.deferReply(); // Acknowledge the command

        try {
            const { memberStats, failedMembers } = await main();

            const embed = new EmbedBuilder()
                .setColor('#0099FF')
                .setTitle('Guild Bedwars Stats')
                .setDescription('Here are the bedwars stats for the guild members.');

            let statArray = [];
            memberStats.forEach((memberStat, index) => {
                statArray.push({ name: `#${index + 1}. ${memberStat.username}`, value: `Wins: ${memberStat.wins}`, inline: true });
            });
            embed.addFields(statArray);

            if (failedMembers.length > 0) {
                embed.addField('Failed to retrieve stats for the following members:', failedMembers.join('\n'));
            }

            await interaction.editReply({ embeds: [embed] }); // Send the embed
            console.log('Guild stats sent successfully.');
        } catch (error) {
            console.error('Error retrieving guild stats:', error.message);
            await interaction.editReply('An error occurred while retrieving guild stats.');
        }
    }
});

client.login(process.env.TOKEN);
Leave a Comment