botify-wa 0.2.0 → 0.4.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.4.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/Context.js CHANGED
@@ -1,8 +1,34 @@
1
+ import {
2
+ deriveMessageState,
3
+ textSendingMethods,
4
+ mediaSendingMethods,
5
+ interactiveSendingMethods,
6
+ richSendingMethods,
7
+ otherSendingMethods,
8
+ mediaTransferMethods,
9
+ messageActionMethods,
10
+ groupInfoMethods,
11
+ } from "./context/index.js";
12
+
1
13
  /**
2
14
  * Context
3
15
  * -------
4
16
  * A friendly, per-message object passed to every command/middleware.
5
17
  * Wraps the raw connection message + gives shortcuts like ctx.reply().
18
+ *
19
+ * Handles every message type the vendored core supports (text, image,
20
+ * video, audio/voice-note, sticker, document, contact(s), location,
21
+ * live location, polls, reactions, button/list replies, group invites,
22
+ * products, events, and protocol messages like edits/deletes) — see
23
+ * ctx.type. Also exposes media download, rich media sending (buttons,
24
+ * list menus, albums, sticker packs, AI-style rich tables/code blocks/
25
+ * links, payments, events, poll results, product cards, status mentions),
26
+ * and message-management actions (edit, delete, react, pin, star, forward).
27
+ *
28
+ * This class itself only owns construction — the ~40 instance methods are
29
+ * organized by concern into `./context/*.js` and mixed onto the prototype
30
+ * below. See `./context/index.js` for the full map of which file owns
31
+ * which methods.
6
32
  */
7
33
  export class Context {
8
34
  /**
@@ -15,53 +41,7 @@ export class Context {
15
41
  this.raw = rawMessage;
16
42
  this.botConfig = botConfig;
17
43
 
18
- const key = rawMessage.key;
19
-
20
- // WhatsApp is rolling out "LID" (Linked ID, @lid) as an alternate,
21
- // non-phone-number identifier — mainly in DMs and communities, for
22
- // privacy. When that's active, the "primary" field (participant /
23
- // remoteJid) may hold the @lid form while the real phone-number JID
24
- // sits in the matching "Alt" field (participantAlt / remoteJidAlt),
25
- // or vice versa. We fall back through all four so `sender`/`from`
26
- // are never silently empty just because WhatsApp picked a different
27
- // field for this account/chat.
28
- this.from = key.remoteJid || key.remoteJidAlt || "";
29
- this.sender =
30
- key.participant || key.remoteJid || key.participantAlt || key.remoteJidAlt || "";
31
- this.fromMe = !!key.fromMe;
32
-
33
- /**
34
- * Kind of chat this message came from:
35
- * "group" | "channel" (newsletter) | "broadcast" | "private"
36
- */
37
- this.chatType = detectChatType(this.from);
38
- /** Convenience boolean, derived from chatType (kept for backwards compat). */
39
- this.isGroup = this.chatType === "group";
40
-
41
- /** Display name of the sender as WhatsApp reports it (may be stale/unset). */
42
- this.pushName = rawMessage.pushName || "Unknown";
43
-
44
- /** The sender's @lid identifier, if WhatsApp provided one — else null. */
45
- this.senderLid = [key.participant, key.participantAlt, key.remoteJid, key.remoteJidAlt]
46
- .find((jid) => isLid(jid)) ?? null;
47
- /** The sender's real phone-number JID (@s.whatsapp.net), if available — else null. */
48
- this.senderPn = [key.participant, key.participantAlt, key.remoteJid, key.remoteJidAlt]
49
- .find((jid) => isPn(jid)) ?? null;
50
-
51
- /**
52
- * Sender's phone number with no @domain suffix, e.g. "6281234567890".
53
- * Prefers the real phone-number JID over a LID (a LID's numeric part
54
- * is NOT a phone number, so it's only used here as a last resort).
55
- */
56
- this.senderNumber = (this.senderPn ?? this.senderLid ?? this.sender).split("@")[0] ?? "";
57
-
58
- this.text = extractText(rawMessage);
59
- const parsed = parseCommand(this.text, botConfig.prefix);
60
- this.command = parsed.command;
61
- this.args = parsed.args;
62
-
63
- /** Whether the sender is listed in Bot({ owners: [...] }). */
64
- this.isOwner = (botConfig.owners ?? []).includes(this.sender);
44
+ Object.assign(this, deriveMessageState(sock, rawMessage, botConfig));
65
45
 
66
46
  /**
67
47
  * Cache for the group metadata fetch, shared by isGroupAdmin() and
@@ -71,115 +51,19 @@ export class Context {
71
51
  */
72
52
  this._groupMetadataCache = undefined;
73
53
  }
