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) {
- try {
- await interaction.deferReply();
- } catch (error) {
- console.error('Erro ao adiar a resposta:', error.message);
- return;
- }
- const nick = interaction.options.getString('nick');
- let playerData;
- let isBanned = false;
- try {
- const response = await axios.get(`https://mush.com.br/api/player/${encodeURIComponent(nick)}`, {
- timeout: 15000,
- headers: {
- 'User-Agent': 'SuecoTweakerBot/1.0',
- },
- });
- // Logar a resposta completa para depuração
- console.log(`Resposta da API para ${nick} (status: ${response.status}):`, JSON.stringify(response.data, null, 2));
- // Verificar se response.data é um objeto válido
- if (!response.data || typeof response.data !== 'object') {
- const embed = new EmbedBuilder()
- .setTitle('❌ Erro ao Consultar a API')
- .setDescription(`Os dados retornados para o jogador \`${nick}\` são inválidos.`)
- .setColor('#4B0082')
- .setTimestamp();
- await interaction.editReply({ embeds: [embed] });
- return;
- }
- playerData = response.data;
- // Achatar o JSON para facilitar a busca
- const flatData = flattenJSON(playerData);
- // Procurar por chaves relacionadas a banimento
- 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();
- let message;
- try {
- message = await interaction.editReply({ embeds: [embed], fetchReply: true });
- } catch (error) {
- console.error('Erro ao enviar a mensagem inicial:', error.message);
- return;
- }
- 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)
- );
- try {
- await message.edit({ embeds: [embed], components: [row] });
- } catch (error) {
- console.error('Erro ao editar a mensagem para perguntar sobre estatísticas:', error.message);
- return;
- }
- const collector = message.createMessageComponentCollector({
- filter: i => i.user.id === interaction.user.id,
- time: 60000,
- });
- collector.on('collect', async i => {
- try {
- 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 => {
- try {
- 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();
- } catch (error) {
- console.error('Erro ao atualizar a mensagem com o formato das estatísticas:', error.message);
- await interaction.followUp({
- content: 'Ocorreu um erro ao exibir as estatísticas. Por favor, tente novamente mais tarde.',
- ephemeral: true
- });
- }
- });
- formatCollector.on('end', () => {
- if (message.components.length > 0) {
- message.edit({ components: [] }).catch(err => {
- console.error('Erro ao remover botões do formatCollector:', err.message);
- });
- }
- });
- } 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: []
- });
- }
- } catch (error) {
- console.error('Erro ao processar a interação do botão:', error.message);
- await interaction.followUp({
- content: 'Ocorreu um erro ao processar sua escolha. Por favor, tente novamente.',
- ephemeral: true
- });
- }
- });
- collector.on('end', () => {
- if (message.components.length > 0) {
- message.edit({ components: [] }).catch(err => {
- console.error('Erro ao remover botões do collector:', err.message);
- });
- }
- });
- } catch (error) {
- console.error(`Erro ao verificar punição para ${nick}:`, error.message);
- const embed = new EmbedBuilder()
- .setTitle('❌ Erro ao Consultar a API')
- .setColor('#4B0082')
- .setTimestamp();
- if (error.response?.status === 404) {
- embed.setDescription(`O jogador \`${nick}\` nunca se registrou no MushMC.`);
- } else if (error.response?.status === 403) {
- embed.setDescription(
- `Não foi possível consultar o jogador \`${nick}\`.\n` +
- 'A API do MushMC retornou um erro 403 (Forbidden), indicando que o acesso foi negado.\n' +
- 'Possíveis causas:\n' +
- '- O bot não tem permissão para acessar a API (pode ser necessário uma chave de API).\n' +
- '- O IP do bot foi bloqueado pela API.\n' +
- 'Por favor, verifique as configurações da API ou contate o suporte do MushMC.'
- );
- } else {
- embed.setDescription(`Ocorreu um erro ao consultar a API para o jogador \`${nick}\`: ${error.message}`);
- }
- await interaction.editReply({ embeds: [embed] }).catch(err => {
- console.error('Erro ao enviar mensagem de erro:', err.message);
- });
- }
- },
- };
- 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