Guest User

Código do verificarpunicao

a guest
Apr 28th, 2025
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.90 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. try {
  16. await interaction.deferReply();
  17. } catch (error) {
  18. console.error('Erro ao adiar a resposta:', error.message);
  19. return;
  20. }
  21.  
  22. const nick = interaction.options.getString('nick');
  23. let playerData;
  24. let isBanned = false;
  25.  
  26. try {
  27. const response = await axios.get(`https://mush.com.br/api/player/${encodeURIComponent(nick)}`, {
  28. timeout: 15000,
  29. headers: {
  30. 'User-Agent': 'SuecoTweakerBot/1.0',
  31. },
  32. });
  33.  
  34. // Logar a resposta completa para depuração
  35. console.log(`Resposta da API para ${nick} (status: ${response.status}):`, JSON.stringify(response.data, null, 2));
  36.  
  37. // Verificar se response.data é um objeto válido
  38. if (!response.data || typeof response.data !== 'object') {
  39. const embed = new EmbedBuilder()
  40. .setTitle('❌ Erro ao Consultar a API')
  41. .setDescription(`Os dados retornados para o jogador \`${nick}\` são inválidos.`)
  42. .setColor('#4B0082')
  43. .setTimestamp();
  44.  
  45. await interaction.editReply({ embeds: [embed] });
  46. return;
  47. }
  48.  
  49. playerData = response.data;
  50.  
  51. // Achatar o JSON para facilitar a busca
  52. const flatData = flattenJSON(playerData);
  53.  
  54. // Procurar por chaves relacionadas a banimento
  55. const banKeys = ['banned', 'isBanned', 'banStatus', 'is_banned', 'ban_status'];
  56. for (const key of banKeys) {
  57. const fullKey = Object.keys(flatData).find(k => k.toLowerCase().endsWith(key.toLowerCase()));
  58. if (fullKey && flatData[fullKey] === true) {
  59. isBanned = true;
  60. break;
  61. }
  62. }
  63.  
  64. const embed = new EmbedBuilder()
  65. .setTitle(isBanned ? '⛔ Jogador Banido' : '✅ Jogador Não Banido')
  66. .setDescription(isBanned
  67. ? `O jogador \`${nick}\` está banido!`
  68. : `O jogador \`${nick}\` não foi banido.`)
  69. .setColor('#4B0082')
  70. .setTimestamp();
  71.  
  72. let message;
  73. try {
  74. message = await interaction.editReply({ embeds: [embed], fetchReply: true });
  75. } catch (error) {
  76. console.error('Erro ao enviar a mensagem inicial:', error.message);
  77. return;
  78. }
  79.  
  80. embed.setDescription(
  81. (isBanned ? `O jogador \`${nick}\` está banido!` : `O jogador \`${nick}\` não foi banido.`) +
  82. '\n\nDeseja ver as estatísticas do jogador?'
  83. );
  84.  
  85. const row = new ActionRowBuilder()
  86. .addComponents(
  87. new ButtonBuilder()
  88. .setCustomId('show_stats_yes')
  89. .setLabel('Sim')
  90. .setStyle(ButtonStyle.Primary),
  91. new ButtonBuilder()
  92. .setCustomId('show_stats_no')
  93. .setLabel('Não')
  94. .setStyle(ButtonStyle.Secondary)
  95. );
  96.  
  97. try {
  98. await message.edit({ embeds: [embed], components: [row] });
  99. } catch (error) {
  100. console.error('Erro ao editar a mensagem para perguntar sobre estatísticas:', error.message);
  101. return;
  102. }
  103.  
  104. const collector = message.createMessageComponentCollector({
  105. filter: i => i.user.id === interaction.user.id,
  106. time: 60000,
  107. });
  108.  
  109. collector.on('collect', async i => {
  110. try {
  111. if (i.customId === 'show_stats_yes') {
  112. embed.setTitle('📊 Formato das Estatísticas')
  113. .setDescription('Em qual formato você deseja ver as estatísticas?');
  114.  
  115. const formatRow = new ActionRowBuilder()
  116. .addComponents(
  117. new ButtonBuilder()
  118. .setCustomId('format_text')
  119. .setLabel('Formato de Texto')
  120. .setStyle(ButtonStyle.Primary),
  121. new ButtonBuilder()
  122. .setCustomId('format_json')
  123. .setLabel('Formato JSON')
  124. .setStyle(ButtonStyle.Secondary)
  125. );
  126.  
  127. await i.update({
  128. embeds: [embed],
  129. components: [formatRow]
  130. });
  131.  
  132. const formatCollector = message.createMessageComponentCollector({
  133. filter: f => f.user.id === interaction.user.id,
  134. time: 60000,
  135. });
  136.  
  137. formatCollector.on('collect', async f => {
  138. try {
  139. if (f.customId === 'format_text') {
  140. const statsText = formatStatsAsText(playerData);
  141. embed.setTitle(`📊 Estatísticas de \`${nick}\``);
  142.  
  143. if (statsText.length > 2000) {
  144. const attachment = new AttachmentBuilder(
  145. Buffer.from(statsText, 'utf-8'),
  146. { name: 'estatisticas.txt' }
  147. );
  148. embed.setDescription('As estatísticas são muito longas para exibir aqui. Veja o arquivo abaixo:');
  149. await f.update({
  150. embeds: [embed],
  151. components: [],
  152. files: [attachment]
  153. });
  154. } else {
  155. embed.setDescription(statsText);
  156. await f.update({
  157. embeds: [embed],
  158. components: []
  159. });
  160. }
  161. } else if (f.customId === 'format_json') {
  162. const statsJSON = JSON.stringify(playerData, null, 2);
  163. embed.setTitle(`📊 Estatísticas de \`${nick}\` (JSON)`);
  164.  
  165. if (statsJSON.length > 2000) {
  166. const attachment = new AttachmentBuilder(
  167. Buffer.from(statsJSON, 'utf-8'),
  168. { name: 'estatisticas.json' }
  169. );
  170. embed.setDescription('As estatísticas em JSON são muito longas para exibir aqui. Veja o arquivo abaixo:');
  171. await f.update({
  172. embeds: [embed],
  173. components: [],
  174. files: [attachment]
  175. });
  176. } else {
  177. embed.setDescription(`\`\`\`json\n${statsJSON}\n\`\`\``);
  178. await f.update({
  179. embeds: [embed],
  180. components: []
  181. });
  182. }
  183. }
  184.  
  185. formatCollector.stop();
  186. } catch (error) {
  187. console.error('Erro ao atualizar a mensagem com o formato das estatísticas:', error.message);
  188. await interaction.followUp({
  189. content: 'Ocorreu um erro ao exibir as estatísticas. Por favor, tente novamente mais tarde.',
  190. ephemeral: true
  191. });
  192. }
  193. });
  194.  
  195. formatCollector.on('end', () => {
  196. if (message.components.length > 0) {
  197. message.edit({ components: [] }).catch(err => {
  198. console.error('Erro ao remover botões do formatCollector:', err.message);
  199. });
  200. }
  201. });
  202. } else if (i.customId === 'show_stats_no') {
  203. embed.setDescription(isBanned
  204. ? `O jogador \`${nick}\` está banido!`
  205. : `O jogador \`${nick}\` não foi banido.`);
  206. await i.update({
  207. embeds: [embed],
  208. components: []
  209. });
  210. }
  211. } catch (error) {
  212. console.error('Erro ao processar a interação do botão:', error.message);
  213. await interaction.followUp({
  214. content: 'Ocorreu um erro ao processar sua escolha. Por favor, tente novamente.',
  215. ephemeral: true
  216. });
  217. }
  218. });
  219.  
  220. collector.on('end', () => {
  221. if (message.components.length > 0) {
  222. message.edit({ components: [] }).catch(err => {
  223. console.error('Erro ao remover botões do collector:', err.message);
  224. });
  225. }
  226. });
  227.  
  228. } catch (error) {
  229. console.error(`Erro ao verificar punição para ${nick}:`, error.message);
  230.  
  231. const embed = new EmbedBuilder()
  232. .setTitle('❌ Erro ao Consultar a API')
  233. .setColor('#4B0082')
  234. .setTimestamp();
  235.  
  236. if (error.response?.status === 404) {
  237. embed.setDescription(`O jogador \`${nick}\` nunca se registrou no MushMC.`);
  238. } else if (error.response?.status === 403) {
  239. embed.setDescription(
  240. `Não foi possível consultar o jogador \`${nick}\`.\n` +
  241. 'A API do MushMC retornou um erro 403 (Forbidden), indicando que o acesso foi negado.\n' +
  242. 'Possíveis causas:\n' +
  243. '- O bot não tem permissão para acessar a API (pode ser necessário uma chave de API).\n' +
  244. '- O IP do bot foi bloqueado pela API.\n' +
  245. 'Por favor, verifique as configurações da API ou contate o suporte do MushMC.'
  246. );
  247. } else {
  248. embed.setDescription(`Ocorreu um erro ao consultar a API para o jogador \`${nick}\`: ${error.message}`);
  249. }
  250.  
  251. await interaction.editReply({ embeds: [embed] }).catch(err => {
  252. console.error('Erro ao enviar mensagem de erro:', err.message);
  253. });
  254. }
  255. },
  256. };
  257.  
  258. function flattenJSON(obj, parentKey = '', result = {}) {
  259. for (const key in obj) {
  260. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  261. const newKey = parentKey ? `${parentKey}.${key}` : key;
  262. if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
  263. flattenJSON(obj[key], newKey, result);
  264. } else {
  265. result[newKey] = obj[key];
  266. }
  267. }
  268. }
  269. return result;
  270. }
  271.  
  272. function formatStatsAsText(data) {
  273. const flatData = flattenJSON(data);
  274. const lines = [];
  275. for (const key in flatData) {
  276. if (Object.prototype.hasOwnProperty.call(flatData, key)) {
  277. lines.push(`${key}: ${flatData[key]}`);
  278. }
  279. }
  280. return lines.join('\n');
  281. }
Advertisement
Add Comment
Please, Sign In to add comment