Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, AttachmentBuilder } = require('discord.js');
- const axios = require('axios');
- module.exports = {
- data: new SlashCommandBuilder()
- .setName('verificarpunicao')
- .setDescription('Verifica se um jogador foi banido no servidor Mush')
- .addStringOption(option =>
- option
- .setName('nick')
- .setDescription('Nome do jogador a ser verificado (ex.: DaysBeforeRodeo)')
- .setRequired(true)
- ),
- async execute(interaction) {
- await interaction.deferReply({ withResponse: true });
- const nick = interaction.options.getString('nick');
- let isBanned = false;
- let playerData;
- console.log(`[Requisição 1/1] Obtendo informações para ${nick}...`);
- const playerUrl = `https://mush.com.br/api/player/${encodeURIComponent(nick)}`;
- console.log(`URL da requisição: ${playerUrl}`);
- try {
- // Usar ZenRows para fazer a requisição
- const zenRowsApiKey = '';
- const zenRowsUrl = `https://api.zenrows.com/v1/?apikey=${zenRowsApiKey}&url=${encodeURIComponent(playerUrl)}&js_render=true&wait=5000`;
- const response = await axios.get(zenRowsUrl, {
- timeout: 30000,
- headers: {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
- },
- });
- // Logar o conteúdo bruto para depuração
- console.log(`Conteúdo bruto retornado para ${nick}:`, response.data);
- // Verificar se a resposta é um JSON válido
- if (typeof response.data === 'string' && !response.data.trim().startsWith('{') && !response.data.trim().startsWith('[')) {
- throw new Error('A resposta não é um JSON válido. Possível erro da API ou bloqueio do Cloudflare.');
- }
- playerData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
- // Verificar se a API retornou uma mensagem de erro
- if (playerData.error || playerData.message) {
- throw new Error(playerData.error || playerData.message || 'Erro desconhecido da API.');
- }
- console.log(`Resposta da API para ${nick}:`, JSON.stringify(playerData, null, 2));
- } catch (error) {
- console.error(`Erro ao consultar a API para ${nick}:`, error.message);
- const embed = new EmbedBuilder()
- .setTitle('❌ Erro ao Consultar a API')
- .setDescription(
- error.message.includes('403')
- ? `A API retornou erro 403 (Forbidden). Possível bloqueio pelo Cloudflare. Tente usar uma chave de API ou contatar o suporte do MushMC.`
- : error.message.includes('not found') || error.message.includes('Player not found')
- ? `Jogador \`${nick}\` não encontrado. Verifique o nome e tente novamente.`
- : `Erro ao consultar a API: ${error.message}`
- )
- .setColor('#4B0082')
- .setTimestamp();
- await interaction.editReply({ embeds: [embed] });
- return;
- }
- const flatData = flattenJSON(playerData);
- const banKeys = ['banned', 'isBanned', 'banStatus', 'is_banned', 'ban_status'];
- for (const key of banKeys) {
- const fullKey = Object.keys(flatData).find(k => k.toLowerCase().endsWith(key.toLowerCase()));
- if (fullKey && flatData[fullKey] === true) {
- isBanned = true;
- break;
- }
- }
- const embed = new EmbedBuilder()
- .setTitle(isBanned ? '⛔ Jogador Banido' : '✅ Jogador Não Banido')
- .setDescription(isBanned
- ? `O jogador \`${nick}\` está banido!`
- : `O jogador \`${nick}\` não foi banido.`)
- .setColor('#4B0082')
- .setTimestamp();
- const message = await interaction.editReply({ embeds: [embed], withResponse: true });
- embed.setDescription(
- (isBanned ? `O jogador \`${nick}\` está banido!` : `O jogador \`${nick}\` não foi banido.`) +
- '\n\nDeseja ver as estatísticas do jogador?'
- );
- const row = new ActionRowBuilder()
- .addComponents(
- new ButtonBuilder()
- .setCustomId('show_stats_yes')
- .setLabel('Sim')
- .setStyle(ButtonStyle.Primary),
- new ButtonBuilder()
- .setCustomId('show_stats_no')
- .setLabel('Não')
- .setStyle(ButtonStyle.Secondary)
- );
- await message.edit({ embeds: [embed], components: [row] });
- const collector = message.createMessageComponentCollector({
- filter: i => i.user.id === interaction.user.id,
- time: 60000,
- });
- collector.on('collect', async i => {
- if (i.customId === 'show_stats_yes') {
- embed.setTitle('📊 Formato das Estatísticas')
- .setDescription('Em qual formato você deseja ver as estatísticas?');
- const formatRow = new ActionRowBuilder()
- .addComponents(
- new ButtonBuilder()
- .setCustomId('format_text')
- .setLabel('Formato de Texto')
- .setStyle(ButtonStyle.Primary),
- new ButtonBuilder()
- .setCustomId('format_json')
- .setLabel('Formato JSON')
- .setStyle(ButtonStyle.Secondary)
- );
- await i.update({
- embeds: [embed],
- components: [formatRow]
- });
- const formatCollector = message.createMessageComponentCollector({
- filter: f => f.user.id === interaction.user.id,
- time: 60000,
- });
- formatCollector.on('collect', async f => {
- if (f.customId === 'format_text') {
- const statsText = formatStatsAsText(playerData);
- embed.setTitle(`📊 Estatísticas de \`${nick}\``);
- if (statsText.length > 2000) {
- const attachment = new AttachmentBuilder(
- Buffer.from(statsText, 'utf-8'),
- { name: 'estatisticas.txt' }
- );
- embed.setDescription('As estatísticas são muito longas para exibir aqui. Veja o arquivo abaixo:');
- await f.update({
- embeds: [embed],
- components: [],
- files: [attachment]
- });
- } else {
- embed.setDescription(statsText);
- await f.update({
- embeds: [embed],
- components: []
- });
- }
- } else if (f.customId === 'format_json') {
- const statsJSON = JSON.stringify(playerData, null, 2);
- embed.setTitle(`📊 Estatísticas de \`${nick}\` (JSON)`);
- if (statsJSON.length > 2000) {
- const attachment = new AttachmentBuilder(
- Buffer.from(statsJSON, 'utf-8'),
- { name: 'estatisticas.json' }
- );
- embed.setDescription('As estatísticas em JSON são muito longas para exibir aqui. Veja o arquivo abaixo:');
- await f.update({
- embeds: [embed],
- components: [],
- files: [attachment]
- });
- } else {
- embed.setDescription(`\`\`\`json\n${statsJSON}\n\`\`\``);
- await f.update({
- embeds: [embed],
- components: []
- });
- }
- }
- formatCollector.stop();
- });
- formatCollector.on('end', () => {
- if (message.components.length > 0) {
- message.edit({ components: [] });
- }
- });
- } else if (i.customId === 'show_stats_no') {
- embed.setDescription(isBanned
- ? `O jogador \`${nick}\` está banido!`
- : `O jogador \`${nick}\` não foi banido.`);
- await i.update({
- embeds: [embed],
- components: []
- });
- }
- });
- collector.on('end', () => {
- if (message.components.length > 0) {
- message.edit({ components: [] });
- }
- });
- },
- };
- function flattenJSON(obj, parentKey = '', result = {}) {
- for (const key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- const newKey = parentKey ? `${parentKey}.${key}` : key;
- if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
- flattenJSON(obj[key], newKey, result);
- } else {
- result[newKey] = obj[key];
- }
- }
- }
- return result;
- }
- function formatStatsAsText(data) {
- const flatData = flattenJSON(data);
- const lines = [];
- for (const key in flatData) {
- if (Object.prototype.hasOwnProperty.call(flatData, key)) {
- lines.push(`${key}: ${flatData[key]}`);
- }
- }
- return lines.join('\n');
- }
Advertisement
Add Comment
Please, Sign In to add comment