astrabail 1.1.3 → 1.1.5

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.
package/readme.md CHANGED
@@ -1957,3 +1957,660 @@ await sock.sendMessage(jid, {
1957
1957
  ```
1958
1958
 
1959
1959
  `cover` dan setiap item `sticker` menerima format media yang sama seperti pengiriman media biasa: path lokal, URL, Buffer, atau stream.
1960
+
1961
+ ---
1962
+
1963
+ <div align="center">
1964
+
1965
+ ## 🛡️ Panduan Stabilitas & Pencegahan Bot Freeze
1966
+
1967
+ <sub>Bagian ini menjelaskan penyebab umum bot hang/freeze dan cara mencegahnya secara profesional.</sub>
1968
+
1969
+ </div>
1970
+
1971
+ ---
1972
+
1973
+ ## ⚠️ PERINGATAN PENTING: Bot Bisa Hang/Freeze Saat Ada User Join/Leave Grup
1974
+
1975
+ > [!CAUTION]
1976
+ > **Ini adalah kesalahan paling umum** yang dilakukan developer bot WhatsApp. Jika kamu mengirim pesan langsung (`await sendMessage(...)`) di dalam event `group-participants.update` **tanpa delay**, botmu akan **hang (macet) dan tidak bisa memproses command apapun** selama beberapa menit.
1977
+
1978
+ ### ❓ Mengapa Bisa Terjadi?
1979
+
1980
+ Ketika ada user baru **join** ke grup, WhatsApp membutuhkan waktu untuk:
1981
+
1982
+ 1. **Menyinkronkan Sender Key** — Kunci enkripsi baru harus dinegosiasikan antara bot dan member baru
1983
+ 2. **Memperbarui Session Signal** — Library perlu update session internal untuk anggota baru
1984
+ 3. **Fetch data server** — WhatsApp server membutuhkan sedikit waktu untuk menyebarkan informasi member baru
1985
+
1986
+ Jika kamu langsung memanggil `sendMessage` pada saat yang sama dengan proses di atas, bot akan **"menunggu"** respons server yang belum siap — menyebabkan seluruh event loop Node.js **tersumbat (blocked)**.
1987
+
1988
+ ### 📊 Ilustrasi Masalah
1989
+
1990
+ ```
1991
+ [User Join Grup]
1992
+ ↓
1993
+ [group-participants.update fired]
1994
+ ↓
1995
+ [Bot langsung await sendMessage()] ← ❌ MASALAH ADA DI SINI
1996
+ ↓
1997
+ [Baileys menunggu Sender Key dari server...]
1998
+ ↓
1999
+ [Event loop TERSUMBAT 30-60 detik]
2000
+ ↓
2001
+ [Semua command lain DIABAIKAN selama menunggu]
2002
+ ```
2003
+
2004
+ ### ✅ Solusi yang Benar
2005
+
2006
+ **Selalu gunakan `setTimeout` dengan delay minimal 3-5 detik** sebelum mengirim pesan welcome/leave di dalam event `group-participants.update`:
2007
+
2008
+ ```javascript
2009
+ // ❌ CARA SALAH — Bot akan hang!
2010
+ sock.ev.on('group-participants.update', async ({ id, participants, action }) => {
2011
+ if (action === 'add') {
2012
+ await sock.sendMessage(id, { text: 'Selamat datang!' }) // ← JANGAN LAKUKAN INI
2013
+ }
2014
+ })
2015
+
2016
+ // ✅ CARA BENAR — Bot tetap responsif!
2017
+ sock.ev.on('group-participants.update', async ({ id, participants, action }) => {
2018
+ // Selesaikan event handler ini secepat mungkin (non-blocking)
2019
+ // Kirim pesan welcome di background setelah 5 detik
2020
+ setTimeout(async () => {
2021
+ try {
2022
+ if (action === 'add') {
2023
+ for (const participant of participants) {
2024
+ await sock.sendMessage(id, {
2025
+ text: `Selamat datang @${participant.id.split('@')[0]}!`,
2026
+ mentions: [participant.id]
2027
+ })
2028
+ }
2029
+ }
2030
+ } catch (e) {
2031
+ console.error('Welcome message error:', e.message)
2032
+ }
2033
+ }, 5000) // ← Delay 5 detik agar Baileys selesai negosiasi kunci enkripsi
2034
+ })
2035
+ ```
2036
+
2037
+ > [!TIP]
2038
+ > **Kenapa 5 detik?** Itulah waktu rata-rata yang dibutuhkan WhatsApp server untuk menyebarkan Sender Key baru ke semua perangkat dalam grup. Kamu bisa mencoba 3 detik jika grupnya kecil (< 50 orang), tapi 5 detik lebih aman untuk grup besar.
2039
+
2040
+ ---
2041
+
2042
+ ## 🧠 Panduan Lengkap: Menangani Event Grup dengan Benar
2043
+
2044
+ ### 📋 Template Lengkap Welcome & Leave Message
2045
+
2046
+ Berikut adalah template yang **sudah teruji dan aman** untuk menangani welcome/leave message:
2047
+
2048
+ ```javascript
2049
+ const { default: makeWASocket, useMultiFileAuthState } = require('astrabail')
2050
+ const fs = require('fs')
2051
+
2052
+ async function startBot() {
2053
+ const { state, saveCreds } = await useMultiFileAuthState('./session')
2054
+ const sock = makeWASocket({ auth: state })
2055
+
2056
+ sock.ev.on('creds.update', saveCreds)
2057
+
2058
+ // ✅ Event handler yang AMAN dan TIDAK menyebabkan hang
2059
+ sock.ev.on('group-participants.update', async ({ id, participants, action, author }) => {
2060
+
2061
+ // ✅ STEP 1: Ambil data grup yang diperlukan SEBELUM setTimeout
2062
+ // Ini aman karena groupMetadata sudah ada di cache internal AstraBail
2063
+ let groupMeta
2064
+ try {
2065
+ groupMeta = await sock.groupMetadata(id)
2066
+ } catch (e) {
2067
+ console.error('Gagal ambil metadata grup:', e.message)
2068
+ return
2069
+ }
2070
+
2071
+ // ✅ STEP 2: Kirim pesan di background dengan delay
2072
+ // Jangan await di sini — biarkan event handler selesai lebih dulu
2073
+ setTimeout(async () => {
2074
+ for (const participant of participants) {
2075
+ const userJid = participant.id || participant
2076
+ const userNumber = userJid.split('@')[0]
2077
+
2078
+ try {
2079
+ if (action === 'add') {
2080
+ // Pesan Welcome
2081
+ await sock.sendMessage(id, {
2082
+ text: `👋 Selamat datang @${userNumber} di grup *${groupMeta.subject}*!`,
2083
+ mentions: [userJid]
2084
+ })
2085
+ } else if (action === 'remove') {
2086
+ // Pesan Leave
2087
+ await sock.sendMessage(id, {
2088
+ text: `👋 Sampai jumpa @${userNumber}, semoga ketemu lagi!`,
2089
+ mentions: [userJid]
2090
+ })
2091
+ } else if (action === 'promote') {
2092
+ // Pesan Promosi Admin
2093
+ await sock.sendMessage(id, {
2094
+ text: `🎊 Selamat @${userNumber}! Kamu sekarang menjadi *Admin* grup ini.`,
2095
+ mentions: [userJid]
2096
+ })
2097
+ } else if (action === 'demote') {
2098
+ // Pesan Copot Admin
2099
+ await sock.sendMessage(id, {
2100
+ text: `ℹ️ @${userNumber} tidak lagi menjadi Admin grup ini.`,
2101
+ mentions: [userJid]
2102
+ })
2103
+ }
2104
+ } catch (e) {
2105
+ console.error(`Gagal kirim pesan untuk ${userJid}:`, e.message)
2106
+ }
2107
+ }
2108
+ }, 5000) // ← Delay 5 detik (JANGAN dihapus!)
2109
+ })
2110
+ }
2111
+
2112
+ startBot()
2113
+ ```
2114
+
2115
+ ---
2116
+
2117
+ ## 🆔 Panduan Lengkap: LID vs JID (Untuk Pemula)
2118
+
2119
+ > [!NOTE]
2120
+ > Bagian ini menjelaskan sistem identifikasi pengguna WhatsApp yang baru. Penting untuk dipahami agar fitur mention, welcome, dan admin-check bekerja dengan benar.
2121
+
2122
+ ### Apa itu JID dan LID?
2123
+
2124
+ WhatsApp menggunakan dua sistem ID pengguna:
2125
+
2126
+ | Tipe | Format | Keterangan |
2127
+ |------|--------|------------|
2128
+ | **JID (Phone Number ID)** | `628xxx@s.whatsapp.net` | ID lama berbasis nomor telepon |
2129
+ | **LID (Linked ID)** | `123456789@lid` | ID baru sistem multi-device WhatsApp |
2130
+
2131
+ ### Masalah yang Sering Terjadi
2132
+
2133
+ Pada grup yang sudah **mengaktifkan sistem LID** (mode addressing baru WhatsApp), event `group-participants.update` bisa mengirimkan participant dengan format `@lid` — bukan nomor telepon. Jika kamu tidak menanganinya, fitur mention tidak akan bekerja.
2134
+
2135
+ **AstraBail sudah otomatis mengatasi ini.** Library secara internal:
2136
+ 1. Mendeteksi apakah participant menggunakan LID
2137
+ 2. Jika LID tersedia dan `phoneNumber` ada, **otomatis mengganti `id` dengan `phoneNumber`** (PN format)
2138
+ 3. Menyimpan LID asli di field `lid` untuk referensi
2139
+
2140
+ ```javascript
2141
+ // Contoh data participant yang dikirim AstraBail ke event handler kamu:
2142
+ {
2143
+ id: '628123456789@s.whatsapp.net', // ← Sudah dinormalisasi ke PN (nomor telepon)
2144
+ phoneNumber: '628123456789@s.whatsapp.net',
2145
+ lid: '272202813464634@lid', // ← LID asli disimpan di sini
2146
+ admin: null // null = bukan admin, 'admin' = admin, 'superadmin' = owner
2147
+ }
2148
+ ```
2149
+
2150
+ ### Cara Aman Mengambil Nomor Telepon dari Participant
2151
+
2152
+ ```javascript
2153
+ // ✅ Cara yang AMAN — kompatibel dengan LID dan JID
2154
+ function getRealJid(participant) {
2155
+ if (!participant) return null
2156
+ if (typeof participant === 'string') return participant
2157
+
2158
+ // Prioritaskan phoneNumber (sudah dinormalisasi oleh AstraBail)
2159
+ if (participant.phoneNumber) return participant.phoneNumber
2160
+
2161
+ // Fallback: gunakan id jika bukan @lid
2162
+ if (participant.id && !participant.id.endsWith('@lid')) return participant.id
2163
+
2164
+ return null
2165
+ }
2166
+
2167
+ // Penggunaan:
2168
+ sock.ev.on('group-participants.update', async ({ participants, action, id }) => {
2169
+ setTimeout(async () => {
2170
+ for (const p of participants) {
2171
+ const userJid = getRealJid(p) // ← Selalu gunakan fungsi ini
2172
+ if (!userJid) continue
2173
+
2174
+ const phoneNumber = userJid.split('@')[0] // Ambil nomor saja
2175
+
2176
+ await sock.sendMessage(id, {
2177
+ text: `@${phoneNumber} bergabung!`,
2178
+ mentions: [userJid]
2179
+ })
2180
+ }
2181
+ }, 5000)
2182
+ })
2183
+ ```
2184
+
2185
+ ---
2186
+
2187
+ ## ⚡ Tips Performa & Optimasi
2188
+
2189
+ ### 1. Aktifkan Cache Metadata Grup (Sangat Direkomendasikan)
2190
+
2191
+ Tanpa cache, setiap kali bot memproses pesan dari grup, library akan melakukan request ke server WhatsApp untuk mengambil daftar peserta. Ini lambat dan bisa menyebabkan rate limit.
2192
+
2193
+ **AstraBail sudah memiliki cache internal bawaan (5 menit TTL)**, tapi kamu bisa menambahkan cache eksternal untuk kontrol lebih lanjut:
2194
+
2195
+ ```javascript
2196
+ // Instalasi: npm install node-cache
2197
+ const NodeCache = require('node-cache')
2198
+ const groupCache = new NodeCache({ stdTTL: 300, useClones: false }) // Cache 5 menit
2199
+
2200
+ const sock = makeWASocket({
2201
+ auth: state,
2202
+ // ← Ini memberi tahu AstraBail untuk pakai cache kamu dulu sebelum hit server
2203
+ cachedGroupMetadata: async (jid) => groupCache.get(jid)
2204
+ })
2205
+
2206
+ // Update cache saat ada perubahan grup
2207
+ sock.ev.on('groups.update', async (updates) => {
2208
+ for (const update of updates) {
2209
+ const meta = await sock.groupMetadata(update.id)
2210
+ groupCache.set(update.id, meta)
2211
+ }
2212
+ })
2213
+
2214
+ sock.ev.on('group-participants.update', async ({ id }) => {
2215
+ // Invalidate cache saat ada perubahan peserta
2216
+ groupCache.del(id)
2217
+ })
2218
+ ```
2219
+
2220
+ ### 2. Gunakan `makeCacheableSignalKeyStore` untuk Performa Signal
2221
+
2222
+ ```javascript
2223
+ const { makeCacheableSignalKeyStore } = require('astrabail')
2224
+ const pino = require('pino')
2225
+
2226
+ const sock = makeWASocket({
2227
+ auth: {
2228
+ creds: state.creds,
2229
+ // ← Ini mempercepat proses enkripsi/dekripsi pesan secara signifikan
2230
+ keys: makeCacheableSignalKeyStore(state.keys, pino({ level: 'silent' }))
2231
+ }
2232
+ })
2233
+ ```
2234
+
2235
+ ### 3. Konfigurasi Socket yang Direkomendasikan untuk Bot Production
2236
+
2237
+ ```javascript
2238
+ const sock = makeWASocket({
2239
+ auth: state,
2240
+ printQRInTerminal: false,
2241
+
2242
+ // Sembunyikan log internal Baileys agar terminal bersih
2243
+ logger: pino({ level: 'silent' }),
2244
+
2245
+ // Nonaktifkan sinkronisasi history penuh (hemat memori & waktu koneksi)
2246
+ syncFullHistory: false,
2247
+ shouldSyncHistoryMessage: () => false,
2248
+
2249
+ // Timeout koneksi yang aman
2250
+ connectTimeoutMs: 60000,
2251
+ defaultQueryTimeoutMs: 0, // 0 = tidak ada timeout (lebih stabil)
2252
+ keepAliveIntervalMs: 10000,
2253
+
2254
+ // Bot tetap terlihat online
2255
+ markOnlineOnConnect: true,
2256
+
2257
+ // Performa enkripsi yang lebih baik
2258
+ keys: makeCacheableSignalKeyStore(state.keys, pino({ level: 'silent' })),
2259
+
2260
+ // Cache metadata grup
2261
+ cachedGroupMetadata: async (jid) => groupCache.get(jid)
2262
+ })
2263
+ ```
2264
+
2265
+ ### 4. Cegah Pemrosesan Pesan Duplikat
2266
+
2267
+ ```javascript
2268
+ // Set untuk menyimpan ID pesan yang sudah diproses
2269
+ const processedMessages = new Set()
2270
+
2271
+ sock.ev.on('messages.upsert', async ({ messages, type }) => {
2272
+ if (type !== 'notify') return
2273
+
2274
+ for (const m of messages) {
2275
+ if (!m.message || !m.key?.id) continue
2276
+
2277
+ // Lewati jika sudah diproses
2278
+ if (processedMessages.has(m.key.id)) continue
2279
+ processedMessages.add(m.key.id)
2280
+
2281
+ // Hapus dari Set setelah 60 detik untuk hemat memori
2282
+ setTimeout(() => processedMessages.delete(m.key.id), 60000)
2283
+
2284
+ // Proses pesan...
2285
+ // await handler(sock, m)
2286
+ }
2287
+ })
2288
+ ```
2289
+
2290
+ ---
2291
+
2292
+ ## 🔧 Panduan Troubleshooting (Untuk Pemula)
2293
+
2294
+ Bagian ini membantu kamu mendiagnosis dan memperbaiki masalah umum yang sering terjadi.
2295
+
2296
+ ---
2297
+
2298
+ ### ❗ Masalah: Bot Tidak Merespon Command Setelah Ada User Join/Leave
2299
+
2300
+ **Gejala:** Terminal menampilkan log `MSG` (pesan masuk) tapi tidak ada log `CMD` (command dieksekusi). Bot seperti "membeku" selama beberapa menit.
2301
+
2302
+ **Penyebab:** `await sendMessage()` dipanggil langsung di dalam event handler `group-participants.update` tanpa delay.
2303
+
2304
+ **Solusi:**
2305
+ ```javascript
2306
+ // Tambahkan setTimeout dengan delay 5000ms (5 detik) sebelum sendMessage
2307
+ setTimeout(async () => {
2308
+ await sock.sendMessage(groupId, { text: 'Welcome!' })
2309
+ }, 5000) // ← Ini yang menyelamatkan botmu
2310
+ ```
2311
+
2312
+ ---
2313
+
2314
+ ### ❗ Masalah: Mention Tidak Berfungsi / Nama Tidak Muncul
2315
+
2316
+ **Gejala:** Pesan terkirim tapi `@nomortelpon` tidak menjadi mention biru, atau nama kontak tidak muncul.
2317
+
2318
+ **Penyebab:** Format JID yang digunakan salah, atau field `mentions` tidak diisi.
2319
+
2320
+ **Solusi:**
2321
+ ```javascript
2322
+ // ✅ Cara yang benar
2323
+ const userJid = '628123456789@s.whatsapp.net' // Harus pakai @s.whatsapp.net
2324
+
2325
+ await sock.sendMessage(groupId, {
2326
+ text: `Halo @628123456789!`, // @ + nomor tanpa kode negara awal 0
2327
+ mentions: [userJid] // ← WAJIB diisi agar mention berfungsi
2328
+ })
2329
+ ```
2330
+
2331
+ ---
2332
+
2333
+ ### ❗ Masalah: Session Terhapus / QR Code Muncul Terus
2334
+
2335
+ **Gejala:** Setiap kali bot restart, QR code muncul lagi dan harus scan ulang.
2336
+
2337
+ **Penyebab:** Folder session tidak disimpan dengan benar, atau ada error saat menyimpan kredensial.
2338
+
2339
+ **Solusi:**
2340
+ ```javascript
2341
+ const { state, saveCreds } = await useMultiFileAuthState('./session')
2342
+
2343
+ const sock = makeWASocket({ auth: state })
2344
+
2345
+ // ← WAJIB: Pastikan ini ada agar session tersimpan
2346
+ sock.ev.on('creds.update', saveCreds)
2347
+ ```
2348
+
2349
+ Pastikan folder `./session` **tidak dihapus** dan bot punya **izin menulis** ke folder tersebut.
2350
+
2351
+ ---
2352
+
2353
+ ### ❗ Masalah: Bot Error "Connection Closed" / Sering Disconnect
2354
+
2355
+ **Gejala:** Bot sering disconnect dan perlu reconnect manual.
2356
+
2357
+ **Solusi:** Implementasikan auto-reconnect yang benar:
2358
+
2359
+ ```javascript
2360
+ const { DisconnectReason } = require('astrabail')
2361
+ const { Boom } = require('@hapi/boom')
2362
+
2363
+ sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
2364
+ if (connection === 'close') {
2365
+ const reason = new Boom(lastDisconnect?.error)?.output?.statusCode
2366
+
2367
+ if (reason === DisconnectReason.loggedOut) {
2368
+ // Sesi expired atau logout — JANGAN reconnect, hapus session dulu
2369
+ console.log('❌ Bot ter-logout. Hapus folder session dan scan ulang QR.')
2370
+ process.exit(1)
2371
+ } else {
2372
+ // Error lain — aman untuk reconnect
2373
+ console.log('🔄 Koneksi terputus, mencoba reconnect...')
2374
+ startBot() // Panggil ulang fungsi utama
2375
+ }
2376
+ } else if (connection === 'open') {
2377
+ console.log('✅ Bot berhasil terhubung!')
2378
+ }
2379
+ })
2380
+ ```
2381
+
2382
+ ---
2383
+
2384
+ ### ❗ Masalah: `groupMetadata` Error / Timeout saat Banyak Request
2385
+
2386
+ **Gejala:** Error seperti `Error: Timed out` atau `Error: not-authorized` saat memanggil `groupMetadata`.
2387
+
2388
+ **Penyebab:** Terlalu banyak request `groupMetadata` dalam waktu singkat (rate limit dari WhatsApp).
2389
+
2390
+ **Solusi:** Gunakan cache dan batasi frekuensi request:
2391
+
2392
+ ```javascript
2393
+ // Map untuk menyimpan waktu terakhir request per grup
2394
+ const lastFetchTime = new Map()
2395
+
2396
+ async function safeGroupMetadata(sock, groupJid) {
2397
+ const now = Date.now()
2398
+ const lastFetch = lastFetchTime.get(groupJid) || 0
2399
+
2400
+ // Batasi request: minimal 30 detik sekali per grup
2401
+ if (now - lastFetch < 30000) {
2402
+ // Gunakan data dari file lokal jika ada
2403
+ const dbPath = `./database/group/${groupJid.split('@')[0]}.json`
2404
+ if (fs.existsSync(dbPath)) {
2405
+ return JSON.parse(fs.readFileSync(dbPath, 'utf-8'))
2406
+ }
2407
+ return null
2408
+ }
2409
+
2410
+ try {
2411
+ const meta = await sock.groupMetadata(groupJid)
2412
+ lastFetchTime.set(groupJid, now)
2413
+ return meta
2414
+ } catch (e) {
2415
+ console.error('groupMetadata error:', e.message)
2416
+ return null
2417
+ }
2418
+ }
2419
+ ```
2420
+
2421
+ ---
2422
+
2423
+ ### ❗ Masalah: Pesan Tidak Terenkripsi / Error Enkripsi
2424
+
2425
+ **Gejala:** Error seperti `Error: No sessions`, `Error: bad mac`, atau pesan gagal terkirim ke grup tertentu.
2426
+
2427
+ **Penyebab:** Session Signal untuk beberapa member belum tersedia atau sudah expired.
2428
+
2429
+ **Solusi:** Pastikan menggunakan `makeCacheableSignalKeyStore` dan **jangan hapus folder session** secara manual. Jika masalah persisten, coba:
2430
+
2431
+ ```javascript
2432
+ // Reset cache session (hati-hati: ini akan reconnect)
2433
+ // Hapus folder session, lalu scan QR ulang
2434
+ ```
2435
+
2436
+ ---
2437
+
2438
+ ## 📐 Referensi Cepat: Format ID WhatsApp
2439
+
2440
+ | Tipe | Format | Contoh |
2441
+ |------|--------|--------|
2442
+ | **User (PN)** | `[kode_negara][nomor]@s.whatsapp.net` | `628123456789@s.whatsapp.net` |
2443
+ | **User (LID)** | `[angka_random]@lid` | `272202813464634@lid` |
2444
+ | **Grup** | `[timestamp]-[random]@g.us` | `120363186018390209@g.us` |
2445
+ | **Broadcast** | `[timestamp]@broadcast` | `1234567890@broadcast` |
2446
+ | **Status/Story** | `status@broadcast` | `status@broadcast` |
2447
+ | **Newsletter** | `[id]@newsletter` | `123456789@newsletter` |
2448
+
2449
+ > [!IMPORTANT]
2450
+ > Selalu gunakan format `@s.whatsapp.net` (bukan `@c.us`) untuk user. Format `@c.us` sudah deprecated dan tidak didukung oleh WhatsApp multi-device.
2451
+
2452
+ ---
2453
+
2454
+ ## 📝 Daftar Event Lengkap AstraBail
2455
+
2456
+ | Event | Kapan Dipanggil | Data yang Diterima |
2457
+ |-------|----------------|-------------------|
2458
+ | `connection.update` | Status koneksi berubah | `{ connection, lastDisconnect, qr }` |
2459
+ | `creds.update` | Kredensial session berubah | Data kredensial baru |
2460
+ | `messages.upsert` | Pesan baru diterima/dikirim | `{ messages, type }` |
2461
+ | `messages.update` | Pesan diperbarui (dibaca, dihapus, dll) | Array update pesan |
2462
+ | `messages.reaction` | Ada reaksi pada pesan | `[{ reaction, key }]` |
2463
+ | `message-receipt.update` | Status pengiriman pesan berubah | Array receipt update |
2464
+ | `messages.delete` | Pesan dihapus | Keys pesan yang dihapus |
2465
+ | `group-participants.update` | Member grup berubah (join/leave/promote) | `{ id, participants, action, author }` |
2466
+ | `groups.update` | Info grup berubah (nama, deskripsi, dll) | Array update grup |
2467
+ | `group.join-request` | Ada request join grup | `{ id, participant, action }` |
2468
+ | `chats.update` | Data chat berubah | Array update chat |
2469
+ | `chats.upsert` | Chat baru muncul | Array chat baru |
2470
+ | `contacts.update` | Info kontak berubah | Array update kontak |
2471
+ | `contacts.upsert` | Kontak baru | Array kontak baru |
2472
+ | `presence.update` | Status online/typing berubah | `{ id, presences }` |
2473
+ | `messaging-history.set` | Riwayat pesan diterima | Data history |
2474
+ | `call` | Ada panggilan masuk | Data panggilan |
2475
+ | `labels.association` | Label chat berubah | Data asosiasi label |
2476
+
2477
+ ---
2478
+
2479
+ ## 🎯 Contoh Bot Lengkap yang Siap Produksi
2480
+
2481
+ Berikut adalah contoh bot **paling lengkap dan aman** menggunakan AstraBail:
2482
+
2483
+ ```javascript
2484
+ const { default: makeWASocket, useMultiFileAuthState, DisconnectReason, makeCacheableSignalKeyStore } = require('astrabail')
2485
+ const { Boom } = require('@hapi/boom')
2486
+ const pino = require('pino')
2487
+ const NodeCache = require('node-cache')
2488
+
2489
+ // Cache untuk metadata grup (TTL 5 menit)
2490
+ const groupCache = new NodeCache({ stdTTL: 300, useClones: false })
2491
+
2492
+ // Set untuk mencegah pesan duplikat
2493
+ const processedMsgs = new Set()
2494
+
2495
+ async function startBot() {
2496
+ const { state, saveCreds } = await useMultiFileAuthState('./session')
2497
+
2498
+ const sock = makeWASocket({
2499
+ auth: {
2500
+ creds: state.creds,
2501
+ keys: makeCacheableSignalKeyStore(state.keys, pino({ level: 'silent' }))
2502
+ },
2503
+ logger: pino({ level: 'silent' }),
2504
+ printQRInTerminal: false,
2505
+ syncFullHistory: false,
2506
+ connectTimeoutMs: 60000,
2507
+ defaultQueryTimeoutMs: 0,
2508
+ keepAliveIntervalMs: 10000,
2509
+ cachedGroupMetadata: async (jid) => groupCache.get(jid)
2510
+ })
2511
+
2512
+ // ─── Simpan session ───────────────────────────────────────────────────
2513
+ sock.ev.on('creds.update', saveCreds)
2514
+
2515
+ // ─── Auto reconnect ───────────────────────────────────────────────────
2516
+ sock.ev.on('connection.update', ({ connection, lastDisconnect, qr }) => {
2517
+ if (qr) console.log('Scan QR ini untuk login')
2518
+ if (connection === 'close') {
2519
+ const reason = new Boom(lastDisconnect?.error)?.output?.statusCode
2520
+ if (reason === DisconnectReason.loggedOut) {
2521
+ console.log('❌ Session expired. Hapus folder session dan restart.')
2522
+ process.exit(1)
2523
+ }
2524
+ console.log('🔄 Reconnecting...')
2525
+ startBot()
2526
+ } else if (connection === 'open') {
2527
+ console.log('✅ Bot Online!')
2528
+ }
2529
+ })
2530
+
2531
+ // ─── Update cache saat grup berubah ──────────────────────────────────
2532
+ sock.ev.on('groups.update', async (updates) => {
2533
+ for (const update of updates) {
2534
+ try {
2535
+ const meta = await sock.groupMetadata(update.id)
2536
+ groupCache.set(update.id, meta)
2537
+ } catch (_) {}
2538
+ }
2539
+ })
2540
+
2541
+ // ─── Welcome/Leave message yang AMAN ─────────────────────────────────
2542
+ sock.ev.on('group-participants.update', async ({ id, participants, action }) => {
2543
+ // Ambil metadata sebelum setTimeout (sudah ada di cache, aman)
2544
+ let meta
2545
+ try {
2546
+ meta = await sock.groupMetadata(id)
2547
+ groupCache.set(id, meta) // Update cache
2548
+ } catch (_) { return }
2549
+
2550
+ // ← KUNCI: Delay 5 detik agar Baileys selesai sinkronisasi kunci enkripsi
2551
+ setTimeout(async () => {
2552
+ for (const p of participants) {
2553
+ const userJid = p.phoneNumber || (p.id?.endsWith('@lid') ? null : p.id) || p
2554
+ if (!userJid || typeof userJid !== 'string') continue
2555
+ const num = userJid.split('@')[0]
2556
+
2557
+ try {
2558
+ if (action === 'add') {
2559
+ await sock.sendMessage(id, {
2560
+ text: `👋 Selamat datang @${num} di grup *${meta.subject}*!`,
2561
+ mentions: [userJid]
2562
+ })
2563
+ } else if (action === 'remove') {
2564
+ await sock.sendMessage(id, {
2565
+ text: `👋 Sampai jumpa @${num}!`,
2566
+ mentions: [userJid]
2567
+ })
2568
+ }
2569
+ } catch (e) {
2570
+ console.error('Pesan gagal:', e.message)
2571
+ }
2572
+ }
2573
+ }, 5000)
2574
+ })
2575
+
2576
+ // ─── Handler pesan masuk ─────────────────────────────────────────────
2577
+ sock.ev.on('messages.upsert', async ({ messages, type }) => {
2578
+ if (type !== 'notify') return
2579
+
2580
+ for (const m of messages) {
2581
+ if (!m.message || !m.key?.id) continue
2582
+ if (m.key.remoteJid === 'status@broadcast') continue
2583
+
2584
+ // Cegah duplikat
2585
+ if (processedMsgs.has(m.key.id)) continue
2586
+ processedMsgs.add(m.key.id)
2587
+ setTimeout(() => processedMsgs.delete(m.key.id), 60000)
2588
+
2589
+ // Proses pesan di sini...
2590
+ const text = m.message.conversation || m.message.extendedTextMessage?.text || ''
2591
+ if (text === '.ping') {
2592
+ await sock.sendMessage(m.key.remoteJid, { text: '🏓 Pong!' }, { quoted: m })
2593
+ }
2594
+ }
2595
+ })
2596
+ }
2597
+
2598
+ startBot()
2599
+ ```
2600
+
2601
+ ---
2602
+
2603
+ <div align="center">
2604
+
2605
+ ## 💬 Butuh Bantuan?
2606
+
2607
+ Jika kamu mengalami masalah yang tidak tercakup di dokumentasi ini:
2608
+
2609
+ [![WhatsApp Channel](https://img.shields.io/badge/WhatsApp-Channel-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029Vazo6KM8kyyJ4eWh3A25)
2610
+ [![GitHub Issues](https://img.shields.io/badge/GitHub-Issues-181717?style=for-the-badge&logo=github)](https://github.com/Danimaru-ze/AstraBail/issues)
2611
+
2612
+ **AstraBail** — *Built for stability. Designed for developers.*
2613
+
2614
+ </div>
2615
+
2616
+ ---