-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
420 lines (368 loc) · 18.6 KB
/
index.js
File metadata and controls
420 lines (368 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import 'dotenv/config'
import makeWASocket, {
DisconnectReason,
useMultiFileAuthState,
fetchLatestBaileysVersion
} from "@whiskeysockets/baileys";
import qrcode from "qrcode-terminal";
import fs from "fs";
import axios from "axios";
import { addCoins, getBalance } from "./db.js";
// ================= IMAGE SEARCH ENGINE =================
const IMG_CACHE = new Map();
function sleep(ms) {
return new Promise(res => setTimeout(res, ms));
}
function pickRandom(arr, n = 5) {
return arr.sort(() => 0.5 - Math.random()).slice(0, n);
}
async function searchPinterest(query) {
const url = `https://www.pinterest.com/resource/BaseSearchResource/get/?source_url=/search/pins/?q=${encodeURIComponent(query)}&data=${encodeURIComponent(JSON.stringify({
options: {
query: query,
scope: "pins",
no_fetch_context_on_resource: false
},
context: {}
}))}`;
const res = await fetch(url, {
headers: {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"accept": "application/json"
}
});
if (!res.ok) throw new Error("Pinterest blocked");
const json = await res.json();
const results = json?.resource_response?.data?.results || [];
const images = results.map(p => p?.images?.orig?.url).filter(Boolean);
return images;
}
async function searchDuckDuckGo(query) {
const vqdRes = await fetch(`https://duckduckgo.com/?q=${encodeURIComponent(query)}&iax=images&ia=images`);
const vqdText = await vqdRes.text();
const vqdMatch = vqdText.match(/vqd='(.*?)'/);
if (!vqdMatch) throw new Error("DDG vqd fail");
const vqd = vqdMatch[1];
const api = `https://duckduckgo.com/i.js?l=us-en&o=json&q=${encodeURIComponent(query)}&vqd=${vqd}&f=,,,&p=1`;
const res = await fetch(api, { headers: { "user-agent": "Mozilla/5.0" } });
if (!res.ok) throw new Error("DDG blocked");
const json = await res.json();
return json.results.map(r => r.image).filter(Boolean);
}
async function imageSearch(query, limit = 5) {
const key = query.toLowerCase();
if (IMG_CACHE.has(key)) return pickRandom(IMG_CACHE.get(key), limit);
let images = [];
try {
images = await searchPinterest(query);
} catch (e) { console.log("Pinterest failed, trying DDG..."); }
if (images.length < 3) {
try {
const ddg = await searchDuckDuckGo(query);
images = images.concat(ddg);
} catch (e) { console.log("DDG also failed"); }
}
images = [...new Set(images)];
if (images.length === 0) throw new Error("No images found");
IMG_CACHE.set(key, images);
return pickRandom(images, limit);
}
// ================= ACTIVITY SYSTEM =================
const ACTIVITY_FILE = "./data/activity.json";
if (!fs.existsSync("./data")) fs.mkdirSync("./data");
let activityDB = {};
if (fs.existsSync(ACTIVITY_FILE)) {
activityDB = JSON.parse(fs.readFileSync(ACTIVITY_FILE));
}
function saveActivity() {
fs.writeFileSync(ACTIVITY_FILE, JSON.stringify(activityDB, null, 2));
}
// ================= STD GAME HELPERS =================
const activeStdGames = new Map();
const lastStdCompleted = new Map();
const STD_COOLDOWN_MS = 2 * 60 * 1000;
const STD_TIMEOUT_MS = 2 * 60 * 1000;
const EMOJI_POOL = [
"🍥","🔥","🥊","⚡","🐉","💧","✨","🌙","🍀","💥",
"🌸","🌊","🪄","🔮","🍣","🍕","🍩","🍪","🌟","⚔️",
"🛡️","🐱","🐶","🐼","🐵","🐲","🌈","🌪️","☀️","🌙"
];
function shuffleArray(arr) {
return arr.slice().sort(() => 0.5 - Math.random());
}
function startStdGame(phone, destJid, sockInstance) {
if (activeStdGames.has(phone)) throw new Error("ALREADY_ACTIVE");
const base = shuffleArray(EMOJI_POOL).slice(0, 5);
const idx = Math.floor(Math.random() * base.length);
const otherChoices = EMOJI_POOL.filter(e => !base.includes(e));
const diff = otherChoices[Math.floor(Math.random() * otherChoices.length)];
const alt = base.slice();
alt[idx] = diff;
const A = `A: ${base.join("")}`;
const B = `B: ${alt.join("")}`;
const ts = Date.now();
const timeoutId = setTimeout(async () => {
if (!activeStdGames.has(phone)) return;
activeStdGames.delete(phone);
try {
await sockInstance.sendMessage(destJid, { text: `⏰ Time's up! You didn't answer in time. Start a new game with .std` });
} catch (e) {}
}, STD_TIMEOUT_MS);
activeStdGames.set(phone, { correct: diff, ts, timeoutId, fromJid: destJid });
return { A, B };
}
function getToday() { return new Date().toISOString().slice(0, 10); }
function getLastNDays(n) {
const days = [];
for (let i = 0; i < n; i++) {
const d = new Date();
d.setDate(d.getDate() - i);
days.push(d.toISOString().slice(0, 10));
}
return days;
}
const PREFIX = ".";
async function startBot() {
const { state, saveCreds } = await useMultiFileAuthState("./session");
const { version } = await fetchLatestBaileysVersion();
const sock = makeWASocket({
version,
auth: state,
browser: ["GMB Bot", "Chrome", "1.0"],
markOnlineOnConnect: false,
syncFullHistory: false
});
sock.ev.on("creds.update", saveCreds);
sock.ev.on("connection.update", (update) => {
const { connection, lastDisconnect, qr } = update;
if (qr) qrcode.generate(qr, { small: true });
if (connection === "open") console.log("✅ Bot connected successfully!");
if (connection === "close") {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) startBot();
}
});
sock.ev.on("group-participants.update", async (update) => {
try {
const groupJid = update.id;
const action = update.action;
if (!["add", "invite"].includes(action)) return;
let participants = (update.participants || []).map(p => typeof p === "string" ? p : p.id).filter(Boolean);
await new Promise(r => setTimeout(r, 700));
for (const userJidRaw of participants) {
const userJid = userJidRaw.includes("@") ? userJidRaw : `${userJidRaw}@s.whatsapp.net`;
const username = userJid.split("@")[0];
const welcomeText = `⚔️🔥 *A NEW WARRIOR HAS ENTERED THE REALM* 🔥⚔️\n\n💥 *@${username} has entered the CHAOS!* 💥\n\n📝 Name:\n🎂 Age:\n🍥 Anime:\n👑 Character:\n\n⚔️ _Choose your side wisely..._ 😏🔥`;
await sock.sendMessage(groupJid, { text: welcomeText, mentions: [userJid] });
}
} catch (err) { console.error("WELCOME ERROR:", err); }
});
function jidToId(jid) {
if (!jid) return null;
return jid.split("@")[0].split(":")[0];
}
// ================= MESSAGE HANDLER =================
sock.ev.on("messages.upsert", async (m) => {
const msg = m.messages[0];
if (!msg.message || msg.key.fromMe) return;
const from = msg.key.remoteJid;
const isGroup = from.endsWith("@g.us");
// --- 🛡️ GLOBAL IDENTITY SCANNER ---
let whoRaw = msg.key.participant || msg.key.remoteJid;
let senderNum = whoRaw.split('@')[0].split(':')[0];
if (isGroup) {
try {
const groupMetadata = await sock.groupMetadata(from);
const participant = groupMetadata.participants.find(p => p.id === whoRaw);
if (participant && participant.phoneNumber) {
senderNum = participant.phoneNumber.split('@')[0].split(':')[0];
}
} catch (e) {}
}
// --- 📊 ACTIVITY TRACKING ---
if (isGroup) {
const today = getToday();
if (!activityDB[from]) activityDB[from] = {};
if (!activityDB[from][today]) activityDB[from][today] = {};
if (!activityDB[from][today][senderNum]) activityDB[from][today][senderNum] = 0;
activityDB[from][today][senderNum] += 1;
saveActivity();
}
const text = msg.message.conversation || msg.message.extendedTextMessage?.text || "";
// --- 🔎 STD GAME REPLY CHECK ---
if (activeStdGames.has(senderNum)) {
const game = activeStdGames.get(senderNum);
const reply = text.trim();
if (reply) {
const answeredCorrect = reply.includes(game.correct);
clearTimeout(game.timeoutId);
activeStdGames.delete(senderNum);
if (answeredCorrect) {
const secondsTaken = Math.floor((Date.now() - game.ts) / 1000);
const coins = Math.max(1, 60 - secondsTaken);
try {
const newBalance = await addCoins(senderNum, coins);
lastStdCompleted.set(senderNum, Date.now());
await sock.sendMessage(from, {
text: `✅ *Correct!* You found: ${game.correct}\n⏱️ Time: ${secondsTaken}s\n💰 Reward: §${coins} Sigils\n🔥 New balance: §${newBalance}`
}, { quoted: msg });
} catch (err) { await sock.sendMessage(from, { text: `❌ ${err.message}` }, { quoted: msg }); }
} else {
lastStdCompleted.set(senderNum, Date.now());
await sock.sendMessage(from, { text: `❌ *Wrong!* The correct emoji was: ${game.correct}` }, { quoted: msg });
}
return;
}
}
if (!text.startsWith(PREFIX)) return;
const args = text.slice(1).trim().split(/\s+/);
const command = args.shift().toLowerCase();
// ================= COMMANDS =================
if (command === "ping") return sock.sendMessage(from, { text: "🏓 Pong!" }, { quoted: msg });
if (isGroup) {
const groupMetadata = await sock.groupMetadata(from);
const participants = groupMetadata.participants;
// --- ADMIN DETECTION ---
const senderParticipant = participants.find(p => jidToId(p.id) === jidToId(whoRaw) || (p.phoneNumber && jidToId(p.phoneNumber) === jidToId(whoRaw)));
const isSenderAdmin = senderParticipant?.admin === "admin" || senderParticipant?.admin === "superadmin";
const botId = jidToId(sock.user.id);
const botParticipant = participants.find(p => jidToId(p.id) === botId || (p.phoneNumber && jidToId(p.phoneNumber) === botId));
const isBotAdmin = botParticipant?.admin === "admin" || botParticipant?.admin === "superadmin";
// 1. .active
if (command === "active") {
const threshold = 1; // Lowered to 1 so you see results immediately
const days = getLastNDays(7);
const groupData = activityDB[from] || {};
let perUser = {};
days.forEach(d => {
if (groupData[d]) {
Object.entries(groupData[d]).forEach(([uid, count]) => {
perUser[uid] = (perUser[uid] || 0) + count;
});
}
});
const sorted = Object.entries(perUser).filter(([uid, count]) => count >= threshold).sort((a, b) => b[1] - a[1]).slice(0, 15);
let outText = `✅ *Active Members (Last 7 Days)*\n\n`;
let mentions = [];
sorted.forEach(([uid, count], i) => {
const p = participants.find(p => jidToId(p.id) === uid || (p.phoneNumber && jidToId(p.phoneNumber) === uid));
const mentionJid = p ? (p.phoneNumber ? p.phoneNumber.split(":")[0] + "@s.whatsapp.net" : p.id) : `${uid}@s.whatsapp.net`;
mentions.push(mentionJid);
outText += `${i+1}. @${mentionJid.split("@")[0]} — ${count} msgs\n`;
});
return sock.sendMessage(from, { text: outText, mentions }, { quoted: msg });
}
// 2. .activity
if (command === "activity") {
const days = getLastNDays(7);
const groupData = activityDB[from] || {};
let total = 0, perUser = {};
days.forEach(d => {
if (groupData[d]) {
Object.entries(groupData[d]).forEach(([uid, count]) => {
total += count;
perUser[uid] = (perUser[uid] || 0) + count;
});
}
});
const sorted = Object.entries(perUser).sort((a, b) => b[1] - a[1]).slice(0, 5);
let outText = `📊 *Group Activity*\n💬 Total Messages: ${total}\n\n🔥 *Top Contributors:*\n`;
let mentions = [];
sorted.forEach(([uid, count]) => {
const p = participants.find(p => jidToId(p.id) === uid || (p.phoneNumber && jidToId(p.phoneNumber) === uid));
const mentionJid = p ? (p.phoneNumber ? p.phoneNumber.split(":")[0] + "@s.whatsapp.net" : p.id) : `${uid}@s.whatsapp.net`;
mentions.push(mentionJid);
outText += `• @${mentionJid.split("@")[0]} : ${count}\n`;
});
return sock.sendMessage(from, { text: outText, mentions });
}
// 3. .inactive
if (command === "inactive") {
const days = getLastNDays(7);
const groupData = activityDB[from] || {};
let activeUids = new Set();
days.forEach(d => { if (groupData[d]) Object.keys(groupData[d]).forEach(u => activeUids.add(u)); });
const inactive = participants.filter(p => !activeUids.has(jidToId(p.id)) && (!p.phoneNumber || !activeUids.has(jidToId(p.phoneNumber))));
let outText = `💤 *Inactive Members (0 msgs in 7 days)*\n\n`;
let mentions = [];
inactive.slice(0, 20).forEach(p => {
const mJid = p.phoneNumber ? p.phoneNumber.split(":")[0] + "@s.whatsapp.net" : p.id;
mentions.push(mJid);
outText += `• @${mJid.split("@")[0]}\n`;
});
return sock.sendMessage(from, { text: outText, mentions });
}
// --- ADMIN COMMANDS ---
if (["kick", "del", "promote", "demote", "tagall", "hidetag"].includes(command) && !isSenderAdmin) {
return sock.sendMessage(from, { text: "❌ *Admin only!*" }, { quoted: msg });
}
if (command === "kick") {
if (!isBotAdmin) return sock.sendMessage(from, { text: "❌ Make the bot Admin first." });
const target = msg.message.extendedTextMessage?.contextInfo?.participant || (args[0] ? args[0].replace("@", "") + "@s.whatsapp.net" : null);
if (!target) return sock.sendMessage(from, { text: "❌ Tag someone to kick." });
await sock.groupParticipantsUpdate(from, [target], "remove");
return sock.sendMessage(from, { text: "👢 Removed user." });
}
if (command === "del") {
const key = {
remoteJid: from,
fromMe: false,
id: msg.message.extendedTextMessage?.contextInfo?.stanzaId,
participant: msg.message.extendedTextMessage?.contextInfo?.participant
};
if (!key.id) return sock.sendMessage(from, { text: "❌ Reply to a message to delete it." });
await sock.sendMessage(from, { delete: key });
}
if (command === "promote" || command === "demote") {
const target = msg.message.extendedTextMessage?.contextInfo?.participant || (args[0] ? args[0].replace("@", "") + "@s.whatsapp.net" : null);
if (!target) return sock.sendMessage(from, { text: `❌ Tag someone to ${command}.` });
await sock.groupParticipantsUpdate(from, [target], command);
return sock.sendMessage(from, { text: `✅ User ${command}d.` });
}
if (command === "tagall" || command === "hidetag") {
const message = args.join(" ") || "Attention!";
const mentions = participants.map(p => p.id);
if (command === "tagall") {
let out = `📢 *Tag All*\n\n${message}\n\n`;
mentions.forEach(m => out += `@${m.split("@")[0]} `);
await sock.sendMessage(from, { text: out, mentions });
} else {
await sock.sendMessage(from, { text: message, mentions });
}
}
// --- ECONOMY & GAMES ---
if (command === "std") {
try {
await getBalance(senderNum);
const last = lastStdCompleted.get(senderNum) || 0;
if (Date.now() - last < STD_COOLDOWN_MS) {
return sock.sendMessage(from, { text: `⏳ Cooldown: ${Math.ceil((STD_COOLDOWN_MS - (Date.now() - last)) / 1000)}s.` }, { quoted: msg });
}
const { A, B } = startStdGame(senderNum, from, sock);
await sock.sendMessage(from, { text: `🔎 *Spot the Difference*\n\n${A}\n${B}` }, { quoted: msg });
} catch (err) { await sock.sendMessage(from, { text: "❌ Register first to play." }, { quoted: msg }); }
}
if (command === "give") {
try {
const amount = Number(args[0]) || 0;
if (amount <= 0) return sock.sendMessage(from, { text: "❌ Invalid amount" });
const newBal = await addCoins(senderNum, amount);
await sock.sendMessage(from, { text: `💰 Success!\n🔥 Balance: §${newBal}` });
} catch (err) { await sock.sendMessage(from, { text: `❌ ${err.message}` }); }
}
if (command === "img") {
if (!args.length) return sock.sendMessage(from, { text: "❌ Usage: .img <query>" });
const query = args.join(" ");
await sock.sendMessage(from, { text: `🔍 Searching for: *${query}*` });
try {
const images = await imageSearch(query, 5);
for (const img of images) {
await sock.sendMessage(from, { image: { url: img }, caption: `🖼️ *${query}*` });
await sleep(700);
}
} catch (err) { await sock.sendMessage(from, { text: "❌ No images found." }); }
}
}
});
}
startBot();