botify-wa 0.6.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 +29 -4
- package/package.json +1 -1
- package/src/Bot.js +21 -4
- package/src/PluginManager.js +165 -12
- package/src/Quoted.js +2 -0
- package/src/context/derive-message-state.js +32 -2
- package/src/context/group-info.js +36 -1
- package/src/context/jid-utils.js +13 -0
- package/src/templates/plugins/admin.js +37 -0
- package/src/templates/plugins/menu.js +40 -17
- package/src/templates/plugins/ping.js +20 -7
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`
|
|
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
package/src/Bot.js
CHANGED
|
@@ -124,10 +124,27 @@ export class Bot {
|
|
|
124
124
|
|
|
125
125
|
// ── Public API ─────────────────────────────────────────────────────────────
|
|
126
126
|
|
|
127
|
-
/**
|
|
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
|
+
*/
|
|
128
146
|
command(name, handler, opts) {
|
|
129
|
-
this.plugins.command(name, handler, opts);
|
|
130
|
-
return this;
|
|
147
|
+
return this.plugins.command(name, handler, opts);
|
|
131
148
|
}
|
|
132
149
|
|
|
133
150
|
/**
|
|
@@ -191,4 +208,4 @@ Object.assign(
|
|
|
191
208
|
connectionMethods, // start, stop, _handleConnectionUpdate
|
|
192
209
|
dispatchMethods, // _handleMessagesUpsert, _dispatchIncoming
|
|
193
210
|
reconnectMethods, // _handleDisconnect, _nextReconnectDelay, _clearReconnectTimer
|
|
194
|
-
);
|
|
211
|
+
);
|
package/src/PluginManager.js
CHANGED
|
@@ -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.
|
|
12
|
-
*
|
|
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
|
|
117
|
-
//
|
|
118
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -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
|
+
};
|
package/src/context/jid-utils.js
CHANGED
|
@@ -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
|
|
9
|
-
const
|
|
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
|
-
|
|
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${
|
|
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:
|
|
2
|
+
* plugin: info
|
|
3
3
|
* ------------
|
|
4
|
-
* Contoh command
|
|
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("
|
|
9
|
-
await ctx.
|
|
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
|
-
|
|
22
|
+
category: "Umum",
|
|
23
|
+
description: "Info tentang pengirim dan chat",
|
|
24
|
+
cooldown: 5_000,
|
|
12
25
|
});
|
|
13
|
-
}
|
|
26
|
+
}
|