botify-wa 0.2.0 → 0.6.0

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
@@ -1,38 +1,79 @@
1
1
  # Botify (`botify-wa`)
2
2
 
3
- # Botify (`botify-wa`)
3
+ **Botify** adalah *framework* WhatsApp bot yang ringan, dibangun di atas *core* protokol WhatsApp yang di-*vendor* langsung ke dalam repo ini (`vendor/core/`) — bukan diambil dari npm saat instalasi. Artinya, proyekmu tetap berjalan normal walaupun suatu saat paket upstream-nya hilang dari registry. Dependensi dari core itu sendiri (`ws`, `pino`, `libsignal`, `protobufjs`, dll) tetap ter-install seperti biasa lewat npm — semuanya paket yang sudah mapan dan berisiko rendah.
4
+
5
+ Di atas core tersebut, Botify menambahkan struktur yang benar-benar dibutuhkan hampir semua bot:
4
6
 
5
- A lightweight WhatsApp bot **framework**. The WhatsApp protocol core is **vendored directly in this repo** (`vendor/core/`) — it's not pulled from npm at install time, so your project keeps working even if any upstream package disappears from the registry. Its own dependencies (`ws`, `pino`, `libsignal`, `protobufjs`, etc.) are still installed normally from npm — those are established, widely-used packages with much lower risk.
7
+ - **Sistem command** — `bot.command("ping", handler)`, tanpa perlu parsing manual event koneksi mentah
8
+ - **Middleware** — `bot.use(fn)`
9
+ - **Objek `Context`** yang ramah pakai — `ctx.reply()`, `ctx.args`, `ctx.sender`, dst — menggantikan objek pesan mentah
10
+ - **Penanganan pesan lengkap** — setiap tipe pesan sudah diklasifikasikan (`ctx.type`: teks, gambar, video, audio/voice note, stiker, dokumen, kontak, lokasi, poll, balasan tombol/list, undangan grup, edit/hapus, dan lainnya), dengan pembongkaran otomatis untuk pesan *ephemeral*/*view-once*
11
+ - **Unduh & kirim media** — `ctx.download()` / `ctx.saveMedia()`, serta lebih dari 20 metode `ctx.sendXxx()` (gambar, video, audio, dokumen, stiker, kontak, lokasi, poll, tombol interaktif, list menu, album, tabel, code block, dan lain-lain — lihat [Referensi API](#referensi-api))
12
+ - **Manajemen pesan** — `ctx.react()`, `ctx.edit()` / `ctx.editMessage()`, `ctx.delete()` / `ctx.deleteMessage()`, `ctx.pin()`, `ctx.star()`, `ctx.forward()`
13
+ - **Dukungan pesan yang di-*reply* (Quoted)** — `ctx.quoted` memberi akses yang sama lengkapnya (download/react/delete) untuk pesan yang sedang dibalas
14
+ - **Auto-reconnect** bawaan dengan *exponential backoff*, plus manajemen sesi lewat `useMultiFileAuthState`
15
+ - **Event level-framework** yang jelas: `ready`, `message`, `disconnect`, `unknownCommand`
16
+ - **Middleware bawaan** siap pakai: logger, sistem permission (owner/admin), cooldown per-command, dan anti-spam
17
+ - **CLI** (`npx botify-wa build <nama-bot>`) untuk membuat proyek bot baru dari template
6
18
 
7
- Botify adds the structure most bots actually need on top of that core:
19
+ ## Daftar Isi
8
20
 
9
- - A **command system** (`bot.command("ping", handler)`) instead of manually parsing raw connection events
10
- - **Middleware** support (`bot.use(fn)`)
11
- - A friendly **`Context`** object (`ctx.reply()`, `ctx.args`, `ctx.sender`, …) instead of raw message objects
12
- - Built-in **auto-reconnect** and session handling via `useMultiFileAuthState`
13
- - Clean framework-level **events**: `ready`, `message`, `disconnect`, `unknownCommand`
21
+ - [Struktur Proyek](#struktur-proyek)
22
+ - [Instalasi](#instalasi)
23
+ - [Mulai Cepat](#mulai-cepat)
24
+ - [CLI](#cli)
25
+ - [Konfigurasi (`config.bt`)](#konfigurasi-configbt)
26
+ - [Referensi API](#referensi-api)
27
+ - [`new Bot(options)`](#new-botoptions)
28
+ - [`bot.command()` / `bot.use()` / `bot.on()`](#botcommand--botuse--boton)
29
+ - [`Context`](#context)
30
+ - [`Quoted`](#quoted)
31
+ - [Memperbarui Core yang Di-*vendor*](#memperbarui-core-yang-di-vendor)
32
+ - [Turun ke Koneksi Mentah](#turun-ke-koneksi-mentah)
33
+ - [Lisensi](#lisensi)
14
34
 
15
- ## Project structure
35
+ ## Struktur Proyek
16
36
 
17
37
  ```
18
38
  botify-wa/
19
- ├── vendor/core/ ← vendored WhatsApp protocol core (encryption, sockets)
20
- ├── src/ ← Botify framework layer (Bot, Context, PluginManager)
21
- ├── examples/ ← example bots
39
+ ├── vendor/core/ ← core protokol WhatsApp yang di-vendor (enkripsi, socket)
40
+ ├── src/
41
+ │ ├── Bot.js ← siklus hidup koneksi, dispatch command, event
42
+ │ ├── Context.js ← class tipis — merakit seluruh mixin di bawah ini
43
+ │ ├── context/ ← ~40 method Context, dipisah per tanggung jawab
44
+ │ │ ├── derive-message-state.js (pesan mentah → ctx.from/type/text/…)
45
+ │ │ ├── command-parsing.js (teks/id → { command, args })
46
+ │ │ ├── jid-utils.js (helper klasifikasi JID)
47
+ │ │ ├── sending/text.js (reply, send, sendCard)
48
+ │ │ ├── sending/media.js (sendImage, sendVideo, sendAudio, …)
49
+ │ │ ├── sending/interactive.js (sendButtons, sendListMenu)
50
+ │ │ ├── sending/rich.js (sendTable(V2), sendCodeBlock(V2), …)
51
+ │ │ ├── sending/other.js (sendContact, sendPoll, sendPayment, …)
52
+ │ │ ├── media-transfer.js (download, saveMedia)
53
+ │ │ ├── message-actions.js (react, edit, delete, pin, star, …)
54
+ │ │ └── group-info.js (isGroupAdmin, getGroupName, …)
55
+ │ ├── PluginManager.js
56
+ │ ├── middlewares/ ← logger, permission, cooldown, antiSpam
57
+ │ ├── config/ ← parser & schema untuk config.bt
58
+ │ └── templates/ ← template yang di-scaffold oleh CLI
59
+ ├── examples/ ← contoh bot
60
+ ├── bin/botify.js ← entry point CLI
22
61
  └── package.json
23
62
  ```
24
63
 
25
- Raw core APIs are still fully accessible via `bot.sock` if you need to drop down a level.
64
+ `Context` sendiri hanya bertanggung jawab atas konstruksi objeknya; seluruh method instance-nya tinggal di `src/context/*.js`, masing-masing file fokus pada satu tanggung jawab, lalu digabungkan ke `Context.prototype` di `src/Context.js`. Dengan begitu setiap file tetap ringkas, dan method pengiriman pesan baru punya "rumah" sendiri alih-alih menumpuk di satu file yang sudah besar. API publik (`ctx.reply()`, `ctx.sendImage()`, dst) tidak berubah — ini murni reorganisasi internal.
65
+
66
+ API core mentah tetap bisa diakses penuh lewat `bot.sock` kalau kamu perlu turun ke level yang lebih rendah.
26
67
 
27
- ## Install
68
+ ## Instalasi
28
69
 
29
70
  ```bash
30
71
  npm install
31
72
  ```
32
73
 
33
- (The protocol core is already vendored in `vendor/core/` — nothing extra to install for it.)
74
+ Core protokolnya sudah ter-*vendor* di `vendor/core/`, jadi tidak ada instalasi tambahan untuk bagian itu.
34
75
 
35
- ## Quick start
76
+ ## Mulai Cepat
36
77
 
37
78
  ```js
38
79
  import { Bot } from "./src/index.js";
@@ -43,59 +84,187 @@ bot.command("ping", async (ctx) => {
43
84
  await ctx.reply("pong 🏓");
44
85
  });
45
86
 
46
- bot.on("ready", () => console.log("Bot is online!"));
87
+ bot.on("ready", () => console.log("Bot online!"));
47
88
 
48
89
  await bot.start();
49
90
  ```
50
91
 
51
- Scan the QR code printed in your terminal with WhatsApp (Linked Devices) and you're connected.
92
+ Scan QR code yang muncul di terminal menggunakan WhatsApp (menu **Perangkat Tertaut**), dan bot langsung terhubung.
93
+
94
+ Lihat [`examples/simple-bot.js`](./examples/simple-bot.js) untuk contoh yang lebih lengkap (command, alias, middleware, menu bantuan).
95
+
96
+ ## CLI
97
+
98
+ ```bash
99
+ npx botify-wa build <nama-bot> # scaffold proyek bot baru dari template
100
+ npx botify-wa help # tampilkan bantuan
101
+ npx botify-wa version # tampilkan versi framework
102
+ ```
103
+
104
+ Perintah `build` akan menyalin template dari `src/templates/` (termasuk contoh plugin `ping`, `info`, `menu`, dan `config.bt`) ke folder proyek baru. Aman dijalankan berulang kali — file yang sudah ada tidak akan ditimpa.
105
+
106
+ ## Konfigurasi (`config.bt`)
107
+
108
+ Selain lewat opsi di kode (`new Bot({...})`), konfigurasi juga bisa ditaruh di file `config.bt` pada root proyek. Opsi dari kode selalu menang jika keduanya diisi.
52
109
 
53
- See [`examples/simple-bot.js`](./examples/simple-bot.js) for a fuller example (commands, aliases, middleware, help menu).
110
+ ```ini
111
+ [bot]
112
+ prefix = "!"
113
+ session_path = "./session"
114
+ log_level = "error"
115
+ print_qr = true
116
+ # Format JID: "628XXXXXXXXXX@s.whatsapp.net"
117
+ owners = []
54
118
 
55
- ## Updating the vendored core
119
+ [reconnect]
120
+ base_delay = 1000 # ms — percobaan reconnect pertama
121
+ max_delay = 30000 # ms — batas atas exponential backoff
56
122
 
57
- Since the core is vendored (not an npm dependency), it won't auto-update. If you want to pull in upstream protocol fixes later, download the source, diff it against `vendor/core/`, and merge changes manually — this keeps you in control of what changes land in your framework.
123
+ [cooldown]
124
+ default = 0 # ms — default global untuk semua command (0 = nonaktif)
125
+ # message = "⏳ Tunggu {remaining}s sebelum pakai command ini lagi."
58
126
 
59
- ## API overview
127
+ [anti_spam]
128
+ enabled = false
129
+ window_ms = 5000 # ukuran rolling window (ms)
130
+ max_messages = 5 # maksimum command per pengirim per window
131
+ # message = "🚫 Kamu terlalu cepat! Tunggu sebentar."
132
+
133
+ [permission]
134
+ # owner_message = "🚫 Command ini khusus owner bot."
135
+ # admin_message = "🚫 Command ini khusus admin grup."
136
+
137
+ [logger]
138
+ enabled = true
139
+ show_pn = true # tampilkan nomor telepon di samping LID pada log
140
+ ```
141
+
142
+ Semua key bersifat opsional — key yang tidak diisi otomatis memakai nilai default dari Botify.
143
+
144
+ ## Referensi API
60
145
 
61
146
  ### `new Bot(options)`
62
- | Option | Default | Description |
63
- |---|---|---|
64
- | `sessionPath` | `"./session"` | Folder where auth credentials are stored |
65
- | `prefix` | `"!"` | Command prefix |
66
- | `printQR` | `true` | Print QR code to terminal on first login |
67
- | `socketConfig` | `{}` | Passed straight through to the underlying connection socket |
68
147
 
69
- ### `bot.command(name, handler, opts?)`
70
- Registers a command. `handler` receives a [`Context`](./src/Context.js). `opts.aliases` and `opts.description` are optional.
148
+ | Opsi | Default | Deskripsi |
149
+ |---|---|---|
150
+ | `sessionPath` | `"./session"` | Folder penyimpanan kredensial autentikasi |
151
+ | `prefix` | `"!"` | Prefix command |
152
+ | `printQR` | `true` | Cetak QR code ke terminal saat login pertama |
153
+ | `logLevel` | `"error"` | Level log core (`trace`–`silent`) |
154
+ | `socketConfig` | `{}` | Diteruskan langsung ke socket koneksi core |
155
+ | `owners` | `[]` | Daftar JID yang dianggap owner bot |
156
+ | `defaultCooldown` | `0` | Cooldown default (ms) untuk command yang tidak mengatur cooldown sendiri |
157
+ | `cooldownMessage` | – | Pesan saat kena cooldown — string atau `(ctx, remainingMs) => string` |
158
+ | `antiSpam` | `{ enabled:false, windowMs:5000, maxMessages:5 }` | Konfigurasi anti-spam |
159
+ | `permissionMessages` | – | Pesan khusus untuk penolakan `owner`/`admin` |
160
+ | `logger` | `{ enabled:true, showPn:true }` | Konfigurasi logger bawaan |
161
+ | `reconnectBaseDelay` / `reconnectMaxDelay` | `1000` / `30000` | Delay awal & batas atas (ms) untuk exponential backoff |
162
+ | `configDir` | cwd | Folder pencarian `config.bt` |
71
163
 
72
- ### `bot.use(fn)`
73
- Registers a middleware that runs before every command dispatch. Return `false` to stop the chain.
164
+ ### `bot.command()` / `bot.use()` / `bot.on()`
74
165
 
75
- ### `bot.on(event, handler)`
76
- Framework-level events: `"ready"`, `"message"` (every incoming message, command or not), `"disconnect"`, `"unknownCommand"`.
166
+ | Method | Deskripsi |
167
+ |---|---|
168
+ | `bot.command(name, handler, opts?)` | Mendaftarkan command. `handler` menerima sebuah [`Context`](#context). `opts.aliases` dan `opts.description` opsional. |
169
+ | `bot.use(fn)` | Mendaftarkan middleware yang berjalan sebelum setiap dispatch command. `return false` untuk menghentikan chain. |
170
+ | `bot.on(event, handler)` | Event level-framework: `"ready"`, `"message"` (setiap pesan masuk, command maupun bukan), `"disconnect"`, `"unknownCommand"`. |
77
171
 
78
172
  ### `Context`
79
- | Property/Method | Description |
173
+
174
+ **Properti inti**
175
+
176
+ | Properti | Deskripsi |
80
177
  |---|---|
81
- | `ctx.text` | Full message text |
82
- | `ctx.command` / `ctx.args` | Parsed command name + arguments |
83
- | `ctx.sender` / `ctx.from` | Sender JID / chat JID |
84
- | `ctx.isGroup` | Whether the message is from a group |
85
- | `ctx.reply(text, opts?)` | Reply, quoting the original message |
86
- | `ctx.send(content, opts?)` | Send any message content to the chat |
87
- | `ctx.react(emoji)` | React to the triggering message |
178
+ | `ctx.text` | Teks polos terbaik yang bisa diambil (isi pesan atau caption) |
179
+ | `ctx.command` / `ctx.args` | Nama command & argumen hasil parsing |
180
+ | `ctx.sender` / `ctx.from` | JID pengirim / JID chat |
181
+ | `ctx.isGroup` / `ctx.chatType` | Apakah dari grup, dan `"group" \| "channel" \| "broadcast" \| "private"` |
182
+ | `ctx.type` | Tipe pesan (lihat di bawah) |
183
+ | `ctx.mentions` / `ctx.isMentioned(jid)` | JID yang di-*mention* dalam pesan |
184
+ | `ctx.quoted` | Pesan yang sedang dibalas, sebagai [`Quoted`](#quoted) — atau `null` |
185
+ | `ctx.isOwner` / `ctx.pushName` | Apakah pengirim terdaftar di `owners`, dan nama tampilannya |
186
+
187
+ **Tipe pesan** — `ctx.type` salah satu dari: `text`, `image`, `video`, `audio` (`ctx.isPtt` untuk voice note), `sticker`, `document`, `contact`, `contacts`, `location`, `liveLocation`, `poll`, `pollUpdate`, `reaction`, `buttonsResponse`, `listResponse`, `templateButtonReply`, `interactiveResponse`, `groupInvite`, `product`, `event`, `protocol` (edit/hapus — lihat `ctx.protocol.kind`), `unsupported`, `unknown`. Pembungkus *ephemeral* dan *view-once* dibongkar otomatis, jadi `ctx.type` selalu mencerminkan isi pesan yang sesungguhnya.
188
+
189
+ Field khusus per tipe terisi otomatis: `ctx.mimetype`, `ctx.caption`, `ctx.fileName`, `ctx.isViewOnce`, `ctx.location`, `ctx.contact` / `ctx.contacts`, `ctx.poll`, `ctx.buttonReply`, `ctx.listReply`, `ctx.groupInvite`, `ctx.protocol`.
190
+
191
+ **Mengirim pesan**
192
+
193
+ | Method | Deskripsi |
194
+ |---|---|
195
+ | `ctx.reply(text, opts?)` | Balas, mengutip (*quote*) pesan asal |
196
+ | `ctx.send(content, opts?)` | Kirim konten pesan apa pun yang kompatibel dengan core |
197
+ | `ctx.sendCard({ text?, title?, description?, thumbnail, url, highQuality? })` | Kartu link-preview ringan — lihat JSDoc di `sending/text.js` untuk detail |
198
+ | `ctx.sendImage(source, opts?)` | `source`: Buffer, path file, URL http(s), atau `{url}`/`{stream}` |
199
+ | `ctx.sendVideo(source, opts?)` | `opts.gifPlayback: true` untuk diputar seperti GIF |
200
+ | `ctx.sendAudio(source, opts?)` | `opts.ptt: true` untuk kirim sebagai voice note |
201
+ | `ctx.sendDocument(source, opts?)` | `opts.fileName`, `opts.mimetype` |
202
+ | `ctx.sendSticker(source, opts?)` | |
203
+ | `ctx.sendStickerPack({ name, publisher, description, stickers, cover }, opts?)` | Kirim sekumpulan stiker sebagai satu paket |
204
+ | `ctx.sendAlbum(items, opts?)` | Galeri berisi beberapa gambar/video sekaligus |
205
+ | `ctx.sendContact(contacts, opts?)` | Terima satu kontak atau array kontak |
206
+ | `ctx.sendLocation({ latitude, longitude, name?, address? })` | |
207
+ | `ctx.sendPoll({ name, options, selectableCount? })` | |
208
+ | `ctx.sendButtons(content, buttons, opts?)` | Tombol interaktif native (reply/url/copy/list) |
209
+ | `ctx.sendListMenu(content, sections, opts?)` | Menu list native (`single_select`) |
210
+ | `ctx.sendTable(title, headers, rows, opts?)` / `sendTableV2(table, opts?)` | Tabel kaya (V1/V2) |
211
+ | `ctx.sendRichList(title, items, opts?)` | List key/value tanpa judul kolom |
212
+ | `ctx.sendCodeBlock(code, opts?)` / `sendCodeBlockV2(code, opts?)` | Code block dengan syntax highlighting |
213
+ | `ctx.sendLink(text, links, opts?)` / `sendLinkV2(text, links, opts?)` | Teks dengan tautan inline |
214
+ | `ctx.sendRichMessage(submessages, opts?)` | Pesan gabungan dari beberapa submessage |
215
+ | `ctx.sendPayment({ amount, currency, note, from }, opts?)` | Permintaan pembayaran |
216
+ | `ctx.sendEvent({ name, description, startTime, endTime, location }, opts?)` | Undangan event kalender |
217
+ | `ctx.sendPollResult({ name, votes }, opts?)` | Hasil akhir poll |
218
+ | `ctx.sendProduct(product, opts?)` | Kartu produk katalog |
219
+ | `ctx.sendStatusMention(content, jids)` | Post Status (story) yang me-*mention* kontak tertentu |
220
+
221
+ **Unduh media**
222
+
223
+ | Method | Deskripsi |
224
+ |---|---|
225
+ | `ctx.download(opts?)` | Buffer (atau stream dengan `{asStream:true}`) — melempar error jika `!ctx.isMedia` |
226
+ | `ctx.saveMedia(filePath, opts?)` | Stream langsung ke disk, mengembalikan path file |
227
+
228
+ **Manajemen pesan**
229
+
230
+ | Method | Deskripsi |
231
+ |---|---|
232
+ | `ctx.react(emoji)` / `ctx.removeReaction()` | Beri / hapus reaksi bot |
233
+ | `ctx.editMessage(target, content)` | Edit pesan bot sendiri yang sudah terkirim — `target` adalah hasil dari `ctx.reply()`/`ctx.send()` |
234
+ | `ctx.deleteMessage(target?)` | Hapus untuk semua orang (pesan bot sendiri, atau pesan siapa pun jika bot adalah admin grup). Default: pesan yang memicu command |
235
+ | `ctx.edit(text)` / `ctx.delete()` | Shortcut yang langsung menyasar pesan pemicu itu sendiri |
236
+ | `ctx.pin(time?)` / `ctx.unpin()` | Pin/unpin pesan pemicu |
237
+ | `ctx.star(starred?)` | Star/unstar pesan pemicu |
238
+ | `ctx.forward(toJid, opts?)` | Teruskan pesan pemicu ke chat lain |
239
+
240
+ **Helper grup**: `ctx.isGroupAdmin()`, `ctx.getGroupName()`, `ctx.describeChat()`.
241
+
242
+ ### `Quoted`
243
+
244
+ `ctx.quoted` (jika ada) mencerminkan bagian-bagian relevan dari `Context` untuk pesan yang sedang dibalas: `type`, `text`, `mimetype`, `caption`, `isMedia`, `sender`/`senderNumber`, ditambah `.download()`, `.saveMedia(path)`, `.react(emoji)`, dan `.delete()`. Berguna untuk command bergaya "reply gambar dengan `!sticker`":
245
+
246
+ ```js
247
+ bot.command("sticker", async (ctx) => {
248
+ const target = ctx.type === "image" ? ctx : ctx.quoted;
249
+ if (target?.type !== "image") return ctx.reply("Reply gambar dengan !sticker");
250
+ await ctx.sendSticker(await target.download());
251
+ });
252
+ ```
253
+
254
+ ## Memperbarui Core yang Di-*vendor*
255
+
256
+ Karena core-nya di-*vendor* (bukan dependensi npm), ia tidak akan ter-*update* otomatis. Kalau suatu saat ingin menarik perbaikan protokol dari upstream, unduh source-nya, bandingkan (*diff*) dengan `vendor/core/`, lalu gabungkan perubahan secara manual — dengan begitu kamu tetap punya kendali penuh atas perubahan apa saja yang masuk ke framework-mu.
88
257
 
89
- ## Dropping down to the raw connection
258
+ ## Turun ke Koneksi Mentah
90
259
 
91
260
  ```js
92
261
  bot.sock.ev.on("group-participants.update", (update) => {
93
- // raw core connection event
262
+ // event koneksi mentah dari core
94
263
  });
95
264
  ```
96
265
 
97
- ## License
266
+ ## Lisensi
98
267
 
99
- MIT — see [LICENSE](./LICENSE). Third-party code vendored under `vendor/core/` retains its original license — see [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).
268
+ MIT — lihat [LICENSE](./LICENSE). Kode pihak ketiga yang di-*vendor* di `vendor/core/` tetap tunduk pada lisensi aslinya — lihat [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).
100
269
 
101
- **Note:** Use responsibly and in accordance with WhatsApp's Terms of Service. This project is not affiliated with WhatsApp Inc. or Meta Platforms, Inc.
270
+ **Catatan:** Gunakan secara bertanggung jawab dan sesuai Syarat & Ketentuan Layanan WhatsApp. Proyek ini tidak berafiliasi dengan WhatsApp Inc. atau Meta Platforms, Inc.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botify-wa",
3
- "version": "0.2.0",
3
+ "version": "0.6.0",
4
4
  "description": "Lightweight WhatsApp bot framework with plugin system, built-in middlewares, and CLI scaffolding.",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "scripts": {
19
19
  "start": "node examples/simple-bot.js",
20
- "dev": "node --watch examples/simple-bot.js"
20
+ "dev": "node --watch examples/simple-bot.js"
21
21
  },
22
22
  "keywords": [
23
23
  "whatsapp",
@@ -34,6 +34,7 @@
34
34
  "@cacheable/node-cache": "^1.4.0",
35
35
  "@hapi/boom": "^9.1.3",
36
36
  "async-mutex": "^0.5.0",
37
+ "axios": "^1.7.9",
37
38
  "fflate": "^0.8.0",
38
39
  "fluent-ffmpeg": "^2.1.3",
39
40
  "libsignal": "git+https://github.com/whiskeysockets/libsignal-node",
@@ -53,9 +54,17 @@
53
54
  "sharp": "^0.35.2"
54
55
  },
55
56
  "peerDependenciesMeta": {
56
- "audio-decode": { "optional": true },
57
- "jimp": { "optional": true },
58
- "link-preview-js": { "optional": true },
59
- "sharp": { "optional": true }
57
+ "audio-decode": {
58
+ "optional": true
59
+ },
60
+ "jimp": {
61
+ "optional": true
62
+ },
63
+ "link-preview-js": {
64
+ "optional": true
65
+ },
66
+ "sharp": {
67
+ "optional": true
68
+ }
60
69
  }
61
70
  }
package/src/Bot.js CHANGED
@@ -1,16 +1,11 @@
1
- import makeWASocket, {
2
- DisconnectReason,
3
- useMultiFileAuthState,
4
- } from "../vendor/core/lib/index.js";
5
- import qrcode from "qrcode-terminal";
6
- import pino from "pino";
7
1
  import { PluginManager } from "./PluginManager.js";
8
- import { Context } from "./Context.js";
9
2
  import { loadConfig, mergeConfig } from "./config/index.js";
10
- import { logger } from "./middlewares/logger.js";
11
- import { cooldown } from "./middlewares/cooldown.js";
12
- import { permission } from "./middlewares/permission.js";
13
- import { antiSpam } from "./middlewares/antiSpam.js";
3
+ import {
4
+ registerBuiltinsMethods,
5
+ connectionMethods,
6
+ dispatchMethods,
7
+ reconnectMethods,
8
+ } from "./bot/index.js";
14
9
 
15
10
  /**
16
11
  * Bot
@@ -27,6 +22,13 @@ import { antiSpam } from "./middlewares/antiSpam.js";
27
22
  *
28
23
  * Everything low-level (encryption, sockets, WA protocol) lives in
29
24
  * vendor/core — Botify only adds structure on top.
25
+ *
26
+ * This class itself only owns construction + the public API + the small
27
+ * `_emit`/`_handleError` glue shared by every mixin below — the actual
28
+ * connection lifecycle, message dispatch, built-in middleware setup, and
29
+ * reconnect backoff are organized by concern into `./bot/*.js` and mixed
30
+ * onto the prototype below. See `./bot/index.js` for the full map of
31
+ * which file owns which methods.
30
32
  */
