Upload OMCfnbFqnr.js with huggingface_hub
Browse files- OMCfnbFqnr.js +687 -0
OMCfnbFqnr.js
ADDED
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import fs from 'fs';
|
2 |
+
import path from 'path';
|
3 |
+
import { fileURLToPath, pathToFileURL } from 'url';
|
4 |
+
import axios from 'axios';
|
5 |
+
import fuzzy from 'fuzzy';
|
6 |
+
import { google } from 'googleapis';
|
7 |
+
import dotenv from 'dotenv';
|
8 |
+
import ytdl from '@distube/ytdl-core';
|
9 |
+
|
10 |
+
dotenv.config();
|
11 |
+
|
12 |
+
const __filename = fileURLToPath(import.meta.url);
|
13 |
+
const __dirname = path.dirname(__filename);
|
14 |
+
globalThis.client = globalThis.client || { pendingCommands: new Map(), handleReply: [] };
|
15 |
+
|
16 |
+
const CONFIG = {
|
17 |
+
cacheDir: path.join(__dirname, 'cache', 'dun'),
|
18 |
+
contextPath: path.join(__dirname, 'cache', 'dun', 'context.json'),
|
19 |
+
tempPath: path.join(__dirname, 'cache', 'dun', 'temp'),
|
20 |
+
mp3Path: path.join(__dirname, 'cache', 'dun', 'mp3'),
|
21 |
+
imagePath: path.join(__dirname, 'cache', 'dun', 'images'),
|
22 |
+
commandsDir: path.join(__dirname, '..', '..'),
|
23 |
+
maxHistory: 50,
|
24 |
+
cacheDuration: 1800 * 1000,
|
25 |
+
maxCacheSize: 300,
|
26 |
+
maxMp3CacheSize: 30,
|
27 |
+
maxImageSize: 5 * 1024 * 1024,
|
28 |
+
maxFileSize: 20 * 1024 * 1024,
|
29 |
+
apiTimeout: 10000,
|
30 |
+
reactions: ['😎', '🚀', '🎉', '😘', '👋'],
|
31 |
+
imageChance: 0.2,
|
32 |
+
fuzzyThreshold: 0.8,
|
33 |
+
};
|
34 |
+
|
35 |
+
const API_KEYS = process.env.GEMINI_API_KEYS?.split(',') || ['AIzaSyCDzwltmCpZevJv3iKC0nsgQbgX3AhjjKc'];
|
36 |
+
let currentApiKeyIndex = 0;
|
37 |
+
|
38 |
+
class Cache {
|
39 |
+
constructor() {
|
40 |
+
this.gemini = new Map();
|
41 |
+
this.mp3 = new Map();
|
42 |
+
this.commands = new Map([['commands', { commands: [], timestamp: Date.now() }]]);
|
43 |
+
}
|
44 |
+
|
45 |
+
cleanup(maxSize, cache, isMp3 = false) {
|
46 |
+
const now = Date.now();
|
47 |
+
for (const [key, { timestamp, filePath }] of cache) {
|
48 |
+
if (now - timestamp > CONFIG.cacheDuration) {
|
49 |
+
FileHandler.cleanupTempFile(filePath);
|
50 |
+
cache.delete(key);
|
51 |
+
}
|
52 |
+
}
|
53 |
+
while (cache.size > maxSize) {
|
54 |
+
const oldestKey = cache.keys().next().value;
|
55 |
+
FileHandler.cleanupTempFile(cache.get(oldestKey).filePath);
|
56 |
+
cache.delete(oldestKey);
|
57 |
+
}
|
58 |
+
}
|
59 |
+
}
|
60 |
+
|
61 |
+
const caches = new Cache();
|
62 |
+
|
63 |
+
class FileHandler {
|
64 |
+
static ensureDir(dir) {
|
65 |
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
66 |
+
}
|
67 |
+
|
68 |
+
static loadJSON(file) {
|
69 |
+
this.ensureDir(path.dirname(file));
|
70 |
+
if (!fs.existsSync(file)) return {};
|
71 |
+
try {
|
72 |
+
return JSON.parse(fs.readFileSync(file, 'utf8') || '{}') || {};
|
73 |
+
} catch (e) {
|
74 |
+
console.error(`Error loading JSON ${file}:`, e.stack);
|
75 |
+
return {};
|
76 |
+
}
|
77 |
+
}
|
78 |
+
|
79 |
+
static saveJSON(file, data) {
|
80 |
+
this.ensureDir(path.dirname(file));
|
81 |
+
try {
|
82 |
+
fs.writeFileSync(file, JSON.stringify(data, null, 2));
|
83 |
+
} catch (e) {
|
84 |
+
console.error(`Error saving JSON ${file}:`, e.stack);
|
85 |
+
}
|
86 |
+
}
|
87 |
+
|
88 |
+
static async loadCommands() {
|
89 |
+
this.ensureDir(CONFIG.commandsDir);
|
90 |
+
const commands = [];
|
91 |
+
const scanDir = async dir => {
|
92 |
+
for (const file of fs.readdirSync(dir, { withFileTypes: true })) {
|
93 |
+
const fullPath = path.join(dir, file.name);
|
94 |
+
if (file.isDirectory()) await scanDir(fullPath);
|
95 |
+
else if (file.name.endsWith('.js') && file.name !== 'dun.js') {
|
96 |
+
try {
|
97 |
+
const cmd = (await import(pathToFileURL(fullPath).href)).default;
|
98 |
+
if (cmd?.config?.name && cmd?.onRun) {
|
99 |
+
commands.push({ ...cmd.config, path: fullPath, module: cmd });
|
100 |
+
}
|
101 |
+
} catch (e) {
|
102 |
+
console.error(`Error loading command ${fullPath}:`, e.stack);
|
103 |
+
}
|
104 |
+
}
|
105 |
+
}
|
106 |
+
};
|
107 |
+
await scanDir(CONFIG.commandsDir);
|
108 |
+
caches.commands.set('commands', { commands, timestamp: Date.now() });
|
109 |
+
return commands;
|
110 |
+
}
|
111 |
+
|
112 |
+
static cleanupTempFile(filePath) {
|
113 |
+
try {
|
114 |
+
if (filePath && fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
115 |
+
} catch (e) {
|
116 |
+
console.error(`Error cleaning temp file ${filePath}:`, e.stack);
|
117 |
+
}
|
118 |
+
}
|
119 |
+
}
|
120 |
+
|
121 |
+
setInterval(async () => {
|
122 |
+
try {
|
123 |
+
caches.cleanup(CONFIG.maxCacheSize, caches.gemini);
|
124 |
+
caches.cleanup(CONFIG.maxMp3CacheSize, caches.mp3, true);
|
125 |
+
if ((caches.commands.get('commands')?.timestamp || 0) < Date.now() - 3600 * 1000) {
|
126 |
+
await FileHandler.loadCommands();
|
127 |
+
}
|
128 |
+
} catch (e) {
|
129 |
+
console.error('Error in cache cleanup:', e.stack);
|
130 |
+
}
|
131 |
+
}, 60 * 60 * 1000);
|
132 |
+
|
133 |
+
async function checkAdminPermission(userID, threadID, api, isBot = false) {
|
134 |
+
try {
|
135 |
+
const threadInfo = await api.getThreadInfo(threadID).catch(e => {
|
136 |
+
console.error(`Error fetching thread info ${threadID}:`, e.stack);
|
137 |
+
return null;
|
138 |
+
});
|
139 |
+
if (!threadInfo?.adminIDs) return false;
|
140 |
+
const targetID = isBot ? api.getCurrentUserID?.() : userID;
|
141 |
+
return threadInfo.adminIDs.some(admin => admin.id === targetID);
|
142 |
+
} catch (e) {
|
143 |
+
console.error(`Error checking admin permission for ${userID}:`, e.stack);
|
144 |
+
return false;
|
145 |
+
}
|
146 |
+
}
|
147 |
+
|
148 |
+
async function executeGroupAction(api, threadID, action, value) {
|
149 |
+
const actions = {
|
150 |
+
image: async () => {
|
151 |
+
const { data } = await axios.get(value, { responseType: 'stream', timeout: CONFIG.apiTimeout });
|
152 |
+
await api.setThreadImage(data, threadID);
|
153 |
+
return 'Ảnh nhóm mới xịn! 🖼️';
|
154 |
+
},
|
155 |
+
nickname: async () => {
|
156 |
+
await api.changeNickname(value[1], threadID, value[0]);
|
157 |
+
return `Đổi thành ${value[1]}! 😎`;
|
158 |
+
},
|
159 |
+
kick: async () => {
|
160 |
+
await api.removeUserFromGroup(value, threadID);
|
161 |
+
return 'Đã kick! 👋';
|
162 |
+
},
|
163 |
+
add: async () => {
|
164 |
+
await api.addUserToGroup(value, threadID);
|
165 |
+
return 'Thêm người mới! 🎉';
|
166 |
+
},
|
167 |
+
name: async () => {
|
168 |
+
await api.setTitle(value, threadID);
|
169 |
+
return `Tên nhóm mới là ${value}! 🎉`;
|
170 |
+
},
|
171 |
+
poll: async () => {
|
172 |
+
await api.createPoll(value.question, value.options, threadID);
|
173 |
+
return `Bình chọn "${value.question}" đã tạo! 🗳️`;
|
174 |
+
},
|
175 |
+
theme: async () => {
|
176 |
+
await api.changeThreadTheme(value, threadID);
|
177 |
+
return `Chủ đề mới ${value}! 🌈`;
|
178 |
+
},
|
179 |
+
emoji: async () => {
|
180 |
+
await api.changeThreadEmoji(value, threadID);
|
181 |
+
return `Icon nhóm mới ${value}! 😎`;
|
182 |
+
},
|
183 |
+
};
|
184 |
+
|
185 |
+
try {
|
186 |
+
if (!(await checkAdminPermission(null, threadID, api, true))) return 'Bot cần quyền admin! 😎';
|
187 |
+
return await actions[action]?.() || 'Hành động không hỗ trợ! 😝';
|
188 |
+
} catch (e) {
|
189 |
+
console.error(`Error executing action ${action}:`, e.stack);
|
190 |
+
return `Lỗi ${action}: ${e.message}! 😭`;
|
191 |
+
}
|
192 |
+
}
|
193 |
+
|
194 |
+
async function resolveUserID(api, threadID, identifier, event) {
|
195 |
+
try {
|
196 |
+
if (!identifier) return event?.messageReply?.senderID || { error: 'Cần tên, @ hoặc UID! 😝' };
|
197 |
+
const name = normalizeText(identifier.replace(/^@/, '')).trim();
|
198 |
+
const threadInfo = await api.getThreadInfo(threadID).catch(e => {
|
199 |
+
console.error(`Error fetching thread info ${threadID}:`, e.stack);
|
200 |
+
return null;
|
201 |
+
});
|
202 |
+
if (!threadInfo?.userInfo) return { error: 'Không lấy được thông tin nhóm! 😕' };
|
203 |
+
|
204 |
+
const matches = threadInfo.userInfo
|
205 |
+
.map(user => ({
|
206 |
+
id: user.id,
|
207 |
+
name: user.name,
|
208 |
+
nickname: threadInfo.nicknames?.[user.id],
|
209 |
+
score: Math.max(
|
210 |
+
fuzzy.test(name, normalizeText(user.name), { score: CONFIG.fuzzyThreshold }),
|
211 |
+
threadInfo.nicknames?.[user.id] ? fuzzy.test(name, normalizeText(threadInfo.nicknames[user.id]), { score: CONFIG.fuzzyThreshold }) : 0
|
212 |
+
),
|
213 |
+
}))
|
214 |
+
.filter(user => user.score >= CONFIG.fuzzyThreshold)
|
215 |
+
.sort((a, b) => b.score - a.score);
|
216 |
+
|
217 |
+
if (matches.length === 1) return matches[0].id;
|
218 |
+
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! 😝` };
|
219 |
+
if (identifier.match(/^\d+$/)) {
|
220 |
+
const userInfo = await api.getUserInfo([identifier]).catch(e => {
|
221 |
+
console.error(`Error fetching user info ${identifier}:`, e.stack);
|
222 |
+
return {};
|
223 |
+
});
|
224 |
+
return userInfo[identifier]?.name ? identifier : { error: `Không tìm thấy UID "${identifier}"! 😕` };
|
225 |
+
}
|
226 |
+
return { error: `Không tìm thấy "${identifier}" trong nhóm! 😕` };
|
227 |
+
} catch (e) {
|
228 |
+
console.error(`Error resolving user ID "${identifier}":`, e.stack);
|
229 |
+
return { error: `Lỗi tìm "${identifier}". Reply tin nhắn của họ! 😕` };
|
230 |
+
}
|
231 |
+
}
|
232 |
+
|
233 |
+
async function getRandomImage() {
|
234 |
+
try {
|
235 |
+
const images = fs.readdirSync(CONFIG.imagePath).filter(f => /\.(jpg|jpeg|png|gif)$/i.test(f));
|
236 |
+
if (images.length) {
|
237 |
+
const filePath = path.join(CONFIG.imagePath, images[Math.floor(Math.random() * images.length)]);
|
238 |
+
if (fs.statSync(filePath).size <= CONFIG.maxImageSize) return fs.createReadStream(filePath);
|
239 |
+
}
|
240 |
+
return (await axios.get('https://source.unsplash.com/random/200x200', { responseType: 'stream', timeout: 5000 })).data;
|
241 |
+
} catch (e) {
|
242 |
+
console.error('Error getting random image:', e.stack);
|
243 |
+
return null;
|
244 |
+
}
|
245 |
+
}
|
246 |
+
|
247 |
+
function loadChatHistory(uid) {
|
248 |
+
const filePath = path.join(CONFIG.cacheDir, 'uids', `${uid}.json`);
|
249 |
+
FileHandler.ensureDir(path.dirname(filePath));
|
250 |
+
if (!fs.existsSync(filePath)) return [];
|
251 |
+
try {
|
252 |
+
return JSON.parse(fs.readFileSync(filePath, 'utf8') || '[]') || [];
|
253 |
+
} catch (e) {
|
254 |
+
console.error(`Error loading chat history ${uid}:`, e.stack);
|
255 |
+
return [];
|
256 |
+
}
|
257 |
+
}
|
258 |
+
|
259 |
+
function appendToChatHistory(uid, chatHistory) {
|
260 |
+
FileHandler.saveJSON(path.join(CONFIG.cacheDir, 'uids', `${uid}.json`), chatHistory.slice(-CONFIG.maxHistory));
|
261 |
+
}
|
262 |
+
|
263 |
+
async function updateContext(uid, body, response, intent, lastBotMessage) {
|
264 |
+
const context = FileHandler.loadJSON(CONFIG.contextPath);
|
265 |
+
context[uid] = {
|
266 |
+
intents: (context[uid]?.intents || []).concat({ body, response, intent, timestamp: Date.now() }).slice(-CONFIG.maxHistory),
|
267 |
+
lastIntent: intent || 'casual',
|
268 |
+
lastBotMessage: lastBotMessage || response,
|
269 |
+
};
|
270 |
+
FileHandler.saveJSON(CONFIG.contextPath, context);
|
271 |
+
}
|
272 |
+
|
273 |
+
async function searchSong(query) {
|
274 |
+
try {
|
275 |
+
const { data } = await axios.get(`https://www.youtube.com/results?search_query=${encodeURIComponent(query + ' song')}`, { timeout: CONFIG.apiTimeout });
|
276 |
+
const videoIds = (data.match(/"videoId":"([^"]+)"/g) || []).map(id => id.match(/"videoId":"([^"]+)"/)[1]).slice(0, 3);
|
277 |
+
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)));
|
278 |
+
return videos.filter(Boolean).sort((a, b) => fuzzy.test(query, a.title) - fuzzy.test(query, b.title));
|
279 |
+
} catch (e) {
|
280 |
+
console.error(`Error searching song "${query}":`, e.stack);
|
281 |
+
return [];
|
282 |
+
}
|
283 |
+
}
|
284 |
+
|
285 |
+
async function downloadYouTubeAudio(url) {
|
286 |
+
if (!ytdl.validateURL(url)) return { error: 'Link YouTube không hợp lệ! 😕' };
|
287 |
+
const videoId = ytdl.getURLVideoID(url);
|
288 |
+
const cacheKey = `youtube:${videoId}`;
|
289 |
+
const tempPath = path.join(CONFIG.tempPath, `${videoId}_temp.mp3`);
|
290 |
+
const filePath = path.join(CONFIG.mp3Path, `${videoId}_${Date.now()}.mp3`);
|
291 |
+
|
292 |
+
if (caches.mp3.has(cacheKey) && fs.existsSync(caches.mp3.get(cacheKey).filePath)) {
|
293 |
+
return { filePath: caches.mp3.get(cacheKey).filePath, fromCache: true };
|
294 |
+
}
|
295 |
+
|
296 |
+
FileHandler.ensureDir(CONFIG.mp3Path);
|
297 |
+
try {
|
298 |
+
await new Promise((resolve, reject) => {
|
299 |
+
ytdl(url, { filter: 'audioonly', quality: 'lowestaudio' })
|
300 |
+
.pipe(fs.createWriteStream(tempPath))
|
301 |
+
.on('finish', resolve)
|
302 |
+
.on('error', reject);
|
303 |
+
});
|
304 |
+
if (fs.statSync(tempPath).size > CONFIG.maxFileSize) throw new Error('File quá 20MB!');
|
305 |
+
fs.renameSync(tempPath, filePath);
|
306 |
+
if (caches.mp3.size >= CONFIG.maxMp3CacheSize) caches.mp3.delete(caches.mp3.keys().next().value);
|
307 |
+
caches.mp3.set(cacheKey, { filePath, timestamp: Date.now() });
|
308 |
+
return { filePath, fromCache: false };
|
309 |
+
} catch (e) {
|
310 |
+
console.error(`Error downloading audio ${url}:`, e.stack);
|
311 |
+
FileHandler.cleanupTempFile(tempPath);
|
312 |
+
return { error: `Lỗi tải nhạc: ${e.message}! 😭` };
|
313 |
+
}
|
314 |
+
}
|
315 |
+
|
316 |
+
async function suggestThemeOrEmoji(description, type) {
|
317 |
+
try {
|
318 |
+
const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
|
319 |
+
const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
|
320 |
+
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ị.`;
|
321 |
+
const { data } = await genaiService.models.generateContent({
|
322 |
+
model: 'models/gemini-1.5-pro-latest',
|
323 |
+
requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 50, temperature: 0.7 } },
|
324 |
+
auth,
|
325 |
+
});
|
326 |
+
return data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || (type === 'theme' ? 'blue' : '😎');
|
327 |
+
} catch (e) {
|
328 |
+
console.error(`Error suggesting ${type} for "${description}":`, e.stack);
|
329 |
+
return type === 'theme' ? 'blue' : '😎';
|
330 |
+
}
|
331 |
+
}
|
332 |
+
|
333 |
+
async function analyzeIntentWithGemini(body, context, chatHistory, threadInfo = {}) {
|
334 |
+
try {
|
335 |
+
const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
|
336 |
+
const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
|
337 |
+
const memberNames = threadInfo.userInfo?.map(u => ({ id: u.id, name: u.name, nickname: threadInfo.nicknames?.[u.id] })) || [];
|
338 |
+
const prompt = `
|
339 |
+
Phân tích ý định và trích xuất tham số từ câu lệnh sau: "${body}"
|
340 |
+
Lịch sử trò chuyện: ${chatHistory.slice(-3).map(m => `${m.role}: ${m.content}`).join('\n')}
|
341 |
+
Ngữ cảnh trước: ${context.lastIntent || 'casual'}, tin nhắn bot trước: ${context.lastBotMessage || 'Chưa có'}
|
342 |
+
Danh sách thành viên nhóm: ${JSON.stringify(memberNames)}
|
343 |
+
Các ý định có thể: nickname, groupImage, kick, add, groupName, poll, theme, emoji, action, menu, helpRequest, casual
|
344 |
+
Trả về JSON với định dạng:
|
345 |
+
{
|
346 |
+
"intent": "tên ý định",
|
347 |
+
"entities": { "tham số": "giá trị" },
|
348 |
+
"confidence": 0.0 đến 1.0
|
349 |
+
}
|
350 |
+
Lưu ý:
|
351 |
+
- 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.
|
352 |
+
- 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 }
|
353 |
+
`;
|
354 |
+
const { data } = await genaiService.models.generateContent({
|
355 |
+
model: 'models/gemini-1.5-pro-latest',
|
356 |
+
requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 200, temperature: 0.5 } },
|
357 |
+
auth,
|
358 |
+
});
|
359 |
+
const result = JSON.parse(data?.candidates?.[0]?.content?.parts?.[0]?.text || '{}');
|
360 |
+
return result.intent && result.entities ? result : { intent: 'casual', entities: {}, confidence: 0 };
|
361 |
+
} catch (e) {
|
362 |
+
console.error(`Error analyzing intent with Gemini:`, e.stack);
|
363 |
+
return { intent: 'casual', entities: {}, confidence: 0 };
|
364 |
+
}
|
365 |
+
}
|
366 |
+
|
367 |
+
function normalizeText(text) {
|
368 |
+
return text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
|
369 |
+
}
|
370 |
+
|
371 |
+
function cleanText(text) {
|
372 |
+
return text
|
373 |
+
.replace(/[^\p{L}\p{N}\s@:/.-😀-🙏]/gu, '')
|
374 |
+
.replace(/(?<!\w)[!?.](?!\w)/g, '')
|
375 |
+
.trim();
|
376 |
+
}
|
377 |
+
|
378 |
+
async function detectIntent(body, context = {}, chatHistory = [], api, threadID) {
|
379 |
+
const intents = [
|
380 |
+
{ name: 'nickname', description: 'Đổi biệt danh thành viên', entities: ['user', 'nickname'], confirm: false, weight: 3 },
|
381 |
+
{ name: 'groupImage', description: 'Đổi ảnh nhóm', entities: ['url'], confirm: false, weight: 3 },
|
382 |
+
{ name: 'kick', description: 'Kick thành viên', entities: ['user'], confirm: true, weight: 2 },
|
383 |
+
{ name: 'add', description: 'Thêm thành viên', entities: ['user'], confirm: false, weight: 2 },
|
384 |
+
{ name: 'groupName', description: 'Đổi tên nhóm', entities: ['name'], confirm: false, weight: 3 },
|
385 |
+
{ name: 'poll', description: 'Tạo bình chọn', entities: ['options'], confirm: false, weight: 2 },
|
386 |
+
{ name: 'theme', description: 'Đổi chủ đề nhóm', entities: ['theme'], confirm: false, weight: 2 },
|
387 |
+
{ name: 'emoji', description: 'Đổi emoji nhóm', entities: ['emoji'], confirm: false, weight: 2 },
|
388 |
+
{ name: 'action', description: 'Tìm/phát nhạc', entities: ['query'], confirm: false, weight: 2 },
|
389 |
+
{ name: 'menu', description: 'Xem danh sách lệnh', entities: [], confirm: false, weight: 1 },
|
390 |
+
{ name: 'helpRequest', description: 'Yêu cầu trợ giúp', entities: [], confirm: false, weight: 1 },
|
391 |
+
{ name: 'casual', description: 'Trò chuyện thông thường', entities: [], confirm: false, weight: 0 },
|
392 |
+
];
|
393 |
+
|
394 |
+
try {
|
395 |
+
const threadInfo = await api.getThreadInfo(threadID).catch(e => {
|
396 |
+
console.error(`Error fetching thread info ${threadID}:`, e.stack);
|
397 |
+
return {};
|
398 |
+
});
|
399 |
+
|
400 |
+
const geminiResult = await analyzeIntentWithGemini(body, context, chatHistory, threadInfo);
|
401 |
+
console.log('Gemini intent analysis:', geminiResult);
|
402 |
+
|
403 |
+
const intentConfig = intents.find(i => i.name === geminiResult.intent) || intents.find(i => i.name === 'casual');
|
404 |
+
|
405 |
+
const isValid = !intentConfig.entities.length || intentConfig.entities.every(ent => geminiResult.entities[ent]);
|
406 |
+
if (!isValid) {
|
407 |
+
console.log('Invalid entities for intent:', geminiResult.intent, geminiResult.entities);
|
408 |
+
return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false };
|
409 |
+
}
|
410 |
+
|
411 |
+
return {
|
412 |
+
name: geminiResult.intent,
|
413 |
+
matches: geminiResult.entities,
|
414 |
+
score: geminiResult.confidence * 10,
|
415 |
+
confidence: geminiResult.confidence,
|
416 |
+
confirm: intentConfig.confirm || false,
|
417 |
+
};
|
418 |
+
} catch (e) {
|
419 |
+
console.error('Error detecting intent:', e.stack);
|
420 |
+
return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false };
|
421 |
+
}
|
422 |
+
}
|
423 |
+
|
424 |
+
async function processIntent(uid, body, event, api, intent, context, chatHistory) {
|
425 |
+
const locks = new Map();
|
426 |
+
while (locks.has(uid)) await new Promise(r => setTimeout(r, 10));
|
427 |
+
locks.set(uid, true);
|
428 |
+
|
429 |
+
try {
|
430 |
+
globalThis.client.pendingCommands = globalThis.client.pendingCommands || new Map();
|
431 |
+
const pending = globalThis.client.pendingCommands.get(uid);
|
432 |
+
|
433 |
+
if (pending?.waitingFor === 'confirmKick' && body.toLowerCase() === 'ok') {
|
434 |
+
globalThis.client.pendingCommands.delete(uid);
|
435 |
+
const message = await executeGroupAction(api, event.threadID, 'kick', pending.userID);
|
436 |
+
await updateContext(uid, body, message, 'kick', message);
|
437 |
+
return { message };
|
438 |
+
}
|
439 |
+
|
440 |
+
if (pending?.waitingFor === 'singSelect' && body.match(/^[1-3]$/)) {
|
441 |
+
const choice = parseInt(body) - 1;
|
442 |
+
const { songs } = pending.data;
|
443 |
+
globalThis.client.pendingCommands.delete(uid);
|
444 |
+
if (!songs[choice]) return { message: `Số ${body} không hợp lệ! 😕` };
|
445 |
+
const result = await downloadYouTubeAudio(songs[choice].url);
|
446 |
+
if (result.error) return { message: result.error };
|
447 |
+
const message = `Nhạc "${songs[choice].title}" đây! 🎵 ${result.fromCache ? '(cache)' : ''}`;
|
448 |
+
await updateContext(uid, body, message, 'action', message);
|
449 |
+
return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) };
|
450 |
+
}
|
451 |
+
|
452 |
+
if (pending?.waitingFor) {
|
453 |
+
globalThis.client.pendingCommands.delete(uid);
|
454 |
+
return { message: 'Hủy lệnh! 😎' };
|
455 |
+
}
|
456 |
+
|
457 |
+
const groupActions = {
|
458 |
+
nickname: {
|
459 |
+
pattern: 'nickname',
|
460 |
+
value: async () => {
|
461 |
+
if (!intent.matches?.user || !intent.matches?.nickname) {
|
462 |
+
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)! 😝' };
|
463 |
+
}
|
464 |
+
const userID = await resolveUserID(api, event.threadID, intent.matches.user, event);
|
465 |
+
return userID.error ? userID : [userID, intent.matches.nickname];
|
466 |
+
},
|
467 |
+
check: v => Array.isArray(v) && v[0] && v[1],
|
468 |
+
},
|
469 |
+
groupImage: {
|
470 |
+
pattern: 'image',
|
471 |
+
value: () => intent.matches?.url || { error: 'Cần link ảnh trực tiếp! 😝' },
|
472 |
+
},
|
473 |
+
kick: {
|
474 |
+
pattern: 'kick',
|
475 |
+
value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để kick! 😝' },
|
476 |
+
confirm: true,
|
477 |
+
},
|
478 |
+
add: {
|
479 |
+
pattern: 'add',
|
480 |
+
value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để thêm! 😝' },
|
481 |
+
},
|
482 |
+
groupName: {
|
483 |
+
pattern: 'name',
|
484 |
+
value: () => intent.matches?.name || { error: 'Cần tên nhóm mới! 😝' },
|
485 |
+
},
|
486 |
+
poll: {
|
487 |
+
pattern: 'poll',
|
488 |
+
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! 😝' },
|
489 |
+
check: v => v?.options?.length >= 2,
|
490 |
+
},
|
491 |
+
theme: {
|
492 |
+
pattern: 'theme',
|
493 |
+
value: async () => intent.matches?.theme?.match(/^(blue|red|green|purple|pink)$/i) || await suggestThemeOrEmoji(intent.matches?.theme || 'default', 'theme'),
|
494 |
+
},
|
495 |
+
emoji: {
|
496 |
+
pattern: 'emoji',
|
497 |
+
value: async () => intent.matches?.emoji?.match(/[\u{1F600}-\u{1F64F}]/u) || await suggestThemeOrEmoji(intent.matches?.emoji || 'happy', 'emoji'),
|
498 |
+
},
|
499 |
+
};
|
500 |
+
|
501 |
+
if (intent.name in groupActions) {
|
502 |
+
if (!(await checkAdminPermission(uid, event.threadID, api))) return { message: 'Cần quyền admin! 😎' };
|
503 |
+
const { pattern, value, check, confirm } = groupActions[intent.name];
|
504 |
+
const val = await value();
|
505 |
+
if (val?.error) return { message: val.error };
|
506 |
+
if (check && !check(val)) return { message: 'Dữ liệu không hợp lệ! 😝' };
|
507 |
+
if (confirm && intent.confirm) {
|
508 |
+
globalThis.client.pendingCommands.set(uid, {
|
509 |
+
command: intent.name,
|
510 |
+
userID: val,
|
511 |
+
user: intent.matches.user?.replace(/^@/, '') || val,
|
512 |
+
waitingFor: 'confirmKick',
|
513 |
+
timestamp: Date.now(),
|
514 |
+
});
|
515 |
+
return { message: `Chắc chắn muốn kick ${intent.matches.user?.replace(/^@/, '') || val}? Reply 'ok'! 😈` };
|
516 |
+
}
|
517 |
+
const message = await executeGroupAction(api, event.threadID, pattern, val);
|
518 |
+
await updateContext(uid, body, message, intent.name, message);
|
519 |
+
return { message };
|
520 |
+
}
|
521 |
+
|
522 |
+
if (intent.name === 'action') {
|
523 |
+
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();
|
524 |
+
if (query.includes('youtube.com')) {
|
525 |
+
const result = await downloadYouTubeAudio(query);
|
526 |
+
if (result.error) return { message: result.error };
|
527 |
+
const message = `Nhạc đây! 🎵 ${result.fromCache ? '(cache)' : ''}`;
|
528 |
+
await updateContext(uid, body, message, 'action', message);
|
529 |
+
return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) };
|
530 |
+
}
|
531 |
+
const songs = await searchSong(query);
|
532 |
+
if (!songs.length) return { message: `Không tìm thấy "${query}"! 😕` };
|
533 |
+
globalThis.client.pendingCommands.set(uid, { command: 'sing', waitingFor: 'singSelect', data: { songs }, timestamp: Date.now() });
|
534 |
+
const message = `Chọn bài:\n${songs.map((s, i) => `${i + 1}. ${s.title}`).join('\n')}\nReply số 1-3!`;
|
535 |
+
await updateContext(uid, body, message, 'action', message);
|
536 |
+
return { message };
|
537 |
+
}
|
538 |
+
|
539 |
+
if (intent.name === 'menu') {
|
540 |
+
const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands();
|
541 |
+
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')}`;
|
542 |
+
await updateContext(uid, body, message, 'menu', message);
|
543 |
+
return { message };
|
544 |
+
}
|
545 |
+
|
546 |
+
if (intent.name === 'helpRequest') {
|
547 |
+
const message = `Khó xài? Gõ "!dun menu" để xem lệnh! 😎`;
|
548 |
+
await updateContext(uid, body, message, 'helpRequest', message);
|
549 |
+
return { message };
|
550 |
+
}
|
551 |
+
|
552 |
+
if (intent.name === 'casual') {
|
553 |
+
const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands();
|
554 |
+
const args = normalizeText(body).split(/\s+/).filter(Boolean);
|
555 |
+
const cmdName = args[0].match(/^[!\/\#]?dun$/) && args[1] ? args[1] : '';
|
556 |
+
const cmd = commands.find(c => normalizeText(c.name) === cmdName);
|
557 |
+
if (cmd && await checkAdminPermission(uid, event.threadID, api)) {
|
558 |
+
await cmd.module.onRun({ api, event, args: args.slice(2) });
|
559 |
+
await updateContext(uid, body, 'Thực thi lệnh tùy chỉnh', 'command', 'Đã chạy lệnh!');
|
560 |
+
return null;
|
561 |
+
}
|
562 |
+
}
|
563 |
+
|
564 |
+
return null;
|
565 |
+
} catch (e) {
|
566 |
+
console.error(`Error processing intent for ${uid}:`, e.stack);
|
567 |
+
return { message: `Lỗi xử lý lệnh: ${e.message}! 😭` };
|
568 |
+
} finally {
|
569 |
+
locks.delete(uid);
|
570 |
+
}
|
571 |
+
}
|
572 |
+
|
573 |
+
async function handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries = 0) {
|
574 |
+
try {
|
575 |
+
const intentResult = await processIntent(uid, body, event, api, intent, context, chatHistory);
|
576 |
+
if (intentResult) return intentResult;
|
577 |
+
|
578 |
+
const cacheKey = `${uid}:${body}`;
|
579 |
+
if (caches.gemini.has(cacheKey) && Date.now() - caches.gemini.get(cacheKey).timestamp < CONFIG.cacheDuration) {
|
580 |
+
const response = caches.gemini.get(cacheKey).response;
|
581 |
+
await updateContext(uid, body, response, 'casual', response);
|
582 |
+
return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] };
|
583 |
+
}
|
584 |
+
|
585 |
+
const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
|
586 |
+
const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
|
587 |
+
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}"`;
|
588 |
+
const { data } = await genaiService.models.generateContent({
|
589 |
+
model: 'models/gemini-1.5-pro-latest',
|
590 |
+
requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 2048, temperature: 0.7 } },
|
591 |
+
auth,
|
592 |
+
});
|
593 |
+
const response = data?.candidates?.[0]?.content?.parts?.[0]?.text || 'Lỗi rồi, thử lại! 😅';
|
594 |
+
await appendToChatHistory(uid, [...chatHistory, { role: 'user', content: body }, { role: 'assistant', content: response }]);
|
595 |
+
caches.gemini.set(cacheKey, { response, timestamp: Date.now() });
|
596 |
+
await updateContext(uid, body, response, 'casual', response);
|
597 |
+
return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] };
|
598 |
+
} catch (e) {
|
599 |
+
console.error(`Error in Gemini response for ${uid}:`, e.stack);
|
600 |
+
if (e.response?.status === 429 && retries < 3 && currentApiKeyIndex < API_KEYS.length - 1) {
|
601 |
+
currentApiKeyIndex++;
|
602 |
+
await new Promise(r => setTimeout(r, 1000 * Math.pow(2, retries)));
|
603 |
+
return handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries + 1);
|
604 |
+
}
|
605 |
+
return { message: `Lỗi Gemini: ${e.message}! Thử lại nhé! 😭` };
|
606 |
+
}
|
607 |
+
}
|
608 |
+
|
609 |
+
export default {
|
610 |
+
config: {
|
611 |
+
name: 'dun',
|
612 |
+
author: 'Trần Thanh Dương',
|
613 |
+
version: '1.0.0',
|
614 |
+
role: 0,
|
615 |
+
group: 'Tiện ích',
|
616 |
+
description: '',
|
617 |
+
usages: '',
|
618 |
+
usePrefix: true,
|
619 |
+
delay: 0,
|
620 |
+
subcommands: {
|
621 |
+
history: {
|
622 |
+
role: 0,
|
623 |
+
delay: 5,
|
624 |
+
onRun: async ({ api, event, args }) => {}
|
625 |
+
},
|
626 |
+
cache: {
|
627 |
+
role: 0,
|
628 |
+
delay: 5,
|
629 |
+
onRun: async ({ api, event, args }) => {}
|
630 |
+
}
|
631 |
+
}
|
632 |
+
},
|
633 |
+
initialize() {
|
634 |
+
try {
|
635 |
+
FileHandler.ensureDir(CONFIG.cacheDir);
|
636 |
+
FileHandler.loadCommands();
|
637 |
+
} catch (e) {
|
638 |
+
console.error('Error initializing bot:', e.stack);
|
639 |
+
}
|
640 |
+
},
|
641 |
+
async onRun({ api, event }) {
|
642 |
+
try {
|
643 |
+
this.initialize();
|
644 |
+
const uid = event.senderID;
|
645 |
+
const body = event.body?.trim();
|
646 |
+
if (!body) return api.sendMessage('Nói gì đi, tui chờ! 😝', event.threadID);
|
647 |
+
const context = FileHandler.loadJSON(CONFIG.contextPath);
|
648 |
+
const chatHistory = loadChatHistory(uid);
|
649 |
+
const intent = await detectIntent(body, context[uid], chatHistory, api, event.threadID);
|
650 |
+
const response = await handleGeminiResponse(uid, body, event, api, intent, chatHistory, context);
|
651 |
+
if (!response) return;
|
652 |
+
api.sendMessage({ body: response.message, attachment: response.attachments }, event.threadID, (err, info) => {
|
653 |
+
if (err) {
|
654 |
+
console.error(err);
|
655 |
+
return;
|
656 |
+
}
|
657 |
+
globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: uid });
|
658 |
+
if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID);
|
659 |
+
});
|
660 |
+
} catch (e) {
|
661 |
+
console.error(e);
|
662 |
+
api.sendMessage(`Lỗi bot: ${e.message}! Thử lại nhé! 😭`, event.threadID);
|
663 |
+
}
|
664 |
+
},
|
665 |
+
async onReply({ api, event }) {
|
666 |
+
try {
|
667 |
+
this.initialize();
|
668 |
+
const { threadID, messageID, senderID, body } = event;
|
669 |
+
const context = FileHandler.loadJSON(CONFIG.contextPath);
|
670 |
+
const chatHistory = loadChatHistory(senderID);
|
671 |
+
const intent = await detectIntent(body || '', context[senderID], chatHistory, api, threadID);
|
672 |
+
const response = await handleGeminiResponse(senderID, body?.trim() || '', event, api, intent, chatHistory, context);
|
673 |
+
if (!response) return;
|
674 |
+
api.sendMessage({ body: response.message, attachment: response.attachments }, threadID, (err, info) => {
|
675 |
+
if (err) {
|
676 |
+
console.error(err);
|
677 |
+
return;
|
678 |
+
}
|
679 |
+
globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: senderID });
|
680 |
+
if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID);
|
681 |
+
}, messageID);
|
682 |
+
} catch (e) {
|
683 |
+
console.error(e);
|
684 |
+
api.sendMessage(`Lỗi xử lý reply: ${e.message}! Thử lại nhé! 😭`, event.threadID);
|
685 |
+
}
|
686 |
+
},
|
687 |
+
};
|