owner-subasta-jid.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import fs from 'fs';
  2. import path from 'path';
  3. const auctionFilePath = path.resolve('./src/auctions.json');
  4. // Función para cargar subastas
  5. const loadAuctions = () => {
  6. try {
  7. if (!fs.existsSync(auctionFilePath)) return { auctions: [] };
  8. return JSON.parse(fs.readFileSync(auctionFilePath));
  9. } catch (err) {
  10. console.error("❌ Error al cargar subastas:", err);
  11. return { auctions: [] };
  12. }
  13. };
  14. // Función para guardar subastas
  15. const saveAuctions = (auctionData) => {
  16. try {
  17. fs.writeFileSync(auctionFilePath, JSON.stringify(auctionData, null, 2));
  18. return true;
  19. } catch (err) {
  20. console.error("❌ Error al guardar subastas:", err);
  21. return false;
  22. }
  23. };
  24. // Función para formatear tiempo
  25. const formatTime = (hours) => {
  26. if (hours < 24) return `${Math.floor(hours)} horas y ${Math.floor((hours % 1) * 60)} minutos`;
  27. const days = Math.floor(hours / 24);
  28. const remainingHours = hours % 24;
  29. return `${days} días y ${Math.floor(remainingHours)} horas`;
  30. };
  31. let handler = async (m, { conn, args, usedPrefix, command }) => {
  32. if (args.length < 2) {
  33. return m.reply(`╭━━━[ *PUJAR EN SUBASTA* ]━━━⬣
  34. ┃ ⚠️ Formato:
  35. ┃ ${usedPrefix}${command} <ID> <cantidad>
  36. ┃ 📌 Ejemplo:
  37. ┃ ${usedPrefix}${command} AUC-1A2B3C 6
  38. ┃ 📋 Notas:
  39. ┃ • La puja debe superar la actual
  40. ┃ • Mínimo 1 de la puja actual
  41. ┃ • Cada puja añade 3 horas
  42. ╰━━━━━━━━━━━━━━━⬣`);
  43. }
  44. try {
  45. const auctionId = args[0];
  46. const bidAmount = parseInt(args[1]);
  47. // Validar cantidad
  48. if (isNaN(bidAmount) || bidAmount <= 0) {
  49. return m.reply('⚠️ La cantidad debe ser un número válido');
  50. }
  51. // Cargar subastas
  52. let auctionData = loadAuctions();
  53. let auction = auctionData.auctions.find(a => a.auctionId === auctionId);
  54. if (!auction) {
  55. return m.reply('❌ Subasta no encontrada');
  56. }
  57. // Verificar estado de la subasta
  58. if (auction.status !== 'active') {
  59. return m.reply('❌ Esta subasta ya ha finalizado');
  60. }
  61. // Verificar tiempo
  62. const now = new Date();
  63. const endTime = new Date(auction.endTime);
  64. if (now > endTime) {
  65. auction.status = 'ended';
  66. saveAuctions(auctionData);
  67. return m.reply('❌ Esta subasta ya ha expirado');
  68. }
  69. // Verificar precio mínimo
  70. if (bidAmount <= auction.currentPrice) {
  71. return m.reply(`❌ Tu puja debe ser mayor al precio actual: ${auction.currentPrice}`);
  72. }
  73. if (bidAmount < auction.currentPrice + 1) {
  74. return m.reply(`❌ La puja mínima debe ser ${auction.currentPrice + 1} USD`);
  75. }
  76. // Verificar que no sea el último postor
  77. if (auction.lastBidder === m.sender) {
  78. return m.reply('❌ Ya tienes la puja más alta');
  79. }
  80. // Verificar balance del usuario
  81. const user = global.db.data.users[m.sender];
  82. if (!user || user.money < bidAmount) {
  83. return m.reply('❌ No tienes suficientes coins para esta puja');
  84. }
  85. // Realizar la puja
  86. // Devolver coins al anterior postor si existe
  87. if (auction.lastBidder) {
  88. global.db.data.users[auction.lastBidder].money += auction.currentPrice;
  89. }
  90. // Descontar coins al nuevo postor
  91. user.money -= bidAmount;
  92. // Actualizar subasta
  93. auction.currentPrice = bidAmount;
  94. auction.lastBidder = m.sender;
  95. auction.bids.push({
  96. bidder: m.sender,
  97. amount: bidAmount,
  98. time: new Date().toISOString()
  99. });
  100. // Añadir 3 horas
  101. const newEndTime = new Date(endTime.getTime() + (3 * 60 * 60 * 1000));
  102. auction.endTime = newEndTime.toISOString();
  103. auction.remainingHours = (newEndTime - now) / (1000 * 60 * 60);
  104. // Guardar cambios
  105. if (saveAuctions(auctionData)) {
  106. // Mensaje de puja exitosa
  107. let bidMsg = `╭━━━[ *PUJA REALIZADA* ]━━━⬣
  108. ┃ 🔖 *ID:* ${auctionId}
  109. ┃ 🎁 *Premio:*
  110. ┃ ${auction.item}
  111. ┃ 💰 *Nueva puja:*
  112. ┃ ${bidAmount.toLocaleString()} USD
  113. ┃ 👤 *Postor:*
  114. ┃ @${m.sender.split('@')[0]}
  115. ┃ ⏳ *Tiempo añadido:* +3 horas
  116. ┃ ⌛ *Tiempo restante:*
  117. ┃ ${formatTime(auction.remainingHours)}
  118. ┃ 📊 *Pujas totales:*
  119. ┃ ${auction.bids.length}
  120. ╰━━━━━━━━━━━━━━━⬣`;
  121. await conn.reply(m.chat, bidMsg, m, {
  122. mentions: [m.sender]
  123. });
  124. } else {
  125. throw new Error('Error al actualizar la subasta');
  126. }
  127. } catch (error) {
  128. console.error(error);
  129. return m.reply(`❌ Error al realizar la puja: ${error.message}`);
  130. }
  131. };
  132. handler.help = ['.bid <ID> <cantidad>'];
  133. handler.tags = ['economy'];
  134. handler.command = /^(bid|pujar)$/i;
  135. handler.group = true;
  136. handler.register = true;
  137. export default handler;