owner-subasta.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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)) {
  8. fs.writeFileSync(auctionFilePath, JSON.stringify({auctions: []}, null, 2));
  9. return {auctions: []};
  10. }
  11. const data = fs.readFileSync(auctionFilePath, "utf8");
  12. return JSON.parse(data);
  13. } catch (err) {
  14. console.error("❌ Error al cargar las subastas:", err.message);
  15. return {auctions: []};
  16. }
  17. };
  18. // Función para guardar subastas
  19. const saveAuctions = (auctionData) => {
  20. try {
  21. fs.writeFileSync(auctionFilePath, JSON.stringify(auctionData, null, 2));
  22. return true;
  23. } catch (err) {
  24. console.error("❌ Error al guardar las subastas:", err.message);
  25. return false;
  26. }
  27. };
  28. // Función para generar ID único
  29. const generateAuctionId = () => {
  30. return 'AUC-' + Math.random().toString(36).substring(2, 8).toUpperCase();
  31. };
  32. // Función para formatear tiempo
  33. const formatTime = (hours) => {
  34. if (hours < 24) return `${hours} horas`;
  35. const days = Math.floor(hours / 24);
  36. const remainingHours = hours % 24;
  37. return `${days} días y ${remainingHours} horas`;
  38. };
  39. let handler = async (m, { conn, text, args, usedPrefix, command }) => {
  40. if (!text) {
  41. return m.reply(`╭━━━[ *CREAR SUBASTA* ]━━━⬣
  42. ┃ ⚠️ Formato:
  43. ┃ ${usedPrefix}${command} premio|precio inicial|precio directo
  44. ┃ 📌 Ejemplo:
  45. ┃ ${usedPrefix}${command} Diamantes x1000|5000|15000
  46. ┃ 📋 Notas:
  47. ┃ • Premio: Lo que se subasta
  48. ┃ • Precio Inicial: Precio base
  49. ┃ • Precio Directo: Compra inmediata
  50. ┃ • Tiempo inicial: 24 horas
  51. ┃ • +3 horas por cada puja
  52. ╰━━━━━━━━━━━━━━━⬣`);
  53. }
  54. try {
  55. const [prize, startingBid, buyNow] = text.split('|');
  56. if (!prize || !startingBid || !buyNow) {
  57. return m.reply('⚠️ Debes proporcionar todos los datos');
  58. }
  59. // Validar precios
  60. const initialPrice = parseInt(startingBid);
  61. const directPrice = parseInt(buyNow);
  62. if (isNaN(initialPrice) || isNaN(directPrice)) {
  63. return m.reply('⚠️ Los precios deben ser números válidos');
  64. }
  65. if (initialPrice <= 0 || directPrice <= 0) {
  66. return m.reply('⚠️ Los precios deben ser mayores a 0');
  67. }
  68. if (initialPrice >= directPrice) {
  69. return m.reply('⚠️ El precio inicial debe ser menor al precio directo');
  70. }
  71. // Generar ID único
  72. const auctionId = generateAuctionId();
  73. // Tiempo inicial en horas
  74. const initialHours = 24;
  75. // Crear nueva subasta
  76. const newAuction = {
  77. auctionId: auctionId,
  78. item: prize.trim(),
  79. startingPrice: initialPrice,
  80. buyNowPrice: directPrice,
  81. currentPrice: initialPrice,
  82. createdBy: m.sender,
  83. createdAt: new Date().toISOString(),
  84. endTime: new Date(Date.now() + initialHours * 60 * 60 * 1000).toISOString(),
  85. remainingHours: initialHours,
  86. status: 'active',
  87. participants: [],
  88. lastBidder: null,
  89. bids: []
  90. };
  91. // Cargar y guardar subasta
  92. let auctionData = loadAuctions();
  93. auctionData.auctions.push(newAuction);
  94. if (saveAuctions(auctionData)) {
  95. // Mensaje de confirmación
  96. let auctionMsg = `╭━━━[ *NUEVA SUBASTA* ]━━━⬣
  97. ┃ 🔖 *ID:* ${auctionId}
  98. ┃ 🎁 *Premio:*
  99. ┃ ${prize.trim()}
  100. ┃ 💰 *Precio Inicial:*
  101. ┃ ${initialPrice.toLocaleString()} USD
  102. ┃ 💎 *Precio Directo:*
  103. ┃ ${directPrice.toLocaleString()} USD
  104. ┃ ⏳ *Duración Inicial:*
  105. ┃ ${formatTime(initialHours)}
  106. ┃ 📌 *Información:*
  107. ┃ • Cada puja añade 3 horas
  108. ┃ • Precio mínimo de puja:
  109. ┃ 1 USD
  110. ┃ 📍 *Comandos:*
  111. ┃ • Para pujar:
  112. ┃ .bid ${auctionId} <cantidad>
  113. ┃ • Compra directa:
  114. ┃ .buynow ${auctionId}
  115. ┃ • Ver info:
  116. ┃ .auctioninfo ${auctionId}
  117. ╰━━━━━━━━━━━━━━━⬣`;
  118. // Mensaje inicial
  119. await conn.reply(m.chat, auctionMsg, m);
  120. // Mensaje separado con ID
  121. await conn.reply(m.chat, `🔖 *ID DE SUBASTA:* ${auctionId}`, m);
  122. } else {
  123. throw new Error('Error al crear la subasta');
  124. }
  125. } catch (error) {
  126. console.error(error);
  127. return m.reply(`❌ Error al crear la subasta: ${error.message}`);
  128. }
  129. };
  130. handler.help = ['.auction <premio|precio inicial|precio directo>'];
  131. handler.tags = ['economy'];
  132. handler.command = /^(auction|subasta|createauction)$/i;
  133. handler.group = false;
  134. handler.rowner = true;
  135. export default handler;