Guest User

Untitled

a guest
Apr 29th, 2025
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.27 KB | None | 0 0
  1. const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, AttachmentBuilder } = require('discord.js');
  2. const axios = require('axios');
  3.  
  4. module.exports = {
  5. data: new SlashCommandBuilder()
  6. .setName('verificarpunicao')
  7. .setDescription('Verifica se um jogador foi banido no servidor Mush')
  8. .addStringOption(option =>
  9. option
  10. .setName('nick')
  11. .setDescription('Nome do jogador a ser verificado (ex.: DaysBeforeRodeo)')
  12. .setRequired(true)
  13. ),
  14. async execute(interaction) {
  15. await interaction.deferReply({ withResponse: true });
  16.  
  17. const nick = interaction.options.getString('nick');
  18. let isBanned = false;
  19. let playerData;
  20.  
  21. console.log(`[Requisição 1/1] Obtendo informações para ${nick}...`);
  22. const playerUrl = `https://mush.com.br/api/player/${encodeURIComponent(nick)}`;
  23. console.log(`URL da requisição: ${playerUrl}`);
  24.  
  25. try {
  26. // Usar ZenRows para fazer a requisição
  27. const zenRowsApiKey = '';
  28. const zenRowsUrl = `https://api.zenrows.com/v1/?apikey=${zenRowsApiKey}&url=${encodeURIComponent(playerUrl)}&js_render=true&wait=5000`;
  29. const response = await axios.get(zenRowsUrl, {
  30. timeout: 30000,
  31. headers: {
  32. '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',
  33. },
  34. });
  35.  
  36. // Logar o conteúdo bruto para depuração
  37. console.log(`Conteúdo bruto retornado para ${nick}:`, response.data);
  38.  
  39. // Verificar se a resposta é um JSON válido
  40. if (typeof response.data === 'string' && !response.data.trim().startsWith('{') && !response.data.trim().startsWith('[')) {
  41. throw new Error('A resposta não é um JSON válido. Possível erro da API ou bloqueio do Cloudflare.');
  42. }
  43.  
  44. playerData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  45.  
  46. // Verificar se a API retornou uma mensagem de erro
  47. if (playerData.error || playerData.message) {
  48. throw new Error(playerData.error || playerData.message || 'Erro desconhecido da API.');
  49. }
  50.  
  51. console.log(`Resposta da API para ${nick}:`, JSON.stringify(playerData, null, 2));
  52. } catch (error) {
  53. console.error(`Erro ao consultar a API para ${nick}:`, error.message);
  54. const embed = new EmbedBuilder()
  55. .setTitle('❌ Erro ao Consultar a API')
  56. .setDescription(
  57. error.message.includes('403')
  58. ? `A API retornou erro 403 (Forbidden). Possível bloqueio pelo Cloudflare. Tente usar uma chave de API ou contatar o suporte do MushMC.`
  59. : error.message.includes('not found') || error.message.includes('Player not found')
  60. ? `Jogador \`${nick}\` não encontrado. Verifique o nome e tente novamente.`
  61. : `Erro ao consultar a API: ${error.message}`
  62. )
  63. .setColor('#4B0082')
  64. .setTimestamp();
  65. await interaction.editReply({ embeds: [embed] });
  66. return;
  67. }
  68.  
  69. const flatData = flattenJSON(playerData);
  70. const banKeys = ['banned', 'isBanned', 'banStatus', 'is_banned', 'ban_status'];
  71. for (const key of banKeys) {
  72. const fullKey = Object.keys(flatData).find(k => k.toLowerCase().endsWith(key.toLowerCase()));
  73. if (fullKey && flatData[fullKey] === true) {
  74. isBanned = true;
  75. break;
  76. }
  77. }
  78.  
  79. const embed = new EmbedBuilder()
  80. .setTitle(isBanned ? '⛔ Jogador Banido' : '✅ Jogador Não Banido')
  81. .setDescription(isBanned
  82. ? `O jogador \`${nick}\` está banido!`
  83. : `O jogador \`${nick}\` não foi banido.`)
  84. .setColor('#4B0082')
  85. .setTimestamp();
  86.  
  87. const message = await interaction.editReply({ embeds: [embed], withResponse: true });
  88.  
  89. embed.setDescription(
  90. (isBanned ? `O jogador \`${nick}\` está banido!` : `O jogador \`${nick}\` não foi banido.`) +
  91. '\n\nDeseja ver as estatísticas do jogador?'
  92. );
  93.  
  94. const row = new ActionRowBuilder()
  95. .addComponents(
  96. new ButtonBuilder()
  97. .setCustomId('show_stats_yes')
  98. .setLabel('Sim')
  99. .setStyle(ButtonStyle.Primary),
  100. new ButtonBuilder()
  101. .setCustomId('show_stats_no')
  102. .setLabel('Não')
  103. .setStyle(ButtonStyle.Secondary)
  104. );
  105.  
  106. await message.edit({ embeds: [embed], components: [row] });
  107.  
  108. const collector = message.createMessageComponentCollector({
  109. filter: i => i.user.id === interaction.user.id,
  110. time: 60000,
  111. });
  112.  
  113. collector.on('collect', async i => {
  114. if (i.customId === 'show_stats_yes') {
  115. embed.setTitle('📊 Formato das Estatísticas')
  116. .setDescription('Em qual formato você deseja ver as estatísticas?');
  117.  
  118. const formatRow = new ActionRowBuilder()
  119. .addComponents(
  120. new ButtonBuilder()
  121. .setCustomId('format_text')
  122. .setLabel('Formato de Texto')
  123. .setStyle(ButtonStyle.Primary),
  124. new ButtonBuilder()
  125. .setCustomId('format_json')
  126. .setLabel('Formato JSON')
  127. .setStyle(ButtonStyle.Secondary)
  128. );
  129.  
  130. await i.update({
  131. embeds: [embed],
  132. components: [formatRow]
  133. });
  134.  
  135. const formatCollector = message.createMessageComponentCollector({
  136. filter: f => f.user.id === interaction.user.id,
  137. time: 60000,
  138. });
  139.  
  140. formatCollector.on('collect', async f => {
  141. if (f.customId === 'format_text') {
  142. const statsText = formatStatsAsText(playerData);
  143. embed.setTitle(`📊 Estatísticas de \`${nick}\``);
  144.  
  145. if (statsText.length > 2000) {
  146. const attachment = new AttachmentBuilder(
  147. Buffer.from(statsText, 'utf-8'),
  148. { name: 'estatisticas.txt' }
  149. );
  150. embed.setDescription('As estatísticas são muito longas para exibir aqui. Veja o arquivo abaixo:');
  151. await f.update({
  152. embeds: [embed],
  153. components: [],
  154. files: [attachment]
  155. });
  156. } else {
  157. embed.setDescription(statsText);
  158. await f.update({
  159. embeds: [embed],
  160. components: []
  161. });
  162. }
  163. } else if (f.customId === 'format_json') {
  164. const statsJSON = JSON.stringify(playerData, null, 2);
  165. embed.setTitle(`📊 Estatísticas de \`${nick}\` (JSON)`);
  166.  
  167. if (statsJSON.length > 2000) {
  168. const attachment = new AttachmentBuilder(
  169. Buffer.from(statsJSON, 'utf-8'),
  170. { name: 'estatisticas.json' }
  171. );
  172. embed.setDescription('As estatísticas em JSON são muito longas para exibir aqui. Veja o arquivo abaixo:');
  173. await f.update({
  174. embeds: [embed],
  175. components: [],
  176. files: [attachment]
  177. });
  178. } else {
  179. embed.setDescription(`\`\`\`json\n${statsJSON}\n\`\`\``);
  180. await f.update({
  181. embeds: [embed],
  182. components: []
  183. });
  184. }
  185. }
  186.  
  187. formatCollector.stop();
  188. });
  189.  
  190. formatCollector.on('end', () => {
  191. if (message.components.length > 0) {
  192. message.edit({ components: [] });
  193. }
  194. });
  195. } else if (i.customId === 'show_stats_no') {
  196. embed.setDescription(isBanned
  197. ? `O jogador \`${nick}\` está banido!`
  198. : `O jogador \`${nick}\` não foi banido.`);
  199. await i.update({
  200. embeds: [embed],
  201. components: []
  202. });
  203. }
  204. });
  205.  
  206. collector.on('end', () => {
  207. if (message.components.length > 0) {
  208. message.edit({ components: [] });
  209. }
  210. });
  211. },
  212. };
  213.  
  214. function flattenJSON(obj, parentKey = '', result = {}) {
  215. for (const key in obj) {
  216. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  217. const newKey = parentKey ? `${parentKey}.${key}` : key;
  218. if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
  219. flattenJSON(obj[key], newKey, result);
  220. } else {
  221. result[newKey] = obj[key];
  222. }
  223. }
  224. }
  225. return result;
  226. }
  227.  
  228. function formatStatsAsText(data) {
  229. const flatData = flattenJSON(data);
  230. const lines = [];
  231. for (const key in flatData) {
  232. if (Object.prototype.hasOwnProperty.call(flatData, key)) {
  233. lines.push(`${key}: ${flatData[key]}`);
  234. }
  235. }
  236. return lines.join('\n');
  237. }
Advertisement
Add Comment
Please, Sign In to add comment