@yanz_tksrv/sepuhbot 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/ATRIBUTION.md +56 -0
  2. package/LICENSE +21 -0
  3. package/README.md +260 -3
  4. package/bot.js +1046 -0
  5. package/package.json +13 -6
package/bot.js ADDED
@@ -0,0 +1,1046 @@
1
+ import { makeWASocket, DisconnectReason, useMultiFileAuthState, fetchLatestBaileysVersion, downloadContentFromMessage, Browsers, prepareWAMessageMedia, generateWAMessageFromContent, proto } from '@whiskeysockets/baileys'
2
+ import qrcodeTerminal from 'qrcode-terminal'
3
+ import Jimp from 'jimp'
4
+ import QRCode from 'qrcode'
5
+ import fs from 'fs'
6
+ import path from 'path'
7
+ import http from 'http'
8
+ import axios from 'axios'
9
+ import readline from 'readline'
10
+ import ffmpeg from 'fluent-ffmpeg'
11
+ import webp from 'node-webpmux'
12
+
13
+ // ==========================================
14
+ // KONFIGURASI DASHBOARD PORT 3007 & PERSISTENCE 🔥
15
+ // ==========================================
16
+ const DASHBOARD_PORT = 3007
17
+ const CONFIG_FILE = path.join('./', 'bot_config.json')
18
+ const DASHBOARD_HTML_FILE = path.join('./', 'dashboard.html')
19
+ const DOWNLOADER_BASE_URL = 'https://apis-tkzrv.takeserver.web.id/api'
20
+
21
+ const defaultConfig = {
22
+ packName: 'sound sticker',
23
+ authorName: 'yanz',
24
+ aiSessionActive: false,
25
+ antiSider: true,
26
+ geminiApiKey: '-aAs',
27
+ removeBgApiKey: 'API_KEY_REMOVEBG_LU_DISINI'
28
+ }
29
+
30
+ function loadConfig() {
31
+ try {
32
+ if (fs.existsSync(CONFIG_FILE)) {
33
+ const raw = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'))
34
+ return { ...defaultConfig, ...raw }
35
+ }
36
+ } catch {}
37
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(defaultConfig, null, 2))
38
+ return { ...defaultConfig }
39
+ }
40
+
41
+ let botConfig = loadConfig()
42
+ function saveConfig(nextPartial = {}) {
43
+ botConfig = { ...botConfig, ...nextPartial }
44
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(botConfig, null, 2))
45
+ }
46
+
47
+ const startTime = Date.now()
48
+ let isConnected = false
49
+ let botNumber = '-'
50
+ let processedMessages = 0
51
+ const activityLogs = []
52
+
53
+ function pushLog(msg) {
54
+ const timeStr = new Date().toLocaleTimeString('id-ID', { hour12: false })
55
+ const line = `[${timeStr}] ${msg}`
56
+ activityLogs.push(line)
57
+ if (activityLogs.length > 80) activityLogs.shift()
58
+ console.log(line)
59
+ }
60
+
61
+ function formatUptime() {
62
+ const totalSeconds = Math.floor((Date.now() - startTime) / 1000)
63
+ const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
64
+ const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0')
65
+ const seconds = String(totalSeconds % 60).padStart(2, '0')
66
+ return `${hours}:${minutes}:${seconds}`
67
+ }
68
+
69
+ // helper reaction loading (⏳ -> ✅ / ❌) biar gak spam bubble teks
70
+ async function reactMsg(sock, m, emoji) {
71
+ try {
72
+ await sock.sendMessage(m.key.remoteJid, {
73
+ react: { text: emoji, key: m.key }
74
+ })
75
+ } catch {}
76
+ }
77
+
78
+ function startDashboardServer() {
79
+ const server = http.createServer((req, res) => {
80
+ const urlPath = (req.url || '/').split('?')[0]
81
+
82
+ if (req.method === 'GET' && (urlPath === '/' || urlPath === '/dashboard')) {
83
+ if (fs.existsSync(DASHBOARD_HTML_FILE)) {
84
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
85
+ return fs.createReadStream(DASHBOARD_HTML_FILE).pipe(res)
86
+ }
87
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
88
+ return res.end('dashboard.html tidak ditemukan di folder bot.')
89
+ }
90
+
91
+ if (req.method === 'GET' && urlPath === '/api/state') {
92
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
93
+ return res.end(JSON.stringify({
94
+ connected: isConnected,
95
+ botNumber,
96
+ uptime: formatUptime(),
97
+ processedMessages,
98
+ config: botConfig,
99
+ logs: activityLogs
100
+ }))
101
+ }
102
+
103
+ if (req.method === 'POST' && urlPath === '/api/config') {
104
+ let body = ''
105
+ req.on('data', chunk => { body += chunk.toString() })
106
+ req.on('end', () => {
107
+ try {
108
+ const parsed = JSON.parse(body || '{}')
109
+ saveConfig({
110
+ packName: typeof parsed.packName === 'string' && parsed.packName.trim() ? parsed.packName.trim() : botConfig.packName,
111
+ authorName: typeof parsed.authorName === 'string' && parsed.authorName.trim() ? parsed.authorName.trim() : botConfig.authorName,
112
+ aiSessionActive: typeof parsed.aiSessionActive === 'boolean' ? parsed.aiSessionActive : botConfig.aiSessionActive,
113
+ antiSider: typeof parsed.antiSider === 'boolean' ? parsed.antiSider : botConfig.antiSider,
114
+ geminiApiKey: typeof parsed.geminiApiKey === 'string' ? parsed.geminiApiKey.trim() : botConfig.geminiApiKey,
115
+ removeBgApiKey: typeof parsed.removeBgApiKey === 'string' ? parsed.removeBgApiKey.trim() : botConfig.removeBgApiKey
116
+ })
117
+ pushLog(`Dashboard update config -> pack: "${botConfig.packName}", author: "${botConfig.authorName}"`)
118
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
119
+ res.end(JSON.stringify({ ok: true, config: botConfig }))
120
+ } catch {
121
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' })
122
+ res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
123
+ }
124
+ })
125
+ return
126
+ }
127
+
128
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
129
+ res.end('Not found')
130
+ })
131
+
132
+ server.listen(DASHBOARD_PORT, '0.0.0.0', () => {
133
+ pushLog(`Dashboard aktif di http://localhost:${DASHBOARD_PORT}`)
134
+ })
135
+ }
136
+
137
+ const question = (text) => {
138
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
139
+ return new Promise((resolve) => rl.question(text, (answer) => { rl.close(); resolve(answer) }))
140
+ }
141
+
142
+ // ==========================================
143
+ // HELPER SPEEDTEST JARINGAN PERANGKAT PENGGUNA 🔥
144
+ // ==========================================
145
+ async function runDeviceSpeedtest() {
146
+ let ispInfo = 'Tidak diketahui'
147
+ let ipMasked = '-'
148
+ try {
149
+ const meta = await axios.get('https://ipwho.is/', { timeout: 6000 })
150
+ if (meta.data?.success) {
151
+ ispInfo = `${meta.data.connection?.isp || meta.data.org || 'ISP'} (${meta.data.city || 'ID'})`
152
+ const ipParts = String(meta.data.ip || '').split('.')
153
+ ipMasked = ipParts.length === 4 ? `${ipParts[0]}.${ipParts[1]}.xxx.xxx` : (meta.data.ip || '-')
154
+ }
155
+ } catch {}
156
+
157
+ const pings = []
158
+ for (let i = 0; i < 3; i++) {
159
+ const t0 = performance.now()
160
+ await axios.get('https://speed.cloudflare.com/__down?bytes=0', { timeout: 8000 })
161
+ const t1 = performance.now()
162
+ pings.push(t1 - t0)
163
+ }
164
+ const avgPing = pings.reduce((a, b) => a + b, 0) / pings.length
165
+ const jitter = Math.max(...pings) - Math.min(...pings)
166
+
167
+ const dlBytes = 10 * 1024 * 1024
168
+ const dlStart = performance.now()
169
+ const dlRes = await axios.get(`https://speed.cloudflare.com/__down?bytes=${dlBytes}`, {
170
+ responseType: 'arraybuffer',
171
+ timeout: 25000
172
+ })
173
+ const dlDurationSec = (performance.now() - dlStart) / 1000
174
+ const actualDlBytes = dlRes.data?.byteLength || dlBytes
175
+ const dlMbps = ((actualDlBytes * 8) / dlDurationSec) / 1_000_000
176
+
177
+ const ulBytes = 3 * 1024 * 1024
178
+ const dummyPayload = Buffer.alloc(ulBytes, 0x61)
179
+ const ulStart = performance.now()
180
+ await axios.post('https://speed.cloudflare.com/__up', dummyPayload, {
181
+ headers: { 'Content-Type': 'application/octet-stream' },
182
+ maxBodyLength: Infinity,
183
+ timeout: 25000
184
+ })
185
+ const ulDurationSec = (performance.now() - ulStart) / 1000
186
+ const ulMbps = ((ulBytes * 8) / ulDurationSec) / 1_000_000
187
+
188
+ return {
189
+ isp: ispInfo,
190
+ ip: ipMasked,
191
+ pingMs: avgPing.toFixed(1),
192
+ jitterMs: jitter.toFixed(1),
193
+ downloadMbps: dlMbps.toFixed(2),
194
+ uploadMbps: ulMbps.toFixed(2)
195
+ }
196
+ }
197
+
198
+ // ==========================================
199
+ // HELPER STIKER STATIS & BERGERAK DIET KETAT (< 500KB) 🔥
200
+ // ==========================================
201
+ async function createWebpSticker(inputBufferOrUrl, packname = botConfig.packName, author = botConfig.authorName, isVideo = false) {
202
+ const id = Date.now() + '_' + Math.floor(Math.random() * 1000)
203
+ const extIn = isVideo ? 'mp4' : 'png'
204
+ const tmpIn = path.join('./', `in_${id}.${extIn}`)
205
+ const tmpOut = path.join('./', `out_${id}.webp`)
206
+
207
+ let mediaBuffer = inputBufferOrUrl
208
+ if (typeof inputBufferOrUrl === 'string' && inputBufferOrUrl.startsWith('http')) {
209
+ const res = await axios.get(inputBufferOrUrl, { responseType: 'arraybuffer' })
210
+ mediaBuffer = Buffer.from(res.data)
211
+ }
212
+
213
+ fs.writeFileSync(tmpIn, mediaBuffer)
214
+
215
+ await new Promise((resolve, reject) => {
216
+ const cmd = ffmpeg(tmpIn)
217
+ if (isVideo) {
218
+ cmd.outputOptions([
219
+ '-vcodec', 'libwebp',
220
+ '-vf', 'fps=10,scale=320:320:force_original_aspect_ratio=decrease,format=rgba,pad=320:320:(ow-iw)/2:(oh-ih)/2:color=#00000000',
221
+ '-loop', '0',
222
+ '-ss', '00:00:00',
223
+ '-t', '00:00:04',
224
+ '-q:v', '45',
225
+ '-compression_level', '6',
226
+ '-preset', 'picture',
227
+ '-an'
228
+ ])
229
+ } else {
230
+ cmd.outputOptions([
231
+ '-vcodec', 'libwebp',
232
+ '-vf', 'scale=512:512:force_original_aspect_ratio=decrease,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000',
233
+ '-lossless', '0',
234
+ '-q:v', '75',
235
+ '-preset', 'default',
236
+ '-an'
237
+ ])
238
+ }
239
+
240
+ cmd.toFormat('webp')
241
+ .save(tmpOut)
242
+ .on('end', resolve)
243
+ .on('error', reject)
244
+ })
245
+
246
+ const img = new webp.Image()
247
+ await img.load(tmpOut)
248
+ const json = {
249
+ 'sticker-pack-id': 'com.takeserver.bot',
250
+ 'sticker-pack-name': packname,
251
+ 'sticker-pack-publisher': author,
252
+ 'emojis': ['🗿']
253
+ }
254
+ const exifAttr = Buffer.from([0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00])
255
+ const jsonBuff = Buffer.from(JSON.stringify(json), 'utf-8')
256
+ const exif = Buffer.concat([exifAttr, jsonBuff])
257
+ exif.writeUIntLE(jsonBuff.length, 14, 4)
258
+ img.exif = exif
259
+
260
+ const finalBuffer = await img.save(null)
261
+
262
+ if (fs.existsSync(tmpIn)) fs.unlinkSync(tmpIn)
263
+ if (fs.existsSync(tmpOut)) fs.unlinkSync(tmpOut)
264
+
265
+ return finalBuffer
266
+ }
267
+
268
+ // ==========================================
269
+ // HELPER AUDIO OPUS 16KHZ & SOUND STICKER (WRITER FIELD 26) 🔥
270
+ // ==========================================
271
+ async function convertToOpusAudio(inputBufferOrUrl) {
272
+ const id = Date.now() + '_' + Math.floor(Math.random() * 1000)
273
+ const tmpIn = path.join('./', `aud_in_${id}`)
274
+ const tmpOut = path.join('./', `aud_out_${id}.ogg`)
275
+
276
+ let audBuffer = inputBufferOrUrl
277
+ if (typeof inputBufferOrUrl === 'string' && inputBufferOrUrl.startsWith('http')) {
278
+ const res = await axios.get(inputBufferOrUrl, { responseType: 'arraybuffer' })
279
+ audBuffer = Buffer.from(res.data)
280
+ }
281
+
282
+ fs.writeFileSync(tmpIn, audBuffer)
283
+
284
+ let durationSec = 3
285
+ await new Promise((resolve, reject) => {
286
+ ffmpeg(tmpIn)
287
+ .outputOptions([
288
+ '-c:a', 'libopus',
289
+ '-b:a', '24k',
290
+ '-ar', '16000',
291
+ '-ac', '1',
292
+ '-t', '00:00:10',
293
+ '-vn'
294
+ ])
295
+ .toFormat('ogg')
296
+ .on('codecData', (data) => {
297
+ if (data?.duration) {
298
+ const parts = data.duration.split(':')
299
+ if (parts.length === 3) {
300
+ const total = (+parts[0]) * 3600 + (+parts[1]) * 60 + parseFloat(parts[2])
301
+ if (!isNaN(total) && total > 0) {
302
+ durationSec = Math.min(10, Math.max(1, Math.round(total)))
303
+ }
304
+ }
305
+ }
306
+ })
307
+ .save(tmpOut)
308
+ .on('end', resolve)
309
+ .on('error', reject)
310
+ })
311
+
312
+ const finalAudio = fs.readFileSync(tmpOut)
313
+ if (fs.existsSync(tmpIn)) fs.unlinkSync(tmpIn)
314
+ if (fs.existsSync(tmpOut)) fs.unlinkSync(tmpOut)
315
+
316
+ return { buffer: finalAudio, seconds: durationSec }
317
+ }
318
+
319
+ async function sendHybridSoundSticker(sock, jid, stickerBuffer, opusData, isAnimated, quotedMsg) {
320
+ const opusBuffer = Buffer.isBuffer(opusData) ? opusData : opusData.buffer
321
+ const audioSeconds = opusData?.seconds || 3
322
+
323
+ try {
324
+ const stickerMedia = await prepareWAMessageMedia(
325
+ { sticker: stickerBuffer },
326
+ { upload: sock.waUploadToServer }
327
+ )
328
+ const audioMedia = await prepareWAMessageMedia(
329
+ { audio: opusBuffer, mimetype: 'audio/ogg; codecs=opus', ptt: false },
330
+ { upload: sock.waUploadToServer }
331
+ )
332
+
333
+ const audioObj = audioMedia.audioMessage
334
+ if (audioObj) {
335
+ audioObj.mimetype = 'audio/ogg; codecs=opus'
336
+ audioObj.seconds = audioSeconds
337
+ audioObj.ptt = false
338
+ }
339
+
340
+ const stickerMsgObj = stickerMedia.stickerMessage
341
+ stickerMsgObj.isAnimated = isAnimated
342
+
343
+ const waMsg = generateWAMessageFromContent(
344
+ jid,
345
+ proto.Message.fromObject({ stickerMessage: stickerMsgObj }),
346
+ { quoted: quotedMsg }
347
+ )
348
+
349
+ const targetStickerRef = waMsg.message.stickerMessage
350
+ const audioBytes = proto.Message.AudioMessage.encode(audioObj).finish()
351
+
352
+ const origStickerEncode = proto.Message.StickerMessage.encode
353
+ proto.Message.StickerMessage.encode = function (msg, writer) {
354
+ const w = origStickerEncode.call(this, msg, writer)
355
+ if (msg === targetStickerRef) {
356
+ w.uint32(210).bytes(audioBytes)
357
+ }
358
+ return w
359
+ }
360
+
361
+ try {
362
+ await sock.relayMessage(jid, waMsg.message, { messageId: waMsg.key.id })
363
+ } finally {
364
+ proto.Message.StickerMessage.encode = origStickerEncode
365
+ }
366
+
367
+ return 'native_writer_field_26_injected'
368
+ } catch (err) {
369
+ pushLog(`[hybrid fallback] error writer field 26: ${err.message}`)
370
+ await sock.sendMessage(jid, { sticker: stickerBuffer }, { quoted: quotedMsg })
371
+ await sock.sendMessage(jid, {
372
+ audio: opusBuffer,
373
+ mimetype: 'audio/ogg; codecs=opus',
374
+ ptt: true
375
+ })
376
+ return 'fallback_dual_bubble'
377
+ }
378
+ }
379
+
380
+ // ==========================================
381
+ // HELPER UNIVERSAL DOWNLOADER TAKESERVER API 🔥
382
+ // ==========================================
383
+ const fetchTakeServerMedia = async (platform, targetUrl) => {
384
+ const endpoint = `${DOWNLOADER_BASE_URL}/${platform}?url=${encodeURIComponent(targetUrl)}`
385
+ const { data } = await axios.get(endpoint, { timeout: 60000 })
386
+
387
+ const res = data?.result || data
388
+ const downloads = Array.isArray(res?.downloads) ? res.downloads : []
389
+
390
+ const picked = downloads[0] || {}
391
+ const mediaUrl = picked?.url || res?.url || res?.download_url || res?.video || res?.audio || data?.url || null
392
+ const title = res?.title || data?.title || ''
393
+ const author = res?.author?.username ? `@${res.author.username}` : (res?.author?.name || '')
394
+ const mediaType = (res?.type || picked?.type || '').toLowerCase()
395
+ const isAudio = platform === 'youtube/mp3' || mediaType === 'audio' || mediaType === 'mp3'
396
+
397
+ return { raw: data, mediaUrl, title, author, mediaType, isAudio, allDownloads: downloads }
398
+ }
399
+
400
+ async function connectToWhatsApp(savedPairingNumber = null) {
401
+ const { version } = await fetchLatestBaileysVersion()
402
+ const { state, saveCreds } = await useMultiFileAuthState('session_qr_stiker')
403
+
404
+ let usePairing = false
405
+ let cleanNomor = savedPairingNumber
406
+
407
+ if (!state.creds.registered && !cleanNomor) {
408
+ console.log('\n==============================================')
409
+ console.log('🔥 METODE LOGIN BOT WA - SEPUH DEV 2026 🔥')
410
+ console.log('1. Pake QR Code (Buka laptop lu nyet 😭)')
411
+ console.log('2. Pake Pairing Code (Kaum rebahan hp satu 🗿)')
412
+ console.log('==============================================\n')
413
+
414
+ const opsi = await question('pilih metode login (ketik 1 ato 2) bre: ')
415
+
416
+ if (opsi.trim() === '2') {
417
+ usePairing = true
418
+ const nomorBot = await question('\nmasukin nomor wa bot lu (wajib awalan 62, contoh: 628123456789): ')
419
+ cleanNomor = nomorBot.replace(/[^0-9]/g, '')
420
+ if (cleanNomor.startsWith('0')) {
421
+ cleanNomor = '62' + cleanNomor.slice(1)
422
+ }
423
+ } else {
424
+ console.log('\n[!] mode QR code aktif, meluncur gres... 🗿')
425
+ }
426
+ } else if (cleanNomor) {
427
+ usePairing = true
428
+ }
429
+
430
+ pushLog('mencoba ngebuka koneksi aman ke server wa...')
431
+ const sock = makeWASocket({
432
+ auth: state,
433
+ version: version,
434
+ browser: Browsers.ubuntu('Chrome'),
435
+ printQRInTerminal: false,
436
+ defaultQueryTimeoutMs: undefined,
437
+ syncFullHistory: false
438
+ })
439
+
440
+ let pairingRequested = false
441
+
442
+ sock.ev.on('connection.update', async (update) => {
443
+ const { connection, lastDisconnect, qr } = update
444
+
445
+ if (qr && !sock.authState.creds.registered) {
446
+ if (usePairing && cleanNomor && !pairingRequested) {
447
+ pairingRequested = true
448
+ try {
449
+ await new Promise((r) => setTimeout(r, 1500))
450
+ let code = await sock.requestPairingCode(cleanNomor)
451
+ code = code?.match(/.{1,4}/g)?.join('-') || code
452
+ console.log(`\n==============================================`)
453
+ console.log(`🔥 NIH KODE PAIRING LU (${cleanNomor}), BURUAN MASUKIN KE WA:`)
454
+ console.log(`👉 ${code}`)
455
+ console.log(`==============================================\n`)
456
+ } catch (err) {
457
+ pairingRequested = false
458
+ pushLog(`gagal minta kode pairing bre: ${err.message}`)
459
+ }
460
+ } else if (!usePairing) {
461
+ console.log('\nWOI SCAN QR INI BRE: 🗿')
462
+ qrcodeTerminal.generate(qr, { small: true })
463
+ }
464
+ }
465
+
466
+ if (connection === 'close') {
467
+ isConnected = false
468
+ const statusCode = lastDisconnect?.error?.output?.statusCode
469
+ if (statusCode !== DisconnectReason.loggedOut) {
470
+ setTimeout(() => { connectToWhatsApp(usePairing ? cleanNomor : null) }, 5000)
471
+ } else {
472
+ pushLog('sesi logout bre! hapus folder session_qr_stiker terus jalanin ulang.')
473
+ }
474
+ } else if (connection === 'open') {
475
+ isConnected = true
476
+ botNumber = sock.user?.id?.split(':')[0] || '-'
477
+ pushLog(`Bot terhubung (${botNumber}) • Dashboard siap di http://localhost:${DASHBOARD_PORT}`)
478
+ }
479
+ })
480
+
481
+ // ==========================================
482
+ // ANTI SIDER GRUP (SUPPORT MULTI-RECEIPT & LID 2026) 🔥
483
+ // ==========================================
484
+ const siderCooldown = new Map()
485
+ const groupLidCache = new Map()
486
+
487
+ async function resolveParticipantJid(groupJid, rawJid) {
488
+ if (!rawJid) return null
489
+ const cleanJid = rawJid.replace(/:\d+@/, '@')
490
+ if (!cleanJid.endsWith('@lid')) return cleanJid
491
+
492
+ try {
493
+ let lidMap = groupLidCache.get(groupJid)
494
+ if (!lidMap) {
495
+ const meta = await sock.groupMetadata(groupJid)
496
+ lidMap = new Map()
497
+ for (const p of meta.participants || []) {
498
+ if (p.lid && p.id) {
499
+ lidMap.set(p.lid.replace(/:\d+@/, '@'), p.id.replace(/:\d+@/, '@'))
500
+ }
501
+ }
502
+ groupLidCache.set(groupJid, lidMap)
503
+ }
504
+ return lidMap.get(cleanJid) || cleanJid
505
+ } catch {
506
+ return cleanJid
507
+ }
508
+ }
509
+
510
+ async function handleGroupReceipt(groupJid, receiptList) {
511
+ if (!botConfig.antiSider) return
512
+ if (!groupJid || !groupJid.endsWith('@g.us')) return
513
+ if (!Array.isArray(receiptList) || receiptList.length === 0) return
514
+
515
+ const myNum = sock.user?.id?.split(':')[0]?.split('@')[0]
516
+ const myLid = sock.user?.lid?.split(':')[0]?.split('@')[0]
517
+
518
+ for (const r of receiptList) {
519
+ if (!r?.readTimestamp) continue
520
+
521
+ const rawReader = r.userJid || r.participant || r.jid
522
+ if (!rawReader) continue
523
+
524
+ const resolvedJid = await resolveParticipantJid(groupJid, rawReader)
525
+ if (!resolvedJid) continue
526
+
527
+ const readerNum = resolvedJid.split('@')[0].split(':')[0]
528
+ if (readerNum === myNum || readerNum === myLid) continue
529
+
530
+ const cdKey = `${groupJid}_${readerNum}`
531
+ const now = Date.now()
532
+ if (siderCooldown.has(cdKey) && now - siderCooldown.get(cdKey) < 60000) continue
533
+ siderCooldown.set(cdKey, now)
534
+
535
+ pushLog(`[Anti-Sider] Terciduk baca chat di grup: ${readerNum}`)
536
+
537
+ const kataSindiran = [
538
+ `woi @${readerNum} terciduk lu cuma nyimak doang, ketik kek minimal p gitu biar kaga sider amat cok 😭🗿`,
539
+ `eh ada hantu grup @${readerNum} aktif nih, nongol lu bre jangan jadi sider mulu elah 🥲`,
540
+ `baca doang chatnya @${readerNum}? ngetik kagak sider iya wkwkwk absurd lu cok 😭`,
541
+ `terdeteksi sider premium: @${readerNum} bilek cuma numpang lewat doang kagak asik lu wak 🗿`
542
+ ]
543
+ const teksRandom = kataSindiran[Math.floor(Math.random() * kataSindiran.length)]
544
+
545
+ try {
546
+ await sock.sendMessage(groupJid, { text: teksRandom, mentions: [resolvedJid] })
547
+ } catch (err) {
548
+ pushLog(`gagal ngirim sindiran anti sider: ${err.message}`)
549
+ }
550
+ }
551
+ }
552
+
553
+ sock.ev.on('message-receipt.update', async (events) => {
554
+ if (!Array.isArray(events)) return
555
+ for (const ev of events) {
556
+ await handleGroupReceipt(ev?.key?.remoteJid, ev?.receipts || ev?.userReceipt)
557
+ }
558
+ })
559
+
560
+ sock.ev.on('messages.update', async (updates) => {
561
+ if (!Array.isArray(updates)) return
562
+ for (const up of updates) {
563
+ if (up?.userReceipt) {
564
+ await handleGroupReceipt(up?.key?.remoteJid, up.userReceipt)
565
+ }
566
+ }
567
+ })
568
+
569
+ sock.ev.removeAllListeners('messages.upsert')
570
+
571
+ sock.ev.on('messages.upsert', async (event) => {
572
+ try {
573
+ if (!event.messages || event.messages.length === 0) return
574
+ const m = event.messages[0]
575
+ if (!m?.message) return
576
+ if (!m.key?.fromMe) return
577
+
578
+ processedMessages += 1
579
+ const msg = m.message
580
+ const quotedMsg = msg.extendedTextMessage?.contextInfo?.quotedMessage || null
581
+
582
+ const messageText = msg.conversation || msg.extendedTextMessage?.text || msg.imageMessage?.caption || msg.videoMessage?.caption || ''
583
+ const command = messageText.split(' ')[0].toLowerCase()
584
+ const args = messageText.split(' ').slice(1).join(' ')
585
+
586
+ const directImage = msg.imageMessage || null
587
+ const quotedImage = quotedMsg?.imageMessage || null
588
+ const directVideo = msg.videoMessage || null
589
+ const quotedVideo = quotedMsg?.videoMessage || null
590
+ const quotedAudio = quotedMsg?.audioMessage || null
591
+
592
+ if (command === 'p' || command === 'ping') {
593
+ return await sock.sendMessage(m.key.remoteJid, { text: 'pong! ngerespon aman jaya bre 🗿' })
594
+ }
595
+
596
+ if (command === '.menu' || command === '.help') {
597
+ const localeDate = new Date().toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })
598
+ const localeTime = new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\./g, ':')
599
+
600
+ const menuText = `◦ *Library:* Baileys V ${version}
601
+
602
+ ◦ Uptime : ${formatUptime()}
603
+ ◦ Tanggal : ${localeDate}
604
+ ◦ Waktu : ${localeTime}
605
+ ◦ Dashboard : http://localhost:${DASHBOARD_PORT}
606
+
607
+ ◦ *MAIN & STICKER MENU*
608
+ ◦ .menu
609
+ ◦ .ping / p
610
+ ◦ .speedtest / .speed
611
+ ◦ .stiker (reply foto / video gif)
612
+ ◦ .saudio <teks/link> (reply foto / video)
613
+ ◦ .brat <teks + emoji>
614
+ ◦ .smeme <atas|bawah> (reply foto)
615
+
616
+ ◦ *📥 TAKESERVER UNIFIED DOWNLOADER*
617
+ ◦ .tiktok / .tikdl <link>
618
+ ◦ .instagram / .ig <link>
619
+ ◦ .youtube / .yt <link>
620
+ ◦ .ytmp3 / .yta <link>
621
+
622
+ ◦ *🛠️ TOOLS MENU (INTEGRATED ENGINE)*
623
+ ◦ /aistart (Nyalain Engine Web AI)
624
+ ◦ /aiend (Matiin Engine Web AI)
625
+ ◦ .qr / .qrcode <teks>
626
+ ◦ .kalkulator <soal>
627
+ ◦ .removebg / .nobg (reply foto)
628
+
629
+ ◦ *System Inject:* Anti-Sider Grup [${botConfig.antiSider ? 'ACTIVE' : 'OFF'}]
630
+
631
+ _© 2026 sepuh dev - powered by takeserver api_`
632
+
633
+ return await sock.sendMessage(m.key.remoteJid, { text: menuText })
634
+ }
635
+
636
+ if (command === '/aistart') {
637
+ saveConfig({ aiSessionActive: true })
638
+ pushLog('AI Session diaktifkan lewat /aistart')
639
+ await reactMsg(sock, m, '✅')
640
+ return await sock.sendMessage(m.key.remoteJid, {
641
+ text: `*SYSTEM INTEGRATION INJECTED* 😭🔥\n\nstatus: *online*\nengine: *gemini-3.1-flash-lite server script*\nbilek: halo bre, gua udah standby! tanya apa aja bebas pake huruf kecil gres! 🗿`
642
+ })
643
+ }
644
+
645
+ if (command === '/aiend') {
646
+ saveConfig({ aiSessionActive: false })
647
+ pushLog('AI Session dimatikan lewat /aiend')
648
+ await reactMsg(sock, m, '✅')
649
+ return await sock.sendMessage(m.key.remoteJid, {
650
+ text: `*SYSTEM INTEGRATION SUSPENDED* 🙃\n\nstatus: *offline*\nengine: *all_sessions storage locked*\npesan: obrolan berhasil ditutup gres! 🥲`
651
+ })
652
+ }
653
+
654
+ // ==========================================
655
+ // SPEEDTEST JARINGAN PERANGKAT PENGGUNA (.speedtest) 🔥
656
+ // ==========================================
657
+ if (command === '.speedtest' || command === '.speed') {
658
+ pushLog('Menjalankan speedtest koneksi perangkat pengguna...')
659
+ await reactMsg(sock, m, '⏳')
660
+
661
+ try {
662
+ const st = await runDeviceSpeedtest()
663
+ const teksSpeed = `*⚡ DEVICE NETWORK SPEEDTEST ⚡*
664
+
665
+ 📡 *ISP / Jaringan:* ${st.isp}
666
+ 🌐 *IP Publik:* ${st.ip}
667
+
668
+ 📶 *Ping (Latency):* *${st.pingMs} ms*
669
+ 〰️ *Jitter:* *${st.jitterMs} ms*
670
+ ⬇️ *Download:* *${st.downloadMbps} Mbps*
671
+ ⬆️ *Upload:* *${st.uploadMbps} Mbps*
672
+
673
+ _diukur langsung dari koneksi perangkat pengguna • cloudflare edge_`
674
+ pushLog(`Speedtest selesai: DL ${st.downloadMbps} Mbps | UL ${st.uploadMbps} Mbps | Ping ${st.pingMs} ms`)
675
+ await reactMsg(sock, m, '✅')
676
+ return await sock.sendMessage(m.key.remoteJid, { text: teksSpeed })
677
+ } catch (err) {
678
+ pushLog(`error speedtest: ${err.message}`)
679
+ await reactMsg(sock, m, '❌')
680
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal ngetes speed koneksi perangkat lu bre, cek sinyal atau coba lagi! 🥲' })
681
+ }
682
+ }
683
+
684
+ // ==========================================
685
+ // UNIFIED DOWNLOADER (TIKTOK, IG, YT, YTMP3) 🔥
686
+ // ==========================================
687
+ const downloaderMap = {
688
+ '.tt': 'tiktok',
689
+ '.tiktok': 'tiktok',
690
+ '.tikdl': 'tiktok',
691
+ '.ig': 'instagram',
692
+ '.instagram': 'instagram',
693
+ '.yt': 'youtube',
694
+ '.youtube': 'youtube',
695
+ '.ytmp4': 'youtube',
696
+ '.ytmp3': 'youtube/mp3',
697
+ '.yta': 'youtube/mp3'
698
+ }
699
+
700
+ if (downloaderMap[command]) {
701
+ if (!args) return await sock.sendMessage(m.key.remoteJid, { text: 'link-nya mana cok? 😭' })
702
+ const platform = downloaderMap[command]
703
+ pushLog(`Downloader ${platform} -> ${args.trim()}`)
704
+ await reactMsg(sock, m, '⏳')
705
+
706
+ try {
707
+ const { mediaUrl, title, author, mediaType, isAudio } = await fetchTakeServerMedia(platform, args.trim())
708
+
709
+ if (!mediaUrl) {
710
+ await reactMsg(sock, m, '❌')
711
+ return await sock.sendMessage(m.key.remoteJid, { text: `api *${platform}* ngerespon tapi link medianya kosong cok! 🥲` })
712
+ }
713
+
714
+ if (isAudio) {
715
+ await sock.sendMessage(m.key.remoteJid, {
716
+ audio: { url: mediaUrl },
717
+ mimetype: 'audio/mp4',
718
+ ptt: false
719
+ })
720
+ return await reactMsg(sock, m, '✅')
721
+ }
722
+
723
+ const isImage = mediaType === 'image' || mediaType === 'photo' || /\.(jpg|jpeg|png|webp)(\?|$)/i.test(mediaUrl)
724
+ const infoHeader = [title, author ? `👤 ${author}` : ''].filter(Boolean).join('\n')
725
+ const captionText = infoHeader ? `${infoHeader}\n\n*${platform.toUpperCase()} DOWNLOAD SUCCESS* 😭🔥` : `*${platform.toUpperCase()} DOWNLOAD SUCCESS* 😭🔥`
726
+
727
+ if (isImage) {
728
+ await sock.sendMessage(m.key.remoteJid, { image: { url: mediaUrl }, caption: captionText })
729
+ } else {
730
+ await sock.sendMessage(m.key.remoteJid, { video: { url: mediaUrl }, caption: captionText })
731
+ }
732
+ return await reactMsg(sock, m, '✅')
733
+ } catch (e) {
734
+ pushLog(`error downloader [${platform}]: ${e.message}`)
735
+ await reactMsg(sock, m, '❌')
736
+ return await sock.sendMessage(m.key.remoteJid, { text: `gagal nembak api *${platform}* takeserver bre, cek server atau link-nya valid kagak! 🥲` })
737
+ }
738
+ }
739
+
740
+ // ==========================================
741
+ // TOOLS MENU (.qr, .kalkulator, .removebg)
742
+ // ==========================================
743
+ if (command === '.qr' || command === '.qrcode') {
744
+ if (!args) return await sock.sendMessage(m.key.remoteJid, { text: 'teksnya mana cok?' })
745
+ await reactMsg(sock, m, '⏳')
746
+ try {
747
+ const qrBuffer = await QRCode.toBuffer(args, { type: 'png', width: 512 })
748
+ await sock.sendMessage(m.key.remoteJid, { image: qrBuffer, caption: `*QR CODE SUCCESS* 😭🔥\n\n📝 *Text:* ${args}` })
749
+ return await reactMsg(sock, m, '✅')
750
+ } catch {
751
+ await reactMsg(sock, m, '❌')
752
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal generate qrcode bre 🥲' })
753
+ }
754
+ }
755
+
756
+ if (command === '.kalkulator' || command === '.hitung') {
757
+ if (!args) return await sock.sendMessage(m.key.remoteJid, { text: 'soalnya mana cok?' })
758
+ try {
759
+ const sanitizeInput = args.replace(/[^0-9+\-*/().]/g, '')
760
+ const result = new Function(`return ${sanitizeInput}`)()
761
+ return await sock.sendMessage(m.key.remoteJid, { text: `*⚡ KALKULATOR SEPUH ⚡*\n\n📝 *Soal:* ${args}\n✅ *Hasil:* *${result}*\n\n_© sepuh bot_` })
762
+ } catch { return await sock.sendMessage(m.key.remoteJid, { text: 'gagal hitung, format lu salah cok! 🥲' }) }
763
+ }
764
+
765
+ if (command === '.removebg' || command === '.nobg') {
766
+ if (!botConfig.removeBgApiKey || botConfig.removeBgApiKey === 'API_KEY_REMOVEBG_LU_DISINI') {
767
+ return await sock.sendMessage(m.key.remoteJid, { text: 'woi API Key Removebg belum lu pasang di dashboard port 3007! 😭' })
768
+ }
769
+ const imageMessage = directImage || quotedImage
770
+ if (!imageMessage) return await sock.sendMessage(m.key.remoteJid, { text: 'reply fotonya mana cok? 😭' })
771
+ await reactMsg(sock, m, '⏳')
772
+ try {
773
+ const stream = await downloadContentFromMessage(imageMessage, 'image')
774
+ let buffer = Buffer.from([])
775
+ for await (const chunk of stream) { buffer = Buffer.concat([buffer, chunk]) }
776
+
777
+ const response = await axios.post(
778
+ 'https://api.remove.bg/v1.0/removebg',
779
+ { image_file_b64: buffer.toString('base64'), size: 'auto' },
780
+ {
781
+ headers: {
782
+ 'X-Api-Key': botConfig.removeBgApiKey,
783
+ 'Content-Type': 'application/json'
784
+ },
785
+ responseType: 'arraybuffer'
786
+ }
787
+ )
788
+ await sock.sendMessage(m.key.remoteJid, { image: Buffer.from(response.data), caption: `*REMOVE BACKGROUND SUKSES* 😭🔥` })
789
+ return await reactMsg(sock, m, '✅')
790
+ } catch (err) {
791
+ pushLog(`error removebg: ${err.message}`)
792
+ await reactMsg(sock, m, '❌')
793
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal remove background api limit atau key salah bre! 🥲' })
794
+ }
795
+ }
796
+
797
+ // ==========================================
798
+ // HYBRID SOUND STICKER: FOTO & VIDEO BERGERAK + AUDIO (.saudio) 🔥
799
+ // ==========================================
800
+ if (command === '.saudio' || command === '.stikeraudio') {
801
+ const targetImage = directImage || quotedImage
802
+ const targetVideo = directVideo || quotedVideo
803
+
804
+ if (!targetImage && !targetVideo) {
805
+ return await sock.sendMessage(m.key.remoteJid, { text: 'reply foto atau video-nya dulu cok! 😭' })
806
+ }
807
+ if (targetImage && !args && !quotedAudio) {
808
+ return await sock.sendMessage(m.key.remoteJid, { text: 'kalo foto kasih teks TTS atau link mp3 bre! contoh: .saudio anjay mabar' })
809
+ }
810
+
811
+ pushLog(`Render Sound Sticker (${targetVideo ? 'video' : 'foto'}) • pack="${botConfig.packName}" author="${botConfig.authorName}"`)
812
+ await reactMsg(sock, m, '⏳')
813
+
814
+ try {
815
+ const isVideo = Boolean(targetVideo)
816
+ const mediaMsg = isVideo ? targetVideo : targetImage
817
+ const stream = await downloadContentFromMessage(mediaMsg, isVideo ? 'video' : 'image')
818
+
819
+ let mediaBuffer = Buffer.from([])
820
+ for await (const chunk of stream) { mediaBuffer = Buffer.concat([mediaBuffer, chunk]) }
821
+
822
+ const stickerBuffer = await createWebpSticker(mediaBuffer, botConfig.packName, botConfig.authorName, isVideo)
823
+
824
+ let audioInput
825
+ if (args && args.trim().startsWith('http')) {
826
+ audioInput = args.trim()
827
+ } else if (args && args.trim().length > 0) {
828
+ audioInput = `https://translate.google.com/translate_tts?ie=UTF-8&q=${encodeURIComponent(args.trim())}&tl=id&client=tw-ob`
829
+ } else if (isVideo) {
830
+ audioInput = mediaBuffer
831
+ }
832
+
833
+ const opusData = await convertToOpusAudio(audioInput)
834
+ const modeDipakai = await sendHybridSoundSticker(sock, m.key.remoteJid, stickerBuffer, opusData, isVideo, m)
835
+ pushLog(`Sound sticker terkirim via ${modeDipakai}`)
836
+ await reactMsg(sock, m, '✅')
837
+ } catch (err) {
838
+ pushLog(`error hybrid sound sticker: ${err.message}`)
839
+ await reactMsg(sock, m, '❌')
840
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal ngeracik sound sticker bre, pastiin video ada suaranya atau ffmpeg libopus aman! 🥲' })
841
+ }
842
+ return
843
+ }
844
+
845
+ // ==========================================
846
+ // STIKER FOTO, VIDEO BERGERAK (.stiker), & MEME (.smeme) 🔥
847
+ // ==========================================
848
+ const isStickerCmd = command === '.stiker' || command === '.sticker' || command === '.smeme'
849
+
850
+ if (isStickerCmd || (directImage && !messageText)) {
851
+ const targetImage = directImage || quotedImage
852
+ const targetVideo = directVideo || quotedVideo
853
+
854
+ if (!targetImage && !targetVideo) {
855
+ return await sock.sendMessage(m.key.remoteJid, { text: 'kirim atau reply foto/video-nya mana cok? 😭' })
856
+ }
857
+
858
+ if (command === '.smeme' && targetVideo) {
859
+ return await sock.sendMessage(m.key.remoteJid, { text: '.smeme cuma buat foto bre, bukan video! 😭' })
860
+ }
861
+
862
+ try {
863
+ const isVideo = Boolean(targetVideo)
864
+ await reactMsg(sock, m, '⏳')
865
+
866
+ const mediaMsg = isVideo ? targetVideo : targetImage
867
+ const stream = await downloadContentFromMessage(mediaMsg, isVideo ? 'video' : 'image')
868
+ let buffer = Buffer.from([])
869
+ for await (const chunk of stream) { buffer = Buffer.concat([buffer, chunk]) }
870
+
871
+ if (command === '.smeme') {
872
+ if (!args) {
873
+ await reactMsg(sock, m, '❌')
874
+ return await sock.sendMessage(m.key.remoteJid, { text: 'kasih teks atas|bawah cok!' })
875
+ }
876
+ const [top, bottom] = args.split('|')
877
+ const topText = top ? encodeURIComponent(top.trim().replace(/\s+/g, '_')) : '_'
878
+ const bottomText = bottom ? encodeURIComponent(bottom.trim().replace(/\s+/g, '_')) : '_'
879
+
880
+ const formData = new FormData()
881
+ formData.append('image', buffer.toString('base64'))
882
+ const uploadImg = await fetch('https://api.imgbb.com/1/upload?key=d0cdb267fc3579d5790a468e3f0b8929', { method: 'POST', body: formData })
883
+ const resJson = await uploadImg.json()
884
+ buffer = `https://api.memegen.link/images/custom/${topText}/${bottomText}.png?background=${resJson.data.url}`
885
+ }
886
+
887
+ const stickerBuffer = await createWebpSticker(buffer, botConfig.packName, botConfig.authorName, isVideo)
888
+ await sock.sendMessage(m.key.remoteJid, { sticker: stickerBuffer })
889
+ return await reactMsg(sock, m, '✅')
890
+ } catch (err) {
891
+ pushLog(`error render stiker: ${err.message}`)
892
+ await reactMsg(sock, m, '❌')
893
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal render stiker cok 🥲' })
894
+ }
895
+ }
896
+
897
+ // ==========================================
898
+ // BRAT STRETCH HORIZONTAL + INLINE APPLE/TWEMOJI COLOR EMOJI 🔥
899
+ // ==========================================
900
+ if (command === '.brat') {
901
+ if (!args) return await sock.sendMessage(m.key.remoteJid, { text: 'teksnya mana cok? contoh: .brat tulus 😭🗿' })
902
+ await reactMsg(sock, m, '⏳')
903
+
904
+ try {
905
+ const font = await Jimp.loadFont(Jimp.FONT_SANS_64_BLACK)
906
+ const emojiRegex = /(\p{Extended_Pictographic}(?:\uFE0F|\u200D\p{Extended_Pictographic})*)/gu
907
+
908
+ const emojiToCodepoint = (emojiStr) => {
909
+ return [...emojiStr]
910
+ .map(c => c.codePointAt(0).toString(16))
911
+ .filter(hex => hex !== 'fe0f')
912
+ .join('-')
913
+ }
914
+
915
+ const rawTokens = args.split(emojiRegex).filter(Boolean)
916
+ const tokens = []
917
+ for (const part of rawTokens) {
918
+ if (emojiRegex.test(part)) {
919
+ emojiRegex.lastIndex = 0
920
+ tokens.push({ type: 'emoji', value: part })
921
+ } else {
922
+ emojiRegex.lastIndex = 0
923
+ const words = part.split(/(\s+)/).filter(w => w.length > 0)
924
+ for (const w of words) {
925
+ tokens.push({ type: 'text', value: w })
926
+ }
927
+ }
928
+ }
929
+
930
+ const maxWidth = 492
931
+ const lineHeight = 74
932
+ const emojiSize = 58
933
+ let cursorX = 10
934
+ let cursorY = 10
935
+ const drawQueue = []
936
+
937
+ for (const tok of tokens) {
938
+ if (tok.type === 'text') {
939
+ if (/^\s+$/.test(tok.value)) {
940
+ if (cursorX > 10) cursorX += 18
941
+ continue
942
+ }
943
+ const w = Jimp.measureText(font, tok.value)
944
+ if (cursorX + w > maxWidth && cursorX > 10) {
945
+ cursorX = 10
946
+ cursorY += lineHeight
947
+ }
948
+ drawQueue.push({ type: 'text', value: tok.value, x: cursorX, y: cursorY })
949
+ cursorX += w + 12
950
+ } else {
951
+ if (cursorX + emojiSize > maxWidth && cursorX > 10) {
952
+ cursorX = 10
953
+ cursorY += lineHeight
954
+ }
955
+ drawQueue.push({ type: 'emoji', value: tok.value, x: cursorX, y: cursorY + 4 })
956
+ cursorX += emojiSize + 10
957
+ }
958
+ }
959
+
960
+ const canvasHeight = Math.max(240, cursorY + lineHeight + 25)
961
+ const tempCanvas = new Jimp(512, canvasHeight, 0xFFFFFFFF)
962
+
963
+ for (const item of drawQueue) {
964
+ if (item.type === 'text') {
965
+ tempCanvas.print(font, item.x, item.y, item.value)
966
+ } else {
967
+ let emojiImg = null
968
+ try {
969
+ const appleUrl = `https://emojicdn.elk.sh/${encodeURIComponent(item.value)}?style=apple`
970
+ const res = await axios.get(appleUrl, { responseType: 'arraybuffer', timeout: 4500 })
971
+ emojiImg = await Jimp.read(Buffer.from(res.data))
972
+ } catch {
973
+ try {
974
+ const code = emojiToCodepoint(item.value)
975
+ const twemojiUrl = `https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/${code}.png`
976
+ const res2 = await axios.get(twemojiUrl, { responseType: 'arraybuffer', timeout: 4500 })
977
+ emojiImg = await Jimp.read(Buffer.from(res2.data))
978
+ } catch {}
979
+ }
980
+ if (emojiImg) {
981
+ emojiImg.resize(emojiSize, emojiSize)
982
+ tempCanvas.composite(emojiImg, item.x, item.y)
983
+ }
984
+ }
985
+ }
986
+
987
+ tempCanvas.resize(512, 512, Jimp.RESIZE_BEZIER)
988
+ tempCanvas.blur(1)
989
+
990
+ const bratBuffer = await tempCanvas.getBufferAsync(Jimp.MIME_PNG)
991
+ const stickerBuffer = await createWebpSticker(bratBuffer, botConfig.packName, botConfig.authorName, false)
992
+ await sock.sendMessage(m.key.remoteJid, { sticker: stickerBuffer })
993
+ return await reactMsg(sock, m, '✅')
994
+ } catch (err) {
995
+ pushLog(`error render brat: ${err.message}`)
996
+ await reactMsg(sock, m, '❌')
997
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal render brat emoji bre 🥲' })
998
+ }
999
+ }
1000
+
1001
+ // ==========================================
1002
+ // ENGINE LIVE AI CHAT INJECTOR
1003
+ // ==========================================
1004
+ if (botConfig.aiSessionActive && !command.startsWith('.')) {
1005
+ if (!botConfig.geminiApiKey || botConfig.geminiApiKey === 'API_KEY_GEMINI_LU_DISINI') {
1006
+ return await sock.sendMessage(m.key.remoteJid, { text: 'woi API KEY GEMINI belum lu pasang di dashboard port 3007! 😭' })
1007
+ }
1008
+
1009
+ await reactMsg(sock, m, '⏳')
1010
+ try {
1011
+ const promptUser = messageText
1012
+ const urlGemini = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-lite:generateContent?key=${botConfig.geminiApiKey}`
1013
+
1014
+ const response = await axios.post(urlGemini, {
1015
+ contents: [{ role: 'user', parts: [{ text: promptUser }] }],
1016
+ systemInstruction: {
1017
+ parts: [{
1018
+ text: `lu adalah asisten AI pribadi berwujud gen z tiktok Indonesia asli yang absurd dan super santai. Aturan wajib dan mutlak:
1019
+ 1. dilarang keras menyuruh user kirim gambar. jawab aja langsung.
1020
+ 2. wajib menggunakan huruf kecil semua tanpa ada huruf kapital sedikit pun, kecuali pas kaget (kapital semua hanya pas kaget).
1021
+ 3. pake bahasa gaul internet abis: gak, nambahin, lu, gua, ngakak, cok, coy, bre, woi, wak, bilek, p.
1022
+ 4. aturan emoji: 🗿 buat datar/netral, 😭 buat lucu/bingung (jangan pake 😂), 🙂/🙃/🥲 buat sedih/ngenes.
1023
+ 5. kalau pr/soal beri jawaban super pendek ringkas. kalau obrolan biasa beri respon panjang seru layaknya sahabat dekat.`
1024
+ }]
1025
+ }
1026
+ }, { headers: { 'Content-Type': 'application/json' } })
1027
+
1028
+ const hasilBalesan = response.data?.candidates?.[0]?.content?.parts?.[0]?.text || 'aduh blank otaknya bre, coba lagi... 😭'
1029
+ await reactMsg(sock, m, '✅')
1030
+ return await sock.sendMessage(m.key.remoteJid, { text: hasilBalesan })
1031
+ } catch (err) {
1032
+ pushLog(`error gemini ai: ${err.message}`)
1033
+ await reactMsg(sock, m, '❌')
1034
+ return await sock.sendMessage(m.key.remoteJid, { text: 'gagal nembak api gemini, cek koneksi atau key-nya bre! 🥲' })
1035
+ }
1036
+ }
1037
+ } catch (globalErr) {
1038
+ pushLog(`error handler pesan: ${globalErr.message}`)
1039
+ }
1040
+ })
1041
+
1042
+ sock.ev.on('creds.update', saveCreds)
1043
+ }
1044
+
1045
+ startDashboardServer()
1046
+ connectToWhatsApp()