botify-wa 0.4.0 → 1.0.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
@@ -5,6 +5,8 @@
5
5
  Di atas core tersebut, Botify menambahkan struktur yang benar-benar dibutuhkan hampir semua bot:
6
6
 
7
7
  - **Sistem command** — `bot.command("ping", handler)`, tanpa perlu parsing manual event koneksi mentah
8
+ - **Sub-command** — `bot.command("admin", handler, { admin: true }).sub("ban", banHandler)` untuk pola `!admin ban`, `!admin kick`, dengan pewarisan `owner`/`admin`/`cooldown` dari command induknya
9
+ - **Kategori command** — `opts.category` untuk grouping command, dibaca otomatis oleh template `!menu`
8
10
  - **Middleware** — `bot.use(fn)`
9
11
  - **Objek `Context`** yang ramah pakai — `ctx.reply()`, `ctx.args`, `ctx.sender`, dst — menggantikan objek pesan mentah
10
12
  - **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*
@@ -101,7 +103,7 @@ npx botify-wa help # tampilkan bantuan
101
103
  npx botify-wa version # tampilkan versi framework
102
104
  ```
103
105
 
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.
106
+ Perintah `build` akan menyalin template dari `src/templates/` (termasuk contoh plugin `ping`, `info`, `menu`, `admin`, dan `config.bt`) ke folder proyek baru. Aman dijalankan berulang kali — file yang sudah ada tidak akan ditimpa.
105
107
 
106
108
  ## Konfigurasi (`config.bt`)
107
109
 
@@ -165,10 +167,26 @@ Semua key bersifat opsional — key yang tidak diisi otomatis memakai nilai defa
165
167
 
166
168
  | Method | Deskripsi |
167
169
  |---|---|
168
- | `bot.command(name, handler, opts?)` | Mendaftarkan command. `handler` menerima sebuah [`Context`](#context). `opts.aliases` dan `opts.description` opsional. |
170
+ | `bot.command(name, handler, opts?)` | Mendaftarkan command. `handler` menerima sebuah [`Context`](#context). `opts.aliases`, `opts.description`, `opts.category` (grouping untuk `!menu`), `opts.cooldown`, `opts.owner`, `opts.admin` semuanya opsional. Mengembalikan `CommandBuilder` — chain `.sub()` untuk sub-command (lihat di bawah), atau abaikan return value-nya kalau tidak butuh. |
169
171
  | `bot.use(fn)` | Mendaftarkan middleware yang berjalan sebelum setiap dispatch command. `return false` untuk menghentikan chain. |
170
172
  | `bot.on(event, handler)` | Event level-framework: `"ready"`, `"message"` (setiap pesan masuk, command maupun bukan), `"disconnect"`, `"unknownCommand"`. |
171
173
 
174
+ **Sub-command**
175
+
176
+ `bot.command()` mengembalikan `CommandBuilder`, yang punya method `.sub(name, handler, opts?)` untuk mendaftarkan sub-command bertingkat (`!admin ban`, `!admin kick`):
177
+
178
+ ```js
179
+ bot.command("admin", async (ctx) => {
180
+ await ctx.reply("Gunakan: !admin ban @user atau !admin kick @user");
181
+ }, { category: "Admin", admin: true }) // admin: true berlaku juga untuk sub di bawah
182
+ .sub("ban", async (ctx) => { /* ... */ }, { description: "Ban member" })
183
+ .sub("kick", async (ctx) => { /* ... */ }, { description: "Kick member", cooldown: 10_000 });
184
+ ```
185
+
186
+ Sub-command **mewarisi** `owner`/`admin`/`cooldown` dari command induknya, kecuali di-set ulang sendiri di `opts` milik sub tersebut (lihat `kick` yang override cooldown di atas). Di dalam handler, `ctx.args` sudah otomatis dipotong melewati nama sub-command (`!admin ban 628xxx` → `ctx.args` berisi `["628xxx"]`), dan `ctx.subcommand` berisi nama sub yang cocok (`"ban"`) atau `null` kalau tidak ada sub yang match.
187
+
188
+ > ⚠️ **Breaking change kecil**: sebelumnya `bot.command()` mengembalikan `this` (Bot), sehingga bisa dirangkai `bot.command().command()`. Sekarang ia mengembalikan `CommandBuilder`, jadi pola chaining itu tidak berlaku lagi — panggil `bot.command()` lagi sebagai statement terpisah (semua template bawaan sudah memakai pola ini).
189
+
172
190
  ### `Context`
173
191
 
174
192
  **Properti inti**
@@ -182,7 +200,14 @@ Semua key bersifat opsional — key yang tidak diisi otomatis memakai nilai defa
182
200
  | `ctx.type` | Tipe pesan (lihat di bawah) |
183
201
  | `ctx.mentions` / `ctx.isMentioned(jid)` | JID yang di-*mention* dalam pesan |
184
202
  | `ctx.quoted` | Pesan yang sedang dibalas, sebagai [`Quoted`](#quoted) — atau `null` |
203
+ | `ctx.repliedToBot` | `true` kalau `ctx.quoted` adalah pesan yang dikirim bot sendiri |
185
204
  | `ctx.isOwner` / `ctx.pushName` | Apakah pengirim terdaftar di `owners`, dan nama tampilannya |
205
+ | `ctx.id` | ID unik pesan ini (`key.id`) — untuk dedup/logging eksternal |
206
+ | `ctx.timestamp` | Waktu pesan dikirim, unix timestamp dalam **detik** (`null` kalau tidak ada) |
207
+ | `ctx.botJid` | JID bot sendiri (suffix device sudah dibersihkan), `null` sebelum tersambung |
208
+ | `ctx.isForwarded` / `ctx.forwardingScore` | Apakah pesan ditandai *forwarded*, dan sudah berapa kali di-forward |
209
+ | `ctx.expiration` | Durasi *disappearing message* chat ini dalam detik (`0` = nonaktif) |
210
+ | `ctx.raw` | Objek `WebMessageInfo` mentah dari core — *escape hatch* kalau butuh field yang belum dibungkus Botify |
186
211
 
187
212
  **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
213
 
@@ -237,11 +262,11 @@ Field khusus per tipe terisi otomatis: `ctx.mimetype`, `ctx.caption`, `ctx.fileN
237
262
  | `ctx.star(starred?)` | Star/unstar pesan pemicu |
