| import fs from 'fs'; | |
| import path from 'path'; | |
| import { fileURLToPath, pathToFileURL } from 'url'; | |
| import axios from 'axios'; | |
| import fuzzy from 'fuzzy'; | |
| import { google } from 'googleapis'; | |
| import dotenv from 'dotenv'; | |
| import ytdl from '@distube/ytdl-core'; | |
| dotenv.config(); | |
| const __filename = fileURLToPath(import.meta.url); | |
| const __dirname = path.dirname(__filename); | |
| globalThis.client = globalThis.client || { pendingCommands: new Map(), handleReply: [] }; | |
| const CONFIG = { | |
| cacheDir: path.join(__dirname, 'cache', 'dun'), | |
| contextPath: path.join(__dirname, 'cache', 'dun', 'context.json'), | |
| tempPath: path.join(__dirname, 'cache', 'dun', 'temp'), | |
| mp3Path: path.join(__dirname, 'cache', 'dun', 'mp3'), | |
| imagePath: path.join(__dirname, 'cache', 'dun', 'images'), | |
| commandsDir: path.join(__dirname, '..', '..'), | |
| maxHistory: 50, | |
| cacheDuration: 1800 * 1000, | |
| maxCacheSize: 300, | |
| maxMp3CacheSize: 30, | |
| maxImageSize: 5 * 1024 * 1024, | |
| maxFileSize: 20 * 1024 * 1024, | |
| apiTimeout: 10000, | |
| reactions: ['😎', '🚀', '🎉', '😘', '👋'], | |
| imageChance: 0.2, | |
| fuzzyThreshold: 0.8, | |
| }; | |
| const API_KEYS = process.env.GEMINI_API_KEYS?.split(',') || ['AIzaSyCDzwltmCpZevJv3iKC0nsgQbgX3AhjjKc']; | |
| let currentApiKeyIndex = 0; | |
| class Cache { | |
| constructor() { | |
| this.gemini = new Map(); | |
| this.mp3 = new Map(); | |
| this.commands = new Map([['commands', { commands: [], timestamp: Date.now() }]]); | |
| } | |
| cleanup(maxSize, cache, isMp3 = false) { | |
| const now = Date.now(); | |
| for (const [key, { timestamp, filePath }] of cache) { | |
| if (now - timestamp > CONFIG.cacheDuration) { | |
| FileHandler.cleanupTempFile(filePath); | |
| cache.delete(key); | |
| } | |
| } | |
| while (cache.size > maxSize) { | |
| const oldestKey = cache.keys().next().value; | |
| FileHandler.cleanupTempFile(cache.get(oldestKey).filePath); | |
| cache.delete(oldestKey); | |
| } | |
| } | |
| } | |
| const caches = new Cache(); | |
| class FileHandler { | |
| static ensureDir(dir) { | |
| if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); | |
| } | |
| static loadJSON(file) { | |
| this.ensureDir(path.dirname(file)); | |
| if (!fs.existsSync(file)) return {}; | |
| try { | |
| return JSON.parse(fs.readFileSync(file, 'utf8') || '{}') || {}; | |
| } catch (e) { | |
| console.error(`Error loading JSON ${file}:`, e.stack); | |
| return {}; | |
| } | |
| } | |
| static saveJSON(file, data) { | |
| this.ensureDir(path.dirname(file)); | |
| try { | |
| fs.writeFileSync(file, JSON.stringify(data, null, 2)); | |
| } catch (e) { | |
| console.error(`Error saving JSON ${file}:`, e.stack); | |
| } | |
| } | |
| static async loadCommands() { | |
| this.ensureDir(CONFIG.commandsDir); | |
| const commands = []; | |
| const scanDir = async dir => { | |
| for (const file of fs.readdirSync(dir, { withFileTypes: true })) { | |
| const fullPath = path.join(dir, file.name); | |
| if (file.isDirectory()) await scanDir(fullPath); | |
| else if (file.name.endsWith('.js') && file.name !== 'dun.js') { | |
| try { | |
| const cmd = (await import(pathToFileURL(fullPath).href)).default; | |
| if (cmd?.config?.name && cmd?.onRun) { | |
| commands.push({ ...cmd.config, path: fullPath, module: cmd }); | |
| } | |
| } catch (e) { | |
| console.error(`Error loading command ${fullPath}:`, e.stack); | |
| } | |
| } | |
| } | |
| }; | |
| await scanDir(CONFIG.commandsDir); | |
| caches.commands.set('commands', { commands, timestamp: Date.now() }); | |
| return commands; | |
| } | |
| static cleanupTempFile(filePath) { | |
| try { | |
| if (filePath && fs.existsSync(filePath)) fs.unlinkSync(filePath); | |
| } catch (e) { | |
| console.error(`Error cleaning temp file ${filePath}:`, e.stack); | |
| } | |
| } | |
| } | |
| setInterval(async () => { | |
| try { | |
| caches.cleanup(CONFIG.maxCacheSize, caches.gemini); | |
| caches.cleanup(CONFIG.maxMp3CacheSize, caches.mp3, true); | |
| if ((caches.commands.get('commands')?.timestamp || 0) < Date.now() - 3600 * 1000) { | |
| await FileHandler.loadCommands(); | |
| } | |
| } catch (e) { | |
| console.error('Error in cache cleanup:', e.stack); | |
| } | |
| }, 60 * 60 * 1000); | |
| async function checkAdminPermission(userID, threadID, api, isBot = false) { | |
| try { | |
| const threadInfo = await api.getThreadInfo(threadID).catch(e => { | |
| console.error(`Error fetching thread info ${threadID}:`, e.stack); | |
| return null; | |
| }); | |
| if (!threadInfo?.adminIDs) return false; | |
| const targetID = isBot ? api.getCurrentUserID?.() : userID; | |
| return threadInfo.adminIDs.some(admin => admin.id === targetID); | |
| } catch (e) { | |
| console.error(`Error checking admin permission for ${userID}:`, e.stack); | |
| return false; | |
| } | |
| } | |
| async function executeGroupAction(api, threadID, action, value) { | |
| const actions = { | |
| image: async () => { | |
| const { data } = await axios.get(value, { responseType: 'stream', timeout: CONFIG.apiTimeout }); | |
| await api.setThreadImage(data, threadID); | |
| return 'Ảnh nhóm mới xịn! 🖼️'; | |
| }, | |
| nickname: async () => { | |
| await api.changeNickname(value[1], threadID, value[0]); | |
| return `Đổi thành ${value[1]}! 😎`; | |
| }, | |
| kick: async () => { | |
| await api.removeUserFromGroup(value, threadID); | |
| return 'Đã kick! 👋'; | |
| }, | |
| add: async () => { | |
| await api.addUserToGroup(value, threadID); | |
| return 'Thêm người mới! 🎉'; | |
| }, | |
| name: async () => { | |
| await api.setTitle(value, threadID); | |
| return `Tên nhóm mới là ${value}! 🎉`; | |
| }, | |
| poll: async () => { | |
| await api.createPoll(value.question, value.options, threadID); | |
| return `Bình chọn "${value.question}" đã tạo! 🗳️`; | |
| }, | |
| theme: async () => { | |
| await api.changeThreadTheme(value, threadID); | |
| return `Chủ đề mới ${value}! 🌈`; | |
| }, | |
| emoji: async () => { | |
| await api.changeThreadEmoji(value, threadID); | |
| return `Icon nhóm mới ${value}! 😎`; | |
| }, | |
| }; | |
| try { | |
| if (!(await checkAdminPermission(null, threadID, api, true))) return 'Bot cần quyền admin! 😎'; | |
| return await actions[action]?.() || 'Hành động không hỗ trợ! 😝'; | |
| } catch (e) { | |
| console.error(`Error executing action ${action}:`, e.stack); | |
| return `Lỗi ${action}: ${e.message}! 😭`; | |
| } | |
| } | |
| async function resolveUserID(api, threadID, identifier, event) { | |
| try { | |
| if (!identifier) return event?.messageReply?.senderID || { error: 'Cần tên, @ hoặc UID! 😝' }; | |
| const name = normalizeText(identifier.replace(/^@/, '')).trim(); | |
| const threadInfo = await api.getThreadInfo(threadID).catch(e => { | |
| console.error(`Error fetching thread info ${threadID}:`, e.stack); | |
| return null; | |
| }); | |
| if (!threadInfo?.userInfo) return { error: 'Không lấy được thông tin nhóm! 😕' }; | |
| const matches = threadInfo.userInfo | |
| .map(user => ({ | |
| id: user.id, | |
| name: user.name, | |
| nickname: threadInfo.nicknames?.[user.id], | |
| score: Math.max( | |
| fuzzy.test(name, normalizeText(user.name), { score: CONFIG.fuzzyThreshold }), | |
| threadInfo.nicknames?.[user.id] ? fuzzy.test(name, normalizeText(threadInfo.nicknames[user.id]), { score: CONFIG.fuzzyThreshold }) : 0 | |
| ), | |
| })) | |
| .filter(user => user.score >= CONFIG.fuzzyThreshold) | |
| .sort((a, b) => b.score - a.score); | |
| if (matches.length === 1) return matches[0].id; | |
| if (matches.length > 1) return { error: `Tìm thấy ${matches.length} người: ${matches.map(m => m.name).join(', ')}. Dùng @tag hoặc reply! 😝` }; | |
| if (identifier.match(/^\d+$/)) { | |
| const userInfo = await api.getUserInfo([identifier]).catch(e => { | |
| console.error(`Error fetching user info ${identifier}:`, e.stack); | |
| return {}; | |
| }); | |
| return userInfo[identifier]?.name ? identifier : { error: `Không tìm thấy UID "${identifier}"! 😕` }; | |
| } | |
| return { error: `Không tìm thấy "${identifier}" trong nhóm! 😕` }; | |
| } catch (e) { | |
| console.error(`Error resolving user ID "${identifier}":`, e.stack); | |
| return { error: `Lỗi tìm "${identifier}". Reply tin nhắn của họ! 😕` }; | |
| } | |
| } | |
| async function getRandomImage() { | |
| try { | |
| const images = fs.readdirSync(CONFIG.imagePath).filter(f => /\.(jpg|jpeg|png|gif)$/i.test(f)); | |
| if (images.length) { | |
| const filePath = path.join(CONFIG.imagePath, images[Math.floor(Math.random() * images.length)]); | |
| if (fs.statSync(filePath).size <= CONFIG.maxImageSize) return fs.createReadStream(filePath); | |
| } | |
| return (await axios.get('https://source.unsplash.com/random/200x200', { responseType: 'stream', timeout: 5000 })).data; | |
| } catch (e) { | |
| console.error('Error getting random image:', e.stack); | |
| return null; | |
| } | |
| } | |
| function loadChatHistory(uid) { | |
| const filePath = path.join(CONFIG.cacheDir, 'uids', `${uid}.json`); | |
| FileHandler.ensureDir(path.dirname(filePath)); | |
| if (!fs.existsSync(filePath)) return []; | |
| try { | |
| return JSON.parse(fs.readFileSync(filePath, 'utf8') || '[]') || []; | |
| } catch (e) { | |
| console.error(`Error loading chat history ${uid}:`, e.stack); | |
| return []; | |
| } | |
| } | |
| function appendToChatHistory(uid, chatHistory) { | |
| FileHandler.saveJSON(path.join(CONFIG.cacheDir, 'uids', `${uid}.json`), chatHistory.slice(-CONFIG.maxHistory)); | |
| } | |
| async function updateContext(uid, body, response, intent, lastBotMessage) { | |
| const context = FileHandler.loadJSON(CONFIG.contextPath); | |
| context[uid] = { | |
| intents: (context[uid]?.intents || []).concat({ body, response, intent, timestamp: Date.now() }).slice(-CONFIG.maxHistory), | |
| lastIntent: intent || 'casual', | |
| lastBotMessage: lastBotMessage || response, | |
| }; | |
| FileHandler.saveJSON(CONFIG.contextPath, context); | |
| } | |
| async function searchSong(query) { | |
| try { | |
| const { data } = await axios.get(`https://www.youtube.com/results?search_query=${encodeURIComponent(query + ' song')}`, { timeout: CONFIG.apiTimeout }); | |
| const videoIds = (data.match(/"videoId":"([^"]+)"/g) || []).map(id => id.match(/"videoId":"([^"]+)"/)[1]).slice(0, 3); | |
| const videos = await Promise.all(videoIds.map(id => ytdl.getInfo(`https://www.youtube.com/watch?v=${id}`).then(info => ({ url: info.videoDetails.video_url, title: info.videoDetails.title })).catch(() => null))); | |
| return videos.filter(Boolean).sort((a, b) => fuzzy.test(query, a.title) - fuzzy.test(query, b.title)); | |
| } catch (e) { | |
| console.error(`Error searching song "${query}":`, e.stack); | |
| return []; | |
| } | |
| } | |
| async function downloadYouTubeAudio(url) { | |
| if (!ytdl.validateURL(url)) return { error: 'Link YouTube không hợp lệ! 😕' }; | |
| const videoId = ytdl.getURLVideoID(url); | |
| const cacheKey = `youtube:${videoId}`; | |
| const tempPath = path.join(CONFIG.tempPath, `${videoId}_temp.mp3`); | |
| const filePath = path.join(CONFIG.mp3Path, `${videoId}_${Date.now()}.mp3`); | |
| if (caches.mp3.has(cacheKey) && fs.existsSync(caches.mp3.get(cacheKey).filePath)) { | |
| return { filePath: caches.mp3.get(cacheKey).filePath, fromCache: true }; | |
| } | |
| FileHandler.ensureDir(CONFIG.mp3Path); | |
| try { | |
| await new Promise((resolve, reject) => { | |
| ytdl(url, { filter: 'audioonly', quality: 'lowestaudio' }) | |
| .pipe(fs.createWriteStream(tempPath)) | |
| .on('finish', resolve) | |
| .on('error', reject); | |
| }); | |
| if (fs.statSync(tempPath).size > CONFIG.maxFileSize) throw new Error('File quá 20MB!'); | |
| fs.renameSync(tempPath, filePath); | |
| if (caches.mp3.size >= CONFIG.maxMp3CacheSize) caches.mp3.delete(caches.mp3.keys().next().value); | |
| caches.mp3.set(cacheKey, { filePath, timestamp: Date.now() }); | |
| return { filePath, fromCache: false }; | |
| } catch (e) { | |
| console.error(`Error downloading audio ${url}:`, e.stack); | |
| FileHandler.cleanupTempFile(tempPath); | |
| return { error: `Lỗi tải nhạc: ${e.message}! 😭` }; | |
| } | |
| } | |
| async function suggestThemeOrEmoji(description, type) { | |
| try { | |
| const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` }); | |
| const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]); | |
| const prompt = `Gợi ý một ${type === 'theme' ? 'chủ đề (theme ID hoặc tên màu)' : 'emoji'} phù hợp với "${description}". Trả về chỉ một giá trị.`; | |
| const { data } = await genaiService.models.generateContent({ | |
| model: 'models/gemini-1.5-pro-latest', | |
| requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 50, temperature: 0.7 } }, | |
| auth, | |
| }); | |
| return data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || (type === 'theme' ? 'blue' : '😎'); | |
| } catch (e) { | |
| console.error(`Error suggesting ${type} for "${description}":`, e.stack); | |
| return type === 'theme' ? 'blue' : '😎'; | |
| } | |
| } | |
| async function analyzeIntentWithGemini(body, context, chatHistory, threadInfo = {}) { | |
| try { | |
| const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` }); | |
| const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]); | |
| const memberNames = threadInfo.userInfo?.map(u => ({ id: u.id, name: u.name, nickname: threadInfo.nicknames?.[u.id] })) || []; | |
| const prompt = ` | |
| Phân tích ý định và trích xuất tham số từ câu lệnh sau: "${body}" | |
| Lịch sử trò chuyện: ${chatHistory.slice(-3).map(m => `${m.role}: ${m.content}`).join('\n')} | |
| Ngữ cảnh trước: ${context.lastIntent || 'casual'}, tin nhắn bot trước: ${context.lastBotMessage || 'Chưa có'} | |
| Danh sách thành viên nhóm: ${JSON.stringify(memberNames)} | |
| Các ý định có thể: nickname, groupImage, kick, add, groupName, poll, theme, emoji, action, menu, helpRequest, casual | |
| Trả về JSON với định dạng: | |
| { | |
| "intent": "tên ý định", | |
| "entities": { "tham số": "giá trị" }, | |
| "confidence": 0.0 đến 1.0 | |
| } | |
| Lưu ý: | |
| - Nếu ý định là "nickname", tìm tên người trong danh sách thành viên khớp nhất với entities.user. | |
| - Ví dụ: "!dun đổi biệt danh Gia Khang thành Mèo" → { "intent": "nickname", "entities": { "user": "Gia Khang", "nickname": "Mèo" }, "confidence": 0.95 } | |
| `; | |
| const { data } = await genaiService.models.generateContent({ | |
| model: 'models/gemini-1.5-pro-latest', | |
| requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 200, temperature: 0.5 } }, | |
| auth, | |
| }); | |
| const result = JSON.parse(data?.candidates?.[0]?.content?.parts?.[0]?.text || '{}'); | |
| return result.intent && result.entities ? result : { intent: 'casual', entities: {}, confidence: 0 }; | |
| } catch (e) { | |
| console.error(`Error analyzing intent with Gemini:`, e.stack); | |
| return { intent: 'casual', entities: {}, confidence: 0 }; | |
| } | |
| } | |
| function normalizeText(text) { | |
| return text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim(); | |
| } | |
| function cleanText(text) { | |
| return text | |
| .replace(/[^\p{L}\p{N}\s@:/.-😀-🙏]/gu, '') | |
| .replace(/(?<!\w)[!?.](?!\w)/g, '') | |
| .trim(); | |
| } | |
| async function detectIntent(body, context = {}, chatHistory = [], api, threadID) { | |
| const intents = [ | |
| { name: 'nickname', description: 'Đổi biệt danh thành viên', entities: ['user', 'nickname'], confirm: false, weight: 3 }, | |
| { name: 'groupImage', description: 'Đổi ảnh nhóm', entities: ['url'], confirm: false, weight: 3 }, | |
| { name: 'kick', description: 'Kick thành viên', entities: ['user'], confirm: true, weight: 2 }, | |
| { name: 'add', description: 'Thêm thành viên', entities: ['user'], confirm: false, weight: 2 }, | |
| { name: 'groupName', description: 'Đổi tên nhóm', entities: ['name'], confirm: false, weight: 3 }, | |
| { name: 'poll', description: 'Tạo bình chọn', entities: ['options'], confirm: false, weight: 2 }, | |
| { name: 'theme', description: 'Đổi chủ đề nhóm', entities: ['theme'], confirm: false, weight: 2 }, | |
| { name: 'emoji', description: 'Đổi emoji nhóm', entities: ['emoji'], confirm: false, weight: 2 }, | |
| { name: 'action', description: 'Tìm/phát nhạc', entities: ['query'], confirm: false, weight: 2 }, | |
| { name: 'menu', description: 'Xem danh sách lệnh', entities: [], confirm: false, weight: 1 }, | |
| { name: 'helpRequest', description: 'Yêu cầu trợ giúp', entities: [], confirm: false, weight: 1 }, | |
| { name: 'casual', description: 'Trò chuyện thông thường', entities: [], confirm: false, weight: 0 }, | |
| ]; | |
| try { | |
| const threadInfo = await api.getThreadInfo(threadID).catch(e => { | |
| console.error(`Error fetching thread info ${threadID}:`, e.stack); | |
| return {}; | |
| }); | |
| const geminiResult = await analyzeIntentWithGemini(body, context, chatHistory, threadInfo); | |
| console.log('Gemini intent analysis:', geminiResult); | |
| const intentConfig = intents.find(i => i.name === geminiResult.intent) || intents.find(i => i.name === 'casual'); | |
| const isValid = !intentConfig.entities.length || intentConfig.entities.every(ent => geminiResult.entities[ent]); | |
| if (!isValid) { | |
| console.log('Invalid entities for intent:', geminiResult.intent, geminiResult.entities); | |
| return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false }; | |
| } | |
| return { | |
| name: geminiResult.intent, | |
| matches: geminiResult.entities, | |
| score: geminiResult.confidence * 10, | |
| confidence: geminiResult.confidence, | |
| confirm: intentConfig.confirm || false, | |
| }; | |
| } catch (e) { | |
| console.error('Error detecting intent:', e.stack); | |
| return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false }; | |
| } | |
| } | |
| async function processIntent(uid, body, event, api, intent, context, chatHistory) { | |
| const locks = new Map(); | |
| while (locks.has(uid)) await new Promise(r => setTimeout(r, 10)); | |
| locks.set(uid, true); | |
| try { | |
| globalThis.client.pendingCommands = globalThis.client.pendingCommands || new Map(); | |
| const pending = globalThis.client.pendingCommands.get(uid); | |
| if (pending?.waitingFor === 'confirmKick' && body.toLowerCase() === 'ok') { | |
| globalThis.client.pendingCommands.delete(uid); | |
| const message = await executeGroupAction(api, event.threadID, 'kick', pending.userID); | |
| await updateContext(uid, body, message, 'kick', message); | |
| return { message }; | |
| } | |
| if (pending?.waitingFor === 'singSelect' && body.match(/^[1-3]$/)) { | |
| const choice = parseInt(body) - 1; | |
| const { songs } = pending.data; | |
| globalThis.client.pendingCommands.delete(uid); | |
| if (!songs[choice]) return { message: `Số ${body} không hợp lệ! 😕` }; | |
| const result = await downloadYouTubeAudio(songs[choice].url); | |
| if (result.error) return { message: result.error }; | |
| const message = `Nhạc "${songs[choice].title}" đây! 🎵 ${result.fromCache ? '(cache)' : ''}`; | |
| await updateContext(uid, body, message, 'action', message); | |
| return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) }; | |
| } | |
| if (pending?.waitingFor) { | |
| globalThis.client.pendingCommands.delete(uid); | |
| return { message: 'Hủy lệnh! 😎' }; | |
| } | |
| const groupActions = { | |
| nickname: { | |
| pattern: 'nickname', | |
| value: async () => { | |
| if (!intent.matches?.user || !intent.matches?.nickname) { | |
| return { error: 'Cần tên người và biệt danh mới (VD: đổi biệt danh Gia Khang thành Mèo)! 😝' }; | |
| } | |
| const userID = await resolveUserID(api, event.threadID, intent.matches.user, event); | |
| return userID.error ? userID : [userID, intent.matches.nickname]; | |
| }, | |
| check: v => Array.isArray(v) && v[0] && v[1], | |
| }, | |
| groupImage: { | |
| pattern: 'image', | |
| value: () => intent.matches?.url || { error: 'Cần link ảnh trực tiếp! 😝' }, | |
| }, | |
| kick: { | |
| pattern: 'kick', | |
| value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để kick! 😝' }, | |
| confirm: true, | |
| }, | |
| add: { | |
| pattern: 'add', | |
| value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để thêm! 😝' }, | |
| }, | |
| groupName: { | |
| pattern: 'name', | |
| value: () => intent.matches?.name || { error: 'Cần tên nhóm mới! 😝' }, | |
| }, | |
| poll: { | |
| pattern: 'poll', | |
| value: () => intent.matches?.options?.options?.length >= 2 ? intent.matches.options : { error: 'Cần câu hỏi và ít nhất 2 tùy chọn! 😝' }, | |
| check: v => v?.options?.length >= 2, | |
| }, | |
| theme: { | |
| pattern: 'theme', | |
| value: async () => intent.matches?.theme?.match(/^(blue|red|green|purple|pink)$/i) || await suggestThemeOrEmoji(intent.matches?.theme || 'default', 'theme'), | |
| }, | |
| emoji: { | |
| pattern: 'emoji', | |
| value: async () => intent.matches?.emoji?.match(/[\u{1F600}-\u{1F64F}]/u) || await suggestThemeOrEmoji(intent.matches?.emoji || 'happy', 'emoji'), | |
| }, | |
| }; | |
| if (intent.name in groupActions) { | |
| if (!(await checkAdminPermission(uid, event.threadID, api))) return { message: 'Cần quyền admin! 😎' }; | |
| const { pattern, value, check, confirm } = groupActions[intent.name]; | |
| const val = await value(); | |
| if (val?.error) return { message: val.error }; | |
| if (check && !check(val)) return { message: 'Dữ liệu không hợp lệ! 😝' }; | |
| if (confirm && intent.confirm) { | |
| globalThis.client.pendingCommands.set(uid, { | |
| command: intent.name, | |
| userID: val, | |
| user: intent.matches.user?.replace(/^@/, '') || val, | |
| waitingFor: 'confirmKick', | |
| timestamp: Date.now(), | |
| }); | |
| return { message: `Chắc chắn muốn kick ${intent.matches.user?.replace(/^@/, '') || val}? Reply 'ok'! 😈` }; | |
| } | |
| const message = await executeGroupAction(api, event.threadID, pattern, val); | |
| await updateContext(uid, body, message, intent.name, message); | |
| return { message }; | |
| } | |
| if (intent.name === 'action') { | |
| const query = intent.matches?.query || body.replace(/\b(tìm|phát|mở|tải)\b.*\b(nhạc|bài hát|song)\b/i, '').trim(); | |
| if (query.includes('youtube.com')) { | |
| const result = await downloadYouTubeAudio(query); | |
| if (result.error) return { message: result.error }; | |
| const message = `Nhạc đây! 🎵 ${result.fromCache ? '(cache)' : ''}`; | |
| await updateContext(uid, body, message, 'action', message); | |
| return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) }; | |
| } | |
| const songs = await searchSong(query); | |
| if (!songs.length) return { message: `Không tìm thấy "${query}"! 😕` }; | |
| globalThis.client.pendingCommands.set(uid, { command: 'sing', waitingFor: 'singSelect', data: { songs }, timestamp: Date.now() }); | |
| const message = `Chọn bài:\n${songs.map((s, i) => `${i + 1}. ${s.title}`).join('\n')}\nReply số 1-3!`; | |
| await updateContext(uid, body, message, 'action', message); | |
| return { message }; | |
| } | |
| if (intent.name === 'menu') { | |
| const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands(); | |
| const message = `Danh sách lệnh:\n${commands.map(c => `🔹 ${c.name}: ${c.description}\nCách dùng: ${c.usages || c.name}`).join('\n')}`; | |
| await updateContext(uid, body, message, 'menu', message); | |
| return { message }; | |
| } | |
| if (intent.name === 'helpRequest') { | |
| const message = `Khó xài? Gõ "!dun menu" để xem lệnh! 😎`; | |
| await updateContext(uid, body, message, 'helpRequest', message); | |
| return { message }; | |
| } | |
| if (intent.name === 'casual') { | |
| const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands(); | |
| const args = normalizeText(body).split(/\s+/).filter(Boolean); | |
| const cmdName = args[0].match(/^[!\/\#]?dun$/) && args[1] ? args[1] : ''; | |
| const cmd = commands.find(c => normalizeText(c.name) === cmdName); | |
| if (cmd && await checkAdminPermission(uid, event.threadID, api)) { | |
| await cmd.module.onRun({ api, event, args: args.slice(2) }); | |
| await updateContext(uid, body, 'Thực thi lệnh tùy chỉnh', 'command', 'Đã chạy lệnh!'); | |
| return null; | |
| } | |
| } | |
| return null; | |
| } catch (e) { | |
| console.error(`Error processing intent for ${uid}:`, e.stack); | |
| return { message: `Lỗi xử lý lệnh: ${e.message}! 😭` }; | |
| } finally { | |
| locks.delete(uid); | |
| } | |
| } | |
| async function handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries = 0) { | |
| try { | |
| const intentResult = await processIntent(uid, body, event, api, intent, context, chatHistory); | |
| if (intentResult) return intentResult; | |
| const cacheKey = `${uid}:${body}`; | |
| if (caches.gemini.has(cacheKey) && Date.now() - caches.gemini.get(cacheKey).timestamp < CONFIG.cacheDuration) { | |
| const response = caches.gemini.get(cacheKey).response; | |
| await updateContext(uid, body, response, 'casual', response); | |
| return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] }; | |
| } | |
| const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` }); | |
| const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]); | |
| const prompt = `Bot vui tính, trả lời ngắn gọn, lầy lội kiểu Việt Nam.\nLịch sử:\n${chatHistory.slice(-3).map(m => `${m.role}: ${m.content}`).join('\n')}\nTin trước: ${context[uid]?.lastBotMessage || 'Chưa có'}\nDanh sách lệnh:\n${(await caches.commands.get('commands')?.commands || await FileHandler.loadCommands()).map(c => `${c.name}: ${c.description}`).join('\n')}\nCâu hỏi: "${body}"`; | |
| const { data } = await genaiService.models.generateContent({ | |
| model: 'models/gemini-1.5-pro-latest', | |
| requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 2048, temperature: 0.7 } }, | |
| auth, | |
| }); | |
| const response = data?.candidates?.[0]?.content?.parts?.[0]?.text || 'Lỗi rồi, thử lại! 😅'; | |
| await appendToChatHistory(uid, [...chatHistory, { role: 'user', content: body }, { role: 'assistant', content: response }]); | |
| caches.gemini.set(cacheKey, { response, timestamp: Date.now() }); | |
| await updateContext(uid, body, response, 'casual', response); | |
| return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] }; | |
| } catch (e) { | |
| console.error(`Error in Gemini response for ${uid}:`, e.stack); | |
| if (e.response?.status === 429 && retries < 3 && currentApiKeyIndex < API_KEYS.length - 1) { | |
| currentApiKeyIndex++; | |
| await new Promise(r => setTimeout(r, 1000 * Math.pow(2, retries))); | |
| return handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries + 1); | |
| } | |
| return { message: `Lỗi Gemini: ${e.message}! Thử lại nhé! 😭` }; | |
| } | |
| } | |
| export default { | |
| config: { | |
| name: 'dun', | |
| author: 'Trần Thanh Dương', | |
| version: '1.0.0', | |
| role: 0, | |
| group: 'Tiện ích', | |
| description: '', | |
| usages: '', | |
| usePrefix: true, | |
| delay: 0, | |
| subcommands: { | |
| history: { | |
| role: 0, | |
| delay: 5, | |
| onRun: async ({ api, event, args }) => {} | |
| }, | |
| cache: { | |
| role: 0, | |
| delay: 5, | |
| onRun: async ({ api, event, args }) => {} | |
| } | |
| } | |
| }, | |
| initialize() { | |
| try { | |
| FileHandler.ensureDir(CONFIG.cacheDir); | |
| FileHandler.loadCommands(); | |
| } catch (e) { | |
| console.error('Error initializing bot:', e.stack); | |
| } | |
| }, | |
| async onRun({ api, event }) { | |
| try { | |
| this.initialize(); | |
| const uid = event.senderID; | |
| const body = event.body?.trim(); | |
| if (!body) return api.sendMessage('Nói gì đi, tui chờ! 😝', event.threadID); | |
| const context = FileHandler.loadJSON(CONFIG.contextPath); | |
| const chatHistory = loadChatHistory(uid); | |
| const intent = await detectIntent(body, context[uid], chatHistory, api, event.threadID); | |
| const response = await handleGeminiResponse(uid, body, event, api, intent, chatHistory, context); | |
| if (!response) return; | |
| api.sendMessage({ body: response.message, attachment: response.attachments }, event.threadID, (err, info) => { | |
| if (err) { | |
| console.error(err); | |
| return; | |
| } | |
| globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: uid }); | |
| if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID); | |
| }); | |
| } catch (e) { | |
| console.error(e); | |
| api.sendMessage(`Lỗi bot: ${e.message}! Thử lại nhé! 😭`, event.threadID); | |
| } | |
| }, | |
| async onReply({ api, event }) { | |
| try { | |
| this.initialize(); | |
| const { threadID, messageID, senderID, body } = event; | |
| const context = FileHandler.loadJSON(CONFIG.contextPath); | |
| const chatHistory = loadChatHistory(senderID); | |
| const intent = await detectIntent(body || '', context[senderID], chatHistory, api, threadID); | |
| const response = await handleGeminiResponse(senderID, body?.trim() || '', event, api, intent, chatHistory, context); | |
| if (!response) return; | |
| api.sendMessage({ body: response.message, attachment: response.attachments }, threadID, (err, info) => { | |
| if (err) { | |
| console.error(err); | |
| return; | |
| } | |
| globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: senderID }); | |
| if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID); | |
| }, messageID); | |
| } catch (e) { | |
| console.error(e); | |
| api.sendMessage(`Lỗi xử lý reply: ${e.message}! Thử lại nhé! 😭`, event.threadID); | |
| } | |
| }, | |
| }; | |