74
-
75
- /** Reply in the same chat, quoting the triggering message. */
76
- async reply(text, opts = {}) {
77
- return this.sock.sendMessage(
78
- this.from,
79
- { text, ...opts },
80
- { quoted: this.raw }
81
- );
82
- }
83
-
84
- /** Send any core-compatible message content to the same chat. */
85
- async send(content, opts = {}) {
86
- return this.sock.sendMessage(this.from, content, opts);
87
- }
88
-
89
- /** React to the triggering message with an emoji. */
90
- async react(emoji) {
91
- return this.sock.sendMessage(this.from, {
92
- react: { text: emoji, key: this.raw.key },
93
- });
94
- }
95
-
96
- /**
97
- * Fetches (and caches) this chat's group metadata. Returns `null` outside
98
- * of groups, or if the fetch fails (e.g. bot was removed from the group).
99
- */
100
- async _getGroupMetadata() {
101
- if (this.chatType !== "group") return null;
102
- if (this._groupMetadataCache !== undefined) return this._groupMetadataCache;
103
-
104
- try {
105
- this._groupMetadataCache = await this.sock.groupMetadata(this.from);
106
- } catch {
107
- this._groupMetadataCache = null;
108
- }
109
- return this._groupMetadataCache;
110
- }
111
-
112
- /**
113
- * Whether the sender is an admin (or superadmin) of the current group.
114
- * Always `false` outside of groups.
115
- */
116
- async isGroupAdmin() {
117
- const metadata = await this._getGroupMetadata();
118
- if (!metadata) return false;
119
-
120
- const ids = [this.sender, this.senderLid, this.senderPn].filter(Boolean);
121
- const participant = metadata.participants.find((p) => ids.includes(p.id));
122
- return (
123
- !!participant &&
124
- (participant.admin === "admin" || participant.admin === "superadmin")
125
- );
126
- }
127
-
128
- /**
129
- * The current group's display name (its "subject"). Returns `null`
130
- * outside of groups or if metadata couldn't be fetched.
131
- */
132
- async getGroupName() {
133
- const metadata = await this._getGroupMetadata();
134
- return metadata?.subject ?? null;
135
- }
136
-
137
- /**
138
- * A human-readable one-liner describing where this message came from,
139
- * handy for logging: e.g. `group "Koalisi Community"` or `private chat`.
140
- */
141
- async describeChat() {
142
- if (this.chatType === "group") {
143
- const name = await this.getGroupName();
144
- return `group "${name ?? this.from}"`;
145
- }
146
- if (this.chatType === "channel") return "channel";
147
- if (this.chatType === "broadcast") return "broadcast list";
148
- return "private chat";
149
- }
150
- }
151
-
152
- function isLid(jid) {
153
- return typeof jid === "string" && jid.endsWith("@lid");
154
- }
155
-
156
- function isPn(jid) {
157
- return typeof jid === "string" && jid.endsWith("@s.whatsapp.net");
158
54
  }
159
55
 
160
- function detectChatType(jid) {
161
- if (jid.endsWith("@g.us")) return "group";
162
- if (jid.endsWith("@newsletter")) return "channel";
163
- if (jid.endsWith("@broadcast")) return "broadcast";
164
- return "private";
165
- }
166
-
167
- function extractText(msg) {
168
- const m = msg.message;
169
- if (!m) return "";
170
- return (
171
- m.conversation ??
172
- m.extendedTextMessage?.text ??
173
- m.imageMessage?.caption ??
174
- m.videoMessage?.caption ??
175
- ""
176
- );
177
- }
178
-
179
- function parseCommand(text, prefix) {
180
- if (!text || !text.startsWith(prefix)) {
181
- return { command: null, args: [] };
182
- }
183
- const [command, ...args] = text.slice(prefix.length).trim().split(/\s+/);
184
- return { command: command?.toLowerCase() ?? null, args };
185
- }
56
+ // ── Assemble the prototype from focused, single-purpose mixins ───────────
57
+ // Order is presentation-only (this is how the methods will iterate/print);
58
+ // grouping mirrors the file layout under ./context/.
59
+ Object.assign(
60
+ Context.prototype,
61
+ textSendingMethods, // reply, send, sendCard
62
+ mediaSendingMethods, // sendImage, sendVideo, sendAudio, sendDocument, sendSticker, sendStickerPack, sendAlbum
63
+ interactiveSendingMethods, // sendButtons, sendListMenu
64
+ richSendingMethods, // sendTable(V2), sendRichList, sendCodeBlock(V2), sendLink(V2), sendRichMessage
65
+ otherSendingMethods, // sendContact, sendLocation, sendPoll, sendPayment, sendEvent, sendPollResult, sendProduct, sendStatusMention
66
+ mediaTransferMethods, // download, saveMedia
67
+ messageActionMethods, // react, removeReaction, edit(Message), delete(Message), pin, unpin, star, forward, isMentioned
68
+ groupInfoMethods, // isGroupAdmin, getGroupName, describeChat
69
+ );