31
33
  export class Bot {
32
34
  /**
@@ -116,48 +118,8 @@ export class Bot {
116
118
  this._reconnectTimer = null;
117
119
 
118
120
  // ── 2. Register built-in middlewares in the correct order ────────────────
119
- //
120
- // Order matters:
121
- // 1. logger — log first so every attempt is recorded, even blocked ones
122
- // 2. antiSpam — global rate limit before any per-command check
123
- // 3. permission — owner / admin gate
124
- // 4. cooldown — per-user per-command throttle
125
- // (user middlewares added via bot.use() run after all of the above)
126
-
127
- this.plugins.use(
128
- logger({
129
- enabled: this.options.logger.enabled,
130
- showPn: this.options.logger.showPn,
131
- logFn: this.options.logger.logFn,
132
- format: this.options.logger.format,
133
- })
134
- );
135
-
136
- if (this.options.antiSpam.enabled) {
137
- this.plugins.use(
138
- antiSpam({
139
- windowMs: this.options.antiSpam.windowMs,
140
- maxMessages: this.options.antiSpam.maxMessages,
141
- message: this.options.antiSpam.message,
142
- })
143
- );
144
- }
145
-
146
- this.plugins.use(
147
- permission({
148
- ownerMessage: this.options.permissionMessages.owner,
149
- adminMessage: this.options.permissionMessages.admin,
150
- emitEvent: (ctx, reason) => this._emit("noPermission", ctx, reason),
151
- })
152
- );
153
-
154
- this.plugins.use(
155
- cooldown({
156
- defaultCooldown: this.options.defaultCooldown,
157
- message: this.options.cooldownMessage,
158
- emitEvent: (ctx, remainingMs) => this._emit("cooldown", ctx, remainingMs),
159
- })
160
- );
121
+ // (logger → antiSpam → permission → cooldown; see ./bot/register-builtins.js)
122
+ this._registerBuiltinMiddlewares();
161
123
  }
162
124
 
163
125
  // ── Public API ─────────────────────────────────────────────────────────────
@@ -200,7 +162,7 @@ export class Bot {
200
162
  return this;
201
163
  }
202
164
 
203
- // ── Internals ──────────────────────────────────────────────────────────────
165
+ // ── Internals shared by every ./bot/*.js mixin ────────────────────────────
204
166
 
205
167
  _emit(event, ...args) {
206
168
  for (const fn of this._listeners.get(event) ?? []) fn(...args);
@@ -219,109 +181,14 @@ export class Bot {
219
181
  }
220
182
  }
221
183
  }
222
-
223
- /** Boot the bot: load/create session, connect, wire up listeners. */
224
- async start() {
225
- if (this._reconnectTimer) {
226
- clearTimeout(this._reconnectTimer);
227
- this._reconnectTimer = null;
228
- }
229
-
230
- const { state, saveCreds } = await useMultiFileAuthState(
231
- this.options.sessionPath
232
- );
233
-
234
- const logger_ =
235
- this.options.socketConfig.logger ??
236
- pino({ level: this.options.logLevel });
237
-
238
- this.sock = makeWASocket({
239
- auth: state,
240
- ...this.options.socketConfig,
241
- logger: logger_,
242
- });
243
-
244
- this.sock.ev.on("creds.update", saveCreds);
245
-
246
- this.sock.ev.on("connection.update", (update) => {
247
- const { connection, lastDisconnect, qr } = update;
248
-
249
- if (qr) {
250
- if (this.options.printQR) {
251
- qrcode.generate(qr, { small: true });
252
- console.log("Scan the QR code above with WhatsApp (Linked Devices).");
253
- }
254
- this._emit("qr", qr);
255
- }
256
-
257
- if (connection === "open") {
258
- this._reconnectAttempts = 0;
259
- this._emit("ready", this.sock);
260
- }
261
-
262
- if (connection === "close") {
263
- const statusCode = lastDisconnect?.error?.output?.statusCode;
264
- const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
265
-
266
- if (shouldReconnect) {
267
- const delay = Math.min(
268
- this.options.reconnectBaseDelay * 2 ** this._reconnectAttempts,
269
- this.options.reconnectMaxDelay
270
- );
271
- this._reconnectAttempts++;
272
-
273
- this._emit("disconnect", {
274
- statusCode,
275
- willReconnect: true,
276
- reconnectDelayMs: delay,
277
- attempt: this._reconnectAttempts,
278
- });
279
-
280
- this._reconnectTimer = setTimeout(() => this.start(), delay);
281
- } else {
282
- this._emit("disconnect", { statusCode, willReconnect: false });
283
- }
284
- }
285
- });
286
-
287
- this.sock.ev.on("messages.upsert", async ({ messages, type }) => {
288
- if (type !== "notify") return;
289
-
290
- for (const raw of messages) {
291
- if (!raw.message) continue;
292
-
293
- const ctx = new Context(this.sock, raw, {
294
- prefix: this.options.prefix,
295
- owners: this.options.owners,
296
- });
297
-
298
- this._emit("message", ctx);
299
-
300
- if (!ctx.command) continue;
301
-
302
- const result = await this.plugins.dispatch(ctx.command, ctx);
303
-
304
- switch (result.status) {
305
- case "not_found":
306
- this._emit("unknownCommand", ctx);
307
- break;
308
- case "error":
309
- await this._handleError(result.error, ctx);
310
- break;
311
- // "ok" and "stopped" need no further action
312
- }
313
- }
314
- });
315
-
316
- return this.sock;
317
- }
318
-
319
- /** Gracefully close the socket. */
320
- async stop() {
321
- if (this._reconnectTimer) {
322
- clearTimeout(this._reconnectTimer);
323
- this._reconnectTimer = null;
324
- }
325
- await this.sock?.end?.(undefined);
326
- }
327
184
  }
185
+
186
+ // ── Assemble the prototype from focused, single-purpose mixins ───────────
187
+ // Order is presentation-only; grouping mirrors the file layout under ./bot/.
188
+ Object.assign(
189
+ Bot.prototype,
190
+ registerBuiltinsMethods, // _registerBuiltinMiddlewares
191
+ connectionMethods, // start, stop, _handleConnectionUpdate
192
+ dispatchMethods, // _handleMessagesUpsert, _dispatchIncoming
193
+ reconnectMethods, // _handleDisconnect, _nextReconnectDelay, _clearReconnectTimer
194
+ );