UNPKG

lunahub

Version:

🌙 LunaHUB - Ultimate All-in-One JavaScript Library

293 lines (255 loc) 9.52 kB
const axios = require('axios'); /** * 🌙 LunaHUB - Ultimate All-in-One JavaScript Library * HTTP Client + Discord Webhooks + Utilities + More! */ class LunaHUB { constructor(options = {}) { this.timeout = options.timeout || 30000; this.maxRetries = options.maxRetries || 3; this.debug = options.debug || false; } // ======================================== // 📡 HTTP CLIENT MODULE // ======================================== /** * Make HTTP request with auto-retry */ async request(config) { const mergedConfig = { timeout: this.timeout, ...config }; let lastError; for (let attempt = 1; attempt <= this.maxRetries; attempt++) { try { if (this.debug) console.log(`🌙 [${attempt}/${this.maxRetries}] ${config.method} ${config.url}`); const response = await axios(mergedConfig); if (this.debug) console.log(`✅ Success (${response.status})`); return response; } catch (error) { lastError = error; if (error.response?.status >= 400 && error.response?.status < 500) break; if (attempt < this.maxRetries) { const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000); await new Promise(resolve => setTimeout(resolve, delay)); } } } throw lastError; } async get(url, config = {}) { return this.request({ ...config, method: 'GET', url }); } async post(url, data, config = {}) { return this.request({ ...config, method: 'POST', url, data }); } async put(url, data, config = {}) { return this.request({ ...config, method: 'PUT', url, data }); } async delete(url, config = {}) { return this.request({ ...config, method: 'DELETE', url }); } // ======================================== // 🤖 DISCORD MODULE // ======================================== /** * Discord Webhook Manager */ discord = { /** * Send message to Discord webhook */ sendWebhook: async (webhookUrl, options) => { const payload = { content: options.content || null, username: options.username || 'LunaHUB Bot', avatar_url: options.avatarUrl || null, embeds: options.embeds || [], tts: options.tts || false }; try { const response = await this.post(webhookUrl, payload); return { success: true, data: response.data }; } catch (error) { return { success: false, error: error.message }; } }, /** * Create embed object */ createEmbed: (options) => { return { title: options.title || null, description: options.description || null, color: options.color || 0x5865F2, fields: options.fields || [], thumbnail: options.thumbnail ? { url: options.thumbnail } : null, image: options.image ? { url: options.image } : null, footer: options.footer ? { text: options.footer } : null, timestamp: options.timestamp ? new Date().toISOString() : null, url: options.url || null }; }, /** * Send embed to webhook */ sendEmbed: async (webhookUrl, embed, options = {}) => { return await this.discord.sendWebhook(webhookUrl, { embeds: [embed], username: options.username, avatarUrl: options.avatarUrl }); }, /** * Color presets */ colors: { RED: 0xFF0000, GREEN: 0x00FF00, BLUE: 0x0000FF, YELLOW: 0xFFFF00, PURPLE: 0x800080, ORANGE: 0xFFA500, DISCORD: 0x5865F2, SUCCESS: 0x00FF00, ERROR: 0xFF0000, WARNING: 0xFFFF00, INFO: 0x0099FF } }; // ======================================== // 💰 TRUEWALLET MODULE // ======================================== truewallet = { /** * Redeem TrueWallet voucher */ redeemVoucher: async (voucherLink, phoneNumber) => { const voucherCode = voucherLink.replace("https://gift.truemoney.com/campaign/?v=", ""); try { const response = await this.post( `https://gift.truemoney.com/campaign/vouchers/${voucherCode}/redeem`, { mobile: phoneNumber }, { headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36", "Content-Type": "application/json" }, httpsAgent: new require("https").Agent({ maxVersion: 'TLSv1.3', minVersion: 'TLSv1.3' }) } ); return response.data; } catch (error) { return error.response?.data || { error: error.message }; } } }; // ======================================== // 🛠️ UTILITIES MODULE // ======================================== utils = { /** * Delay execution */ sleep: (ms) => new Promise(resolve => setTimeout(resolve, ms)), /** * Random number between min and max */ random: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min, /** * Generate random string */ randomString: (length = 10) => { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join(''); }, /** * Format number with commas */ formatNumber: (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), /** * Chunk array into smaller arrays */ chunk: (array, size) => { const chunks = []; for (let i = 0; i < array.length; i += size) { chunks.push(array.slice(i, i + size)); } return chunks; }, /** * Parse JSON safely */ parseJSON: (str, fallback = null) => { try { return JSON.parse(str); } catch { return fallback; } }, /** * Get timestamp */ timestamp: () => Math.floor(Date.now() / 1000), /** * Format date */ formatDate: (date = new Date(), format = 'YYYY-MM-DD HH:mm:ss') => { const d = new Date(date); const pad = (n) => n.toString().padStart(2, '0'); return format .replace('YYYY', d.getFullYear()) .replace('MM', pad(d.getMonth() + 1)) .replace('DD', pad(d.getDate())) .replace('HH', pad(d.getHours())) .replace('mm', pad(d.getMinutes())) .replace('ss', pad(d.getSeconds())); } }; // ======================================== // 🔐 CRYPTO MODULE (Basic) // ======================================== crypto = { /** * Base64 encode */ base64Encode: (str) => Buffer.from(str).toString('base64'), /** * Base64 decode */ base64Decode: (str) => Buffer.from(str, 'base64').toString('utf-8'), /** * Generate random token */ generateToken: (length = 32) => { const crypto = require('crypto'); return crypto.randomBytes(length).toString('hex'); } }; // ======================================== // 📊 API WRAPPERS // ======================================== api = { /** * JSONPlaceholder - Fake REST API for testing */ jsonPlaceholder: { getPosts: async () => (await this.get('https://jsonplaceholder.typicode.com/posts')).data, getPost: async (id) => (await this.get(`https://jsonplaceholder.typicode.com/posts/${id}`)).data, createPost: async (data) => (await this.post('https://jsonplaceholder.typicode.com/posts', data)).data }, /** * Random User API */ randomUser: async () => (await this.get('https://randomuser.me/api/')).data.results[0], /** * Cat Facts API */ catFact: async () => (await this.get('https://catfact.ninja/fact')).data.fact, /** * Dog API - Random dog image */ randomDog: async () => (await this.get('https://dog.ceo/api/breeds/image/random')).data.message }; } // Export default instance and class const luna = new LunaHUB(); // Make it usable as both function and object const LunaExport = (config) => luna.request(config); Object.assign(LunaExport, luna); LunaExport.create = (options) => new LunaHUB(options); LunaExport.LunaHUB = LunaHUB; module.exports = LunaExport;