238
263
  | `ctx.forward(toJid, opts?)` | Teruskan pesan pemicu ke chat lain |
239
264
 
240
- **Helper grup**: `ctx.isGroupAdmin()`, `ctx.getGroupName()`, `ctx.describeChat()`.
265
+ **Helper grup**: `ctx.isGroupAdmin()`, `ctx.isBotAdmin()` (apakah bot sendiri admin grup ini), `ctx.groupAdmins()` (array JID semua admin grup), `ctx.getGroupName()`, `ctx.describeChat()`.
241
266
 
242
267
  ### `Quoted`
243
268
 
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`":
269
+ `ctx.quoted` (jika ada) mencerminkan bagian-bagian relevan dari `Context` untuk pesan yang sedang dibalas: `type`, `text`, `mimetype`, `caption`, `isMedia`, `sender`/`senderNumber`, `fromMe` (juga tersedia sebagai `ctx.repliedToBot`), ditambah `.download()`, `.saveMedia(path)`, `.react(emoji)`, dan `.delete()`. Berguna untuk command bergaya "reply gambar dengan `!sticker`":
245
270
 
246
271
  ```js
247
272
  bot.command("sticker", async (ctx) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botify-wa",
3
- "version": "0.4.0",
3
+ "version": "1.0.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",
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,56 +118,33 @@ 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 ─────────────────────────────────────────────────────────────
164
126
 
165
- /** Register a command. Shortcut for bot.plugins.command(...) */
127
+ /**
128
+ * Register a command. Shortcut for bot.plugins.command(...).
129
+ *
130
+ * Returns a `CommandBuilder`, not the `Bot` instance — chain `.sub()` on
131
+ * it to add nested sub-commands (`!admin ban`, `!admin kick`):
132
+ *
133
+ * bot.command("admin", adminHandler, { admin: true })
134
+ * .sub("ban", banHandler)
135
+ * .sub("kick", kickHandler);
136
+ *
137
+ * Sub-commands inherit `owner`/`admin`/`cooldown` from the parent unless
138
+ * they override it themselves. `opts.category` groups commands for the
139
+ * built-in `!menu` template (e.g. `{ category: "Media" }`).
140
+ *
141
+ * Note: this used to return `this` (the `Bot`) for `.command().command()`
142
+ * chaining — call `bot.command()` again as a separate statement instead
143
+ * (every built-in template already does it this way).
144
+ * @returns {import('./PluginManager.js').CommandBuilder}
145
+ */
166
146
  command(name, handler, opts) {
167
- this.plugins.command(name, handler, opts);
168
- return this;
147
+ return this.plugins.command(name, handler, opts);
169
148
  }
170
149
 
171
150
  /**
@@ -200,7 +179,7 @@ export class Bot {
200
179
  return this;
201
180
  }
202
181
 
203
- // ── Internals ──────────────────────────────────────────────────────────────
182
+ // ── Internals shared by every ./bot/*.js mixin ────────────────────────────
204
183
 
205
184
  _emit(event, ...args) {
206
185
  for (const fn of this._listeners.get(event) ?? []) fn(...args);
@@ -219,109 +198,14 @@ export class Bot {
219
198
  }
220
199
  }
221
200
  }
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
201
  }
202
+
203
+ // ── Assemble the prototype from focused, single-purpose mixins ───────────
204
+ // Order is presentation-only; grouping mirrors the file layout under ./bot/.
205
+ Object.assign(
206
+ Bot.prototype,
207
+ registerBuiltinsMethods, // _registerBuiltinMiddlewares
208
+ connectionMethods, // start, stop, _handleConnectionUpdate
209
+ dispatchMethods, // _handleMessagesUpsert, _dispatchIncoming
210
+ reconnectMethods, // _handleDisconnect, _nextReconnectDelay, _clearReconnectTimer
211
+ );
@@ -7,22 +7,70 @@
7
7
  * Cooldown and permission logic have been moved to built-in middlewares
8
8
  * (src/middlewares/cooldown.js and src/middlewares/permission.js).
9
9
  * PluginManager's job is now strictly:
10
- * 1. Store command definitions.
11
- * 2. Attach the matched command entry to ctx._commandEntry so middlewares
12
- * can read per-command opts (cooldown ms, owner flag, admin flag).
10
+ * 1. Store command definitions (including nested sub-commands).
11
+ * 2. Resolve which entry (top-level command or matched sub-command)
12
+ * applies to this message, and attach it to ctx._commandEntry so
13
+ * middlewares can read its opts (cooldown ms, owner flag, admin flag)
14
+ * without caring whether it came from a top-level command or a sub.
13
15
  * 3. Run the middleware chain.
14
16
  * 4. Call the handler if the chain wasn't stopped.
15
17
  * 5. Return a typed result object — never throw.
16
18
  */
19
+
20
+ /**
21
+ * Returned by `PluginManager#command()` (and thus `bot.command()`) so
22
+ * nested sub-commands can be registered fluently:
23
+ *
24
+ * bot.command("admin", adminHandler, { admin: true })
25
+ * .sub("ban", banHandler, { description: "Ban member" })
26
+ * .sub("kick", kickHandler, { description: "Kick member" });
27
+ *
28
+ * Sub-commands inherit `owner`/`admin`/`cooldown` from their parent unless
29
+ * they explicitly override it in their own opts — so `!admin ban` is
30
+ * admin-only "for free" because `admin` declared `{ admin: true }`, but a
31
+ * sub can still loosen/tighten that individually.
32
+ *
33
+ * Note: `bot.command()` used to return the `Bot` instance itself (for
34
+ * `.command().command()`-style chaining). It now returns this builder
35
+ * instead — chain `.sub()` on it, or just call `bot.command()` again as a
36
+ * separate statement (this is how every built-in template already does it).
37
+ */
38
+ export class CommandBuilder {
39
+ constructor(manager, entry) {
40
+ this._manager = manager;
41
+ this._entry = entry;
42
+ }
43
+
44
+ /**
45
+ * Register a nested sub-command (e.g. "ban" under "admin" → `!admin ban`).
46
+ * @param {string} name
47
+ * @param {(ctx: import('./Context.js').Context) => any} handler
48
+ * @param {{
49
+ * description?: string,
50
+ * aliases?: string[],
51
+ * cooldown?: number,
52
+ * owner?: boolean,
53
+ * admin?: boolean
54
+ * }} [opts]
55
+ * @returns {CommandBuilder} itself, so `.sub()` calls can be chained
56
+ */
57
+ sub(name, handler, opts = {}) {
58
+ this._manager._registerSub(this._entry, name, handler, opts);
59
+ return this;
60
+ }
61
+ }
62
+
17
63
  export class PluginManager {
18
64
  constructor() {
19
65
  /**
20
66
  * @type {Map<string, {
21
67
  * handler: Function,
22
68
  * description?: string,
69
+ * category?: string | null,
23
70
  * cooldown?: number,
24
71
  * owner?: boolean,
25
- * admin?: boolean
72
+ * admin?: boolean,
73
+ * subcommands: Map<string, object>
26
74
  * }>}
27
75
  */
28
76
  this.commands = new Map();
@@ -31,31 +79,61 @@ export class PluginManager {
31
79
  }
32
80
 
33
81
  /**
34
- * Register a command.
82
+ * Register a top-level command.
35
83
  * @param {string} name - command name without prefix (e.g. "ping")
36
84
  * @param {(ctx: import('./Context.js').Context) => any} handler
37
85
  * @param {{
38
86
  * description?: string,
39
87
  * aliases?: string[],
88
+ * category?: string, // grouping label, e.g. "Media" — read by !menu
40
89
  * cooldown?: number, // ms — read by the cooldown middleware
41
90
  * owner?: boolean, // read by the permission middleware
42
91
  * admin?: boolean // read by the permission middleware
43
92
  * }} [opts]
93
+ * @returns {CommandBuilder} use `.sub()` on it to add nested sub-commands
44
94
  */
45
95
  command(name, handler, opts = {}) {
46
96
  const entry = {
47
97
  handler,
48
98
  description: opts.description ?? "",
99
+ category: opts.category ?? null,
49
100
  cooldown: opts.cooldown ?? 0,
50
101
  owner: opts.owner ?? false,
51
102
  admin: opts.admin ?? false,
103
+ subcommands: new Map(),
52
104
  };
53
105
 
54
106
  this.commands.set(name.toLowerCase(), entry);
55
107
  for (const alias of opts.aliases ?? []) {
56
108
  this.commands.set(alias.toLowerCase(), entry);
57
109
  }
58
- return this;
110
+ return new CommandBuilder(this, entry);
111
+ }
112
+
113
+ /**
114
+ * Internal: register a sub-command onto an existing parent entry.
115
+ * Not called directly — use the `CommandBuilder` returned by `command()`.
116
+ * @param {object} parentEntry
117
+ * @param {string} name
118
+ * @param {Function} handler
119
+ * @param {object} opts
120
+ */
121
+ _registerSub(parentEntry, name, handler, opts = {}) {
122
+ const subEntry = {
123
+ handler,
124
+ description: opts.description ?? "",
125
+ // Inherit gating/cooldown from the parent by default — `!admin` being
126
+ // admin-only should mean `!admin ban` is too, unless overridden here.
127
+ cooldown: opts.cooldown ?? parentEntry.cooldown ?? 0,
128
+ owner: opts.owner ?? parentEntry.owner ?? false,
129
+ admin: opts.admin ?? parentEntry.admin ?? false,
130
+ parent: parentEntry,
131
+ };
132
+
133
+ parentEntry.subcommands.set(name.toLowerCase(), subEntry);
134
+ for (const alias of opts.aliases ?? []) {
135
+ parentEntry.subcommands.set(alias.toLowerCase(), subEntry);
136
+ }
59
137
  }
60
138
 
61
139
  /**
@@ -68,7 +146,7 @@ export class PluginManager {
68
146
  return this;
69
147
  }
70
148
 
71
- /** List all unique registered commands (deduplicates aliases). */
149
+ /** List all unique registered top-level commands (deduplicates aliases). */
72
150
  list() {
73
151
  const seen = new Set();
74
152
  const out = [];
@@ -82,9 +160,49 @@ export class PluginManager {
82
160
  name: key,
83
161
  aliases,
84
162
  description: entry.description,
163
+ category: entry.category,
85
164
  cooldown: entry.cooldown,
86
165
  owner: entry.owner,
87
166
  admin: entry.admin,
167
+ subcommands: this._listSubcommands(entry),
168
+ });
169
+ }
170
+ return out;
171
+ }
172
+
173
+ /**
174
+ * Same as `list()`, but grouped by `category` (insertion-ordered).
175
+ * Commands without a `category` are grouped under `uncategorized`.
176
+ * @returns {Map<string, Array<object>>}
177
+ */
178
+ listByCategory() {
179
+ const grouped = new Map();
180
+ for (const cmd of this.list()) {
181
+ const cat = cmd.category ?? "uncategorized";
182
+ if (!grouped.has(cat)) grouped.set(cat, []);
183
+ grouped.get(cat).push(cmd);
184
+ }
185
+ return grouped;
186
+ }
187
+
188
+ /** Dedup + shape a parent entry's sub-commands the same way `list()` does. */
189
+ _listSubcommands(entry) {
190
+ if (!entry.subcommands || entry.subcommands.size === 0) return [];
191
+ const seen = new Set();
192
+ const out = [];
193
+ for (const [key, sub] of entry.subcommands.entries()) {
194
+ if (seen.has(sub)) continue;
195
+ seen.add(sub);
196
+ const aliases = [...entry.subcommands.entries()]
197
+ .filter(([k, v]) => v === sub && k !== key)
198
+ .map(([k]) => k);
199
+ out.push({
200
+ name: key,
201
+ aliases,
202
+ description: sub.description,
203
+ cooldown: sub.cooldown,
204
+ owner: sub.owner,
205
+ admin: sub.admin,
88
206
  });
89
207
  }
90
208
  return out;
@@ -94,6 +212,26 @@ export class PluginManager {
94
212
  return this.commands.has(name.toLowerCase());
95
213
  }
96
214
 
215
+ /**
216
+ * Given a top-level entry and the parsed args, figure out whether the
217
+ * first arg matches a registered sub-command. Doesn't mutate anything.
218
+ * @param {object} entry
219
+ * @param {string[]} args
220
+ * @returns {{ target: object, subcommand: string|null, args: string[] }}
221
+ */
222
+ _resolveTarget(entry, args) {
223
+ if (entry.subcommands.size && args.length) {
224
+ const subKey = args[0].toLowerCase();
225
+ const subEntry = entry.subcommands.get(subKey);
226
+ if (subEntry) {
227
+ return { target: subEntry, subcommand: subKey, args: args.slice(1) };
228
+ }
229
+ }
230
+ // No sub-command matched (or none registered) — dispatch to the
231
+ // top-level handler with args untouched, e.g. so it can print usage.
232
+ return { target: entry, subcommand: null, args };
233
+ }
234
+
97
235
  /**
98
236
  * Attach command entry, run middlewares, then call the handler.
99
237
  * Never throws — errors are caught and returned as a result object.
@@ -112,20 +250,35 @@ export class PluginManager {
112
250
  const entry = this.commands.get(key);
113
251
  if (!entry) return { status: "not_found" };
114
252
 
253
+ const resolved = this._resolveTarget(entry, ctx.args);
254
+
115
255
  try {
116
- // Attach command metadata to ctx so middlewares (cooldown, permission)
117
- // can read per-command options without needing a registry reference.
118
- ctx._commandEntry = entry;
256
+ // Attach the *resolved* entry (parent or matched sub) to ctx so
257
+ // middlewares (cooldown, permission) transparently apply the right
258
+ // gating/cooldown, whether this is "!admin" or "!admin ban".
259
+ ctx._commandEntry = resolved.target;
260
+ // Exposed for handlers/middlewares/logging: null when no sub matched.
261
+ ctx.subcommand = resolved.subcommand;
119
262
 
120
263
  for (const mw of this.middlewares) {
121
264
  const result = await mw(ctx);
122
265
  if (result === false) return { status: "stopped" };
123
266
  }
124
267
 
125
- await entry.handler(ctx);
268
+ // Only shift args past the matched sub-command name right before
269
+ // calling the handler — built-in middlewares (e.g. the logger) still
270
+ // see ctx.args exactly as typed, sub-command name included.
271
+ const originalArgs = ctx.args;
272
+ if (resolved.subcommand) ctx.args = resolved.args;
273
+ try {
274
+ await resolved.target.handler(ctx);
275
+ } finally {
276
+ ctx.args = originalArgs;
277
+ }
278
+
126
279
  return { status: "ok" };
127
280
  } catch (error) {
128
281
  return { status: "error", error };
129
282
  }
130
283
  }
131
- }
284
+ }
package/src/Quoted.js CHANGED
@@ -41,6 +41,8 @@ export class Quoted {
41
41
 
42
42
  this.sender = participant;
43
43
  this.senderNumber = participantId || "";
44
+ /** True if the bot itself sent the message being quoted. */
45
+ this.fromMe = this.raw.key.fromMe;
44
46
 
45
47
  const { type, key, content } = detectMessageType(contextInfo.quotedMessage);
46
48
  this.type = type;
@@ -0,0 +1,73 @@
1
+ import makeWASocket, { useMultiFileAuthState } from "../../vendor/core/lib/index.js";
2
+ import qrcode from "qrcode-terminal";
3
+ import pino from "pino";
4
+
5
+ /**
6
+ * connection
7
+ * ----------
8
+ * Owns the raw connection lifecycle: creating/loading auth state, opening
9
+ * the underlying socket, and reacting to `connection.update` (QR display,
10
+ * "ready" on open, delegating "close" to `reconnect.js`). Wires the socket's
11
+ * event emitter to `dispatch.js` for incoming messages.
12
+ *
13
+ * Backoff/reconnect *decisions* live in `reconnect.js` — this file only
14
+ * calls into `this._handleDisconnect(...)` when the connection closes.
15
+ */
16
+ export const connectionMethods = {
17
+ /** Boot the bot: load/create session, connect, wire up listeners. */
18
+ async start() {
19
+ this._clearReconnectTimer();
20
+
21
+ const { state, saveCreds } = await useMultiFileAuthState(
22
+ this.options.sessionPath
23
+ );
24
+
25
+ const logger_ =
26
+ this.options.socketConfig.logger ??
27
+ pino({ level: this.options.logLevel });
28
+
29
+ this.sock = makeWASocket({
30
+ auth: state,
31
+ ...this.options.socketConfig,
32
+ logger: logger_,
33
+ });
34
+
35
+ this.sock.ev.on("creds.update", saveCreds);
36
+ this.sock.ev.on("connection.update", (update) => this._handleConnectionUpdate(update));
37
+ this.sock.ev.on("messages.upsert", (payload) => this._handleMessagesUpsert(payload));
38
+
39
+ return this.sock;
40
+ },
41
+
42
+ /** Gracefully close the socket. */
43
+ async stop() {
44
+ this._clearReconnectTimer();
45
+ await this.sock?.end?.(undefined);
46
+ },
47
+
48
+ /**
49
+ * Handle a `connection.update` event: show/emit QR codes, mark the bot
50
+ * "ready" on open, and hand off to `reconnect.js` on close.
51
+ * @param {import('../../vendor/core/lib/index.js').BaileysEventMap['connection.update']} update
52
+ */
53
+ _handleConnectionUpdate(update) {
54
+ const { connection, lastDisconnect, qr } = update;
55
+
56
+ if (qr) {
57
+ if (this.options.printQR) {
58
+ qrcode.generate(qr, { small: true });
59
+ console.log("Scan the QR code above with WhatsApp (Linked Devices).");
60
+ }
61
+ this._emit("qr", qr);
62
+ }
63
+
64
+ if (connection === "open") {
65
+ this._reconnectAttempts = 0;
66
+ this._emit("ready", this.sock);
67
+ }
68
+
69
+ if (connection === "close") {
70
+ this._handleDisconnect(lastDisconnect);
71
+ }
72
+ },
73
+ };
@@ -0,0 +1,59 @@
1
+ import { Context } from "../Context.js";
2
+
3
+ /**
4
+ * dispatch
5
+ * --------
6
+ * Turns raw `messages.upsert` events into Botify `Context` objects and
7
+ * routes them through `PluginManager#dispatch`. Owns:
8
+ * - filtering out non-"notify" upserts and message-less entries
9
+ * (e.g. protocol-only stubs)
10
+ * - constructing `Context` with the bot's prefix/owners config
11
+ * - emitting the "message" event for every incoming message
12
+ * - emitting "unknownCommand" / routing to `_handleError` based on the
13
+ * PluginManager result
14
+ *
15
+ * Wired up once from `connection.js`'s `start()`, via
16
+ * `this.sock.ev.on("messages.upsert", (p) => this._handleMessagesUpsert(p))`.
17
+ */
18
+ export const dispatchMethods = {
19
+ /**
20
+ * @param {{ messages: object[], type: string }} payload
21
+ */
22
+ async _handleMessagesUpsert({ messages, type }) {
23
+ if (type !== "notify") return;
24
+
25
+ for (const raw of messages) {
26
+ if (!raw.message) continue;
27
+ await this._dispatchIncoming(raw);
28
+ }
29
+ },
30
+
31
+ /**
32
+ * Build a Context for one raw message and route it to the right command
33
+ * (if any). Never throws — command/middleware errors go through
34
+ * `this._handleError`.
35
+ * @param {object} raw
36
+ */
37
+ async _dispatchIncoming(raw) {
38
+ const ctx = new Context(this.sock, raw, {
39
+ prefix: this.options.prefix,
40
+ owners: this.options.owners,
41
+ });
42
+
43
+ this._emit("message", ctx);
44
+
45
+ if (!ctx.command) return;
46
+
47
+ const result = await this.plugins.dispatch(ctx.command, ctx);
48
+
49
+ switch (result.status) {
50
+ case "not_found":
51
+ this._emit("unknownCommand", ctx);
52
+ break;
53
+ case "error":
54
+ await this._handleError(result.error, ctx);
55
+ break;
56
+ // "ok" and "stopped" need no further action
57
+ }
58
+ },
59
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * bot (barrel)
3
+ * ------------
4
+ * Everything the `Bot` class mixes onto its prototype lives under this
5
+ * folder, split by concern the same way `./context/` is:
6
+ *
7
+ * register-builtins.js → built-in middleware registration (logger →
8
+ * antiSpam → permission → cooldown), called once
9
+ * from the constructor
10
+ * connection.js → auth state, socket creation, connection.update
11
+ * handling (QR, ready), wiring dispatch/reconnect
12
+ * dispatch.js → messages.upsert → Context → PluginManager#dispatch
13
+ * reconnect.js → exponential-backoff reconnect on unexpected close
14
+ *
15
+ * `Bot.js` (one level up) owns the class itself — constructor, public API
16
+ * (command/use/on/onError), and the small `_emit`/`_handleError` glue used
17
+ * by all of the mixins above — plus
18
+ * `Object.assign(Bot.prototype, ...)` to wire them together.
19
+ */
20
+ export { registerBuiltinsMethods } from "./register-builtins.js";
21
+ export { connectionMethods } from "./connection.js";
22
+ export { dispatchMethods } from "./dispatch.js";
23
+ export { reconnectMethods } from "./reconnect.js";
@@ -0,0 +1,64 @@
1
+ import { DisconnectReason } from "../../vendor/core/lib/index.js";
2
+
3
+ /**
4
+ * reconnect
5
+ * ---------
6
+ * Exponential-backoff auto-reconnect, purely orchestration on top of
7
+ * `connection.js`'s `start()`. Owns:
8
+ * - deciding whether a "close" event should trigger a reconnect
9
+ * (anything except `loggedOut`)
10
+ * - computing the next backoff delay (base * 2^attempt, capped at max)
11
+ * - scheduling/clearing the reconnect timer
12
+ *
13
+ * State (`this._reconnectAttempts`, `this._reconnectTimer`) is initialized
14
+ * in the Bot constructor; these methods just read/mutate it.
15
+ */
16
+ export const reconnectMethods = {
17
+ /**
18
+ * Handle a `connection === "close"` update: emit "disconnect" and, unless
19
+ * the socket was logged out, schedule a reconnect attempt.
20
+ * @param {import('../../vendor/core/lib/index.js').BaileysEventMap['connection.update']['lastDisconnect']} lastDisconnect
21
+ */
22
+ _handleDisconnect(lastDisconnect) {
23
+ const statusCode = lastDisconnect?.error?.output?.statusCode;
24
+ const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
25
+
26
+ if (!shouldReconnect) {
27
+ this._emit("disconnect", { statusCode, willReconnect: false });
28
+ return;
29
+ }
30
+
31
+ const delay = this._nextReconnectDelay();
32
+
33
+ this._emit("disconnect", {
34
+ statusCode,
35
+ willReconnect: true,
36
+ reconnectDelayMs: delay,
37
+ attempt: this._reconnectAttempts,
38
+ });
39
+
40
+ this._reconnectTimer = setTimeout(() => this.start(), delay);
41
+ },
42
+
43
+ /**
44
+ * Computes the next backoff delay and bumps the attempt counter as a
45
+ * side effect (mirrors the previous inline behavior in Bot.start()).
46
+ * @returns {number} delay in ms
47
+ */
48
+ _nextReconnectDelay() {
49
+ const delay = Math.min(
50
+ this.options.reconnectBaseDelay * 2 ** this._reconnectAttempts,
51
+ this.options.reconnectMaxDelay
52
+ );
53
+ this._reconnectAttempts++;
54
+ return delay;
55
+ },
56
+
57
+ /** Clears any pending reconnect timer. Safe to call when none is set. */
58
+ _clearReconnectTimer() {
59
+ if (this._reconnectTimer) {
60
+ clearTimeout(this._reconnectTimer);
61
+ this._reconnectTimer = null;
62
+ }
63
+ },
64
+ };
@@ -0,0 +1,58 @@
1
+ import { logger } from "../middlewares/logger.js";
2
+ import { cooldown } from "../middlewares/cooldown.js";
3
+ import { permission } from "../middlewares/permission.js";
4
+ import { antiSpam } from "../middlewares/antiSpam.js";
5
+
6
+ /**
7
+ * register-builtins
8
+ * -----------------
9
+ * Registers Botify's built-in middlewares onto `this.plugins`, in the
10
+ * order the framework guarantees:
11
+ *
12
+ * 1. logger — log first so every attempt is recorded, even blocked ones
13
+ * 2. antiSpam — global rate limit before any per-command check
14
+ * 3. permission — owner / admin gate
15
+ * 4. cooldown — per-user per-command throttle
16
+ * (user middlewares added via bot.use() run after all of the above)
17
+ *
18
+ * Called once from the Bot constructor, after `this.options` has been
19
+ * normalized and `this.plugins` has been created.
20
+ */
21
+ export const registerBuiltinsMethods = {
22
+ _registerBuiltinMiddlewares() {
23
+ this.plugins.use(
24
+ logger({
25
+ enabled: this.options.logger.enabled,
26
+ showPn: this.options.logger.showPn,
27
+ logFn: this.options.logger.logFn,
28
+ format: this.options.logger.format,
29
+ })
30
+ );
31
+
32
+ if (this.options.antiSpam.enabled) {
33
+ this.plugins.use(
34
+ antiSpam({
35
+ windowMs: this.options.antiSpam.windowMs,
36
+ maxMessages: this.options.antiSpam.maxMessages,
37
+ message: this.options.antiSpam.message,
38
+ })
39
+ );
40
+ }
41
+
42
+ this.plugins.use(
43
+ permission({
44
+ ownerMessage: this.options.permissionMessages.owner,
45
+ adminMessage: this.options.permissionMessages.admin,
46
+ emitEvent: (ctx, reason) => this._emit("noPermission", ctx, reason),
47
+ })
48
+ );
49
+
50
+ this.plugins.use(
51
+ cooldown({
52
+ defaultCooldown: this.options.defaultCooldown,
53
+ message: this.options.cooldownMessage,
54
+ emitEvent: (ctx, remainingMs) => this._emit("cooldown", ctx, remainingMs),
55
+ })
56
+ );
57
+ },
58
+ };
@@ -14,7 +14,7 @@
14
14
  import { proto } from "../../vendor/core/lib/index.js";
15
15
  import { detectMessageType, isMediaType, extractNativeFlowId } from "../utils/messageTypes.js";
16
16
  import { Quoted } from "../Quoted.js";
17
- import { isLid, isPn, detectChatType } from "./jid-utils.js";
17
+ import { isLid, isPn, detectChatType, normalizeJid } from "./jid-utils.js";
18
18
  import { parseCommand, parseNativeFlowCommand } from "./command-parsing.js";
19
19
 
20
20
  /**
@@ -40,6 +40,22 @@ export function deriveMessageState(sock, rawMessage, botConfig) {
40
40
  key.participant || key.remoteJid || key.participantAlt || key.remoteJidAlt || "";
41
41
  state.fromMe = !!key.fromMe;
42
42
 
43
+ /** This message's own id (`key.id`) — e.g. for external dedup/logging. */
44
+ state.id = key.id ?? null;
45
+
46
+ /**
47
+ * When this message was sent, as a unix timestamp in **seconds** (matches
48
+ * WhatsApp's own convention). `messageTimestamp` can come back as a
49
+ * plain number or a Long-like object depending on the transport, so it's
50
+ * normalized here — `null` if missing.
51
+ */
52
+ state.timestamp = rawMessage.messageTimestamp != null
53
+ ? Number(rawMessage.messageTimestamp)
54
+ : null;
55
+
56
+ /** The bot's own JID (device suffix stripped), or null if not connected yet. */
57
+ state.botJid = normalizeJid(sock?.user?.id);
58
+
43
59
  /**
44
60
  * Kind of chat this message came from:
45
61
  * "group" | "channel" (newsletter) | "broadcast" | "private"
@@ -98,11 +114,25 @@ export function deriveMessageState(sock, rawMessage, botConfig) {
98
114
  /** JIDs explicitly @mentioned in this message. */
99
115
  state.mentions = contextInfo?.mentionedJid ?? [];
100
116
 
117
+ /** Whether WhatsApp's client marked this message as forwarded. */
118
+ state.isForwarded = !!contextInfo?.isForwarded;
119
+ /** How many times this content has been forwarded (0 if not forwarded). */
120
+ state.forwardingScore = contextInfo?.forwardingScore ?? 0;
121
+ /**
122
+ * Disappearing-message timer for this chat, in seconds (0 = disabled).
123
+ * Present even on messages that aren't themselves ephemeral, since it
124
+ * describes the chat setting at send time.
125
+ */
126
+ state.expiration = contextInfo?.expiration ?? 0;
127
+
101
128
  /** The message this one is replying to, or null. See Quoted.js. */
102
129
  state.quoted = contextInfo?.quotedMessage
103
130
  ? new Quoted(sock, state.from, contextInfo)
104
131
  : null;
105
132
 
133
+ /** True when the message being replied to was sent by the bot itself. */
134
+ state.repliedToBot = state.quoted?.fromMe ?? false;
135
+
106
136
  // ── Type-specific convenience fields ──────────────────────────────────
107
137
  Object.assign(state, deriveTypeSpecificFields(type, state._content));
108
138
 
@@ -244,4 +274,4 @@ function describeProtocolMessage(content) {
244
274
  ?? content.editedMessage?.extendedTextMessage?.text
245
275
  ?? null,
246
276
  };
247
- }
277
+ }
@@ -38,6 +38,41 @@ export const groupInfoMethods = {
38
38
  );
39
39
  },
40
40
 
41
+ /**
42
+ * Whether the *bot itself* is an admin (or superadmin) of the current
43
+ * group. Always `false` outside of groups. Handy as a guard before
44
+ * actions that require it, e.g. `ctx.deleteMessage()`/`kick` on someone
45
+ * else's message, or `ctx.pin()` in some group settings:
46
+ *
47
+ * if (!(await ctx.isBotAdmin())) return ctx.reply("Bot harus jadi admin dulu.");
48
+ */
49
+ async isBotAdmin() {
50
+ const metadata = await this._getGroupMetadata();
51
+ if (!metadata || !this.botJid) return false;
52
+
53
+ const participant = metadata.participants.find((p) => p.id === this.botJid);
54
+ return (
55
+ !!participant &&
56
+ (participant.admin === "admin" || participant.admin === "superadmin")
57
+ );
58
+ },
59
+
60
+ /**
61
+ * All admin (and superadmin) JIDs in the current group, as a plain
62
+ * array. Returns `[]` outside of groups or if metadata couldn't be
63
+ * fetched. Handy for "notify all admins" / "mention all admins" style
64
+ * commands.
65
+ * @returns {Promise<string[]>}
66
+ */
67
+ async groupAdmins() {
68
+ const metadata = await this._getGroupMetadata();
69
+ if (!metadata) return [];
70
+
71
+ return metadata.participants
72
+ .filter((p) => p.admin === "admin" || p.admin === "superadmin")
73
+ .map((p) => p.id);
74
+ },
75
+
41
76
  /**
42
77
  * The current group's display name (its "subject"). Returns `null`
43
78
  * outside of groups or if metadata couldn't be fetched.
@@ -60,4 +95,4 @@ export const groupInfoMethods = {
60
95
  if (this.chatType === "broadcast") return "broadcast list";
61
96
  return "private chat";
62
97
  },
63
- };
98
+ };
@@ -27,3 +27,16 @@ export function detectChatType(jid) {
27
27
  if (jid.endsWith("@broadcast")) return "broadcast";
28
28
  return "private";
29
29
  }
30
+
31
+ /**
32
+ * Strips the device suffix (":12") that WhatsApp appends to a bot's own
33
+ * JID (`sock.user.id`), e.g. "628xxx:12@s.whatsapp.net" → "628xxx@s.whatsapp.net".
34
+ * Other JIDs (senders, chats) never carry this suffix, so it's only needed
35
+ * for `sock.user.id` — kept here anyway since it's still "just JID shape".
36
+ * @param {string | null | undefined} jid
37
+ * @returns {string | null}
38
+ */
39
+ export function normalizeJid(jid) {
40
+ if (!jid) return null;
41
+ return jid.replace(/:\d+(?=@)/, "");
42
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * plugin: admin
3
+ * -------------
4
+ * Contoh sub-command (`!admin ban`, `!admin kick`) plus penggunaan
5
+ * `category` supaya command ini dikelompokkan rapi di `!menu`.
6
+ *
7
+ * `.sub()` bisa dirangkai berkali-kali. Setiap sub-command mewarisi flag
8
+ * `owner`/`admin`/`cooldown` dari command induknya (di sini `admin: true`)
9
+ * kecuali di-override sendiri — lihat "kick" di bawah yang mengubah cooldown.
10
+ */
11
+ export default function (bot) {
12
+ bot.command("admin", async (ctx) => {
13
+ await ctx.reply(
14
+ `Gunakan:\n${bot.options.prefix}admin ban @user\n${bot.options.prefix}admin kick @user`
15
+ );
16
+ }, {
17
+ category: "Admin",
18
+ admin: true, // berlaku juga untuk sub "ban" & "kick" di bawah
19
+ description: "Perintah khusus admin grup",
20
+ })
21
+ .sub("ban", async (ctx) => {
22
+ const target = ctx.mentions[0];
23
+ if (!target) return ctx.reply("Mention orang yang mau di-ban.");
24
+ // TODO: panggil groupParticipantsUpdate lewat ctx.sock kalau mau nyata.
25
+ await ctx.reply(`🔨 (contoh) Ban ${target}`);
26
+ }, {
27
+ description: "Ban member dari grup",
28
+ })
29
+ .sub("kick", async (ctx) => {
30
+ const target = ctx.mentions[0];
31
+ if (!target) return ctx.reply("Mention orang yang mau di-kick.");
32
+ await ctx.reply(`👋 (contoh) Kick ${target}`);
33
+ }, {
34
+ description: "Kick member dari grup",
35
+ cooldown: 10_000, // override — beda cooldown dari "ban"
36
+ });
37
+ }
@@ -1,30 +1,53 @@
1
1
  /**
2
2
  * plugin: menu
3
3
  * ------------
4
- * Menampilkan daftar semua command yang terdaftar.
4
+ * Menampilkan daftar semua command yang terdaftar, dikelompokkan otomatis
5
+ * per `category` (opts.category saat registrasi), dan menampilkan
6
+ * sub-command (dari `.sub()`) secara nested di bawah command induknya.
7
+ *
8
+ * Command tanpa `category` masuk ke grup "Lainnya".
5
9
  */
6
10
  export default function (bot) {
7
11
  bot.command("menu", async (ctx) => {
8
- const prefix = bot.options.prefix;
9
- const list = bot.plugins
10
- .list()
11
- .map((c) => {
12
- const aliases = c.aliases.length
13
- ? ` (alias: ${c.aliases.map((a) => prefix + a).join(", ")})`
14
- : "";
15
- const flags = [
16
- c.owner ? "👑 owner" : "",
17
- c.admin ? "🛡️ admin" : "",
18
- c.cooldown ? `⏱️ ${c.cooldown / 1000}s` : "",
19
- ].filter(Boolean).join(" · ");
12
+ const prefix = bot.options.prefix;
13
+ const grouped = bot.plugins.listByCategory();
20
14
 
21
- return `${prefix}${c.name}${aliases}${c.description ? ` — ${c.description}` : ""}${flags ? `\n ${flags}` : ""}`;
22
- })
23
- .join("\n");
15
+ const sections = [...grouped.entries()].map(([category, commands]) => {
16
+ const label = category === "uncategorized" ? "Lainnya" : category;
17
+ const lines = commands.map((c) => formatCommand(c, prefix)).join("\n");
18
+ return `*${label}*\n${lines}`;
19
+ });
24
20
 
25
- await ctx.reply(`📋 *Command tersedia:*\n\n${list}`);
21
+ await ctx.reply(`📋 *Command tersedia:*\n\n${sections.join("\n\n")}`);
26
22
  }, {
27
23
  aliases: ["help"],
28
24
  description: "Tampilkan daftar command",
29
25
  });
30
26
  }
27
+
28
+ function formatCommand(c, prefix) {
29
+ const aliases = c.aliases.length
30
+ ? ` (alias: ${c.aliases.map((a) => prefix + a).join(", ")})`
31
+ : "";
32
+ const flags = formatFlags(c);
33
+ const header = `${prefix}${c.name}${aliases}${c.description ? ` — ${c.description}` : ""}${flags ? `\n ${flags}` : ""}`;
34
+
35
+ if (!c.subcommands.length) return header;
36
+
37
+ const subLines = c.subcommands
38
+ .map((s) => {
39
+ const subFlags = formatFlags(s);
40
+ return ` ↳ ${s.name}${s.description ? ` — ${s.description}` : ""}${subFlags ? ` (${subFlags})` : ""}`;
41
+ })
42
+ .join("\n");
43
+
44
+ return `${header}\n${subLines}`;
45
+ }
46
+
47
+ function formatFlags(c) {
48
+ return [
49
+ c.owner ? "👑 owner" : "",
50
+ c.admin ? "🛡️ admin" : "",
51
+ c.cooldown ? `⏱️ ${c.cooldown / 1000}s` : "",
52
+ ].filter(Boolean).join(" · ");
53
+ }
@@ -1,13 +1,26 @@
1
1
  /**
2
- * plugin: ping
2
+ * plugin: info
3
3
  * ------------
4
- * Contoh command paling dasar.
5
- * Setiap plugin mengekspor fungsi default yang menerima `bot` sebagai argumen.
4
+ * Contoh command dengan cooldown dan penggunaan ctx (args, isGroup, sender).
6
5
  */
7
6
  export default function (bot) {
8
- bot.command("ping", async (ctx) => {
9
- await ctx.reply("pong 🏓");
7
+ bot.command("info", async (ctx) => {
8
+ const chat = await ctx.describeChat();
9
+ const lines = [
10
+ `👤 *Pengirim:* ${ctx.pushName}`,
11
+ `📱 *Nomor:* ${ctx.senderNumber}`,
12
+ `💬 *Chat:* ${chat}`,
13
+ `🤖 *Prefix:* ${bot.options.prefix}`,
14
+ ];
15
+
16
+ if (ctx.args.length) {
17
+ lines.push(`📝 *Args:* ${ctx.args.join(", ")}`);
18
+ }
19
+
20
+ await ctx.reply(lines.join("\n"));
10
21
  }, {
11
- description: "Cek apakah bot aktif",
22
+ category: "Umum",
23
+ description: "Info tentang pengirim dan chat",
24
+ cooldown: 5_000,
12
25
  });
13
- }
26
+ }
Binary file