Untitled

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

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, interval = 'weekly', mode = 'ALL_MODES') {
    try {
        const response = await axios.get(`https://stats.pika-network.net/api/profile/${playerIGN}/leaderboard?type=bedwars&interval=${interval}&mode=${mode}`);
        return response.data;
    } catch (error) {
        console.error(`Error fetching stats for ${playerIGN}:`, error.message);
        return null;
    }
}

async function main(interval = 'weekly', mode = 'ALL_MODES') {
    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, interval, mode);
            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') {
        const interval = interaction.options.getString('interval') || 'weekly';
        const mode = interaction.options.getString('mode') || 'ALL_MODES';
        await interaction.deferReply(); // Acknowledge the command
        
        try {
            const { memberStats, failedMembers } = await main(interval, mode);
            
            let statsMessage = `Guild Bedwars Stats (Interval: ${interval}, Mode: ${mode})\n`;
            memberStats.forEach((memberStat, index) => {
                statsMessage += `#${index + 1}. \`${memberStat.username}\` - ${memberStat.wins} wins\n`;
            });
            
            if (failedMembers.length > 0) {
                failedMembers.forEach(failedMember => {
                    statsMessage += `\nFailed to retrieve stats for ${failedMember}. They might have their API turned off.\n`;
                });
            }
            
            await interaction.editReply(statsMessage); // Send the stats
            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);




// const { EmbedBuilder } = require('discord.js');
// const Discord = require('discord.js');
// const client = new Discord.Client({ intents: ['Guilds', 'GuildMessages'] });
// const axios = require('axios');

// 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) {
//         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);
//         }
//     }

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

//     return { memberStats, failedMembers };
// }

// const token = 'MTIwMjIyODYzNTY3OTg1ODcyOA.GK-qOK.tQzNJVuvKQXNUsz5rtbS7YZbUWSlQ34Zr3459Y';

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

// client.on('messageCreate', async (message) => {
//     if (!message.content.startsWith('!gstats')) return;

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

//         const embed = new MessageEmbed()
//             .setColor('#0099FF')
//             .setTitle('Guild Bedwars Stats')
//             .setDescription('Weekly Bedwars stats for guild members.');

//         memberStats.forEach((memberStat, index) => {
//             embed.addField(`#${index + 1}. ${memberStat.username}`, `${memberStat.wins} wins`);
//         });

//         const channel = client.channels.cache.get(process.env.CHANNEL_ID);
//         if (channel) {
//             channel.send({ embeds: [embed] });

//             for (const failedMember of failedMembers) {
//                 const failedMessage = `Unable to retrieve stats for \`${failedMember}\`. They might have their API turned off.`;
//                 channel.send(failedMessage);
//             }
//             console.log('Failed members messages sent successfully.');
//         } else {
//             console.error('Channel not found.');
//         }
//     } catch (error) {
//         console.error('Error retrieving guild stats:', error.message);
//     }
// });

// client.login(token);
Leave a Comment