botify-wa 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botify-wa",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Lightweight WhatsApp bot framework with plugin system, built-in middlewares, and CLI scaffolding.",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/Bot.js CHANGED
@@ -1,16 +1,11 @@
1
- import makeWASocket, {
2
- DisconnectReason,
3
- useMultiFileAuthState,
4
- } from "../vendor/core/lib/index.js";
5
- import qrcode from "qrcode-terminal";
6
- import pino from "pino";
7
1
  import { PluginManager } from "./PluginManager.js";
8
- import { Context } from "./Context.js";
9
2
  import { loadConfig, mergeConfig } from "./config/index.js";
10
- import { logger } from "./middlewares/logger.js";
11
- import { cooldown } from "./middlewares/cooldown.js";
12
- import { permission } from "./middlewares/permission.js";
13
- import { antiSpam } from "./middlewares/antiSpam.js";
3
+ import {
4
+ registerBuiltinsMethods,
5
+ connectionMethods,
6
+ dispatchMethods,
7
+ reconnectMethods,
8
+ } from "./bot/index.js";
14
9
 
15
10
  /**
16
11
  * Bot
@@ -27,6 +22,13 @@ import { antiSpam } from "./middlewares/antiSpam.js";
27
22
  *
28
23
  * Everything low-level (encryption, sockets, WA protocol) lives in
29
24
  * vendor/core — Botify only adds structure on top.
25
+ *
26
+ * This class itself only owns construction + the public API + the small
27
+ * `_emit`/`_handleError` glue shared by every mixin below — the actual
28
+ * connection lifecycle, message dispatch, built-in middleware setup, and
29
+ * reconnect backoff are organized by concern into `./bot/*.js` and mixed
30
+ * onto the prototype below. See `./bot/index.js` for the full map of
31
+ * which file owns which methods.
30
32
  */
31
33
  export class Bot {
32
34
  /**
@@ -116,48 +118,8 @@ export class Bot {
116
118
  this._reconnectTimer = null;
117
119
 
118
120
  // ── 2. Register built-in middlewares in the correct order ────────────────
119
- //
120
- // Order matters:
121
- // 1. logger — log first so every attempt is recorded, even blocked ones
122
- // 2. antiSpam — global rate limit before any per-command check
123
- // 3. permission — owner / admin gate
124
- // 4. cooldown — per-user per-command throttle
125
- // (user middlewares added via bot.use() run after all of the above)
126
-
127
- this.plugins.use(
128
- logger({
129
- enabled: this.options.logger.enabled,
130
- showPn: this.options.logger.showPn,
131
- logFn: this.options.logger.logFn,
132
- format: this.options.logger.format,
133
- })
134
- );
135
-
136
- if (this.options.antiSpam.enabled) {
137
- this.plugins.use(
138
- antiSpam({
139
- windowMs: this.options.antiSpam.windowMs,
140
- maxMessages: this.options.antiSpam.maxMessages,
141
- message: this.options.antiSpam.message,
142
- })
143
- );
144
- }
145
-
146
- this.plugins.use(
147
- permission({
148
- ownerMessage: this.options.permissionMessages.owner,
149
- adminMessage: this.options.permissionMessages.admin,
150
- emitEvent: (ctx, reason) => this._emit("noPermission", ctx, reason),
151
- })
152
- );
153
-
154
- this.plugins.use(
155
- cooldown({
156
- defaultCooldown: this.options.defaultCooldown,
157
- message: this.options.cooldownMessage,
158
- emitEvent: (ctx, remainingMs) => this._emit("cooldown", ctx, remainingMs),
159
- })
160
- );
121
+ // (logger → antiSpam → permission → cooldown; see ./bot/register-builtins.js)
122
+ this._registerBuiltinMiddlewares();
161
123
  }
162
124
 
163
125
  // ── Public API ─────────────────────────────────────────────────────────────
@@ -200,7 +162,7 @@ export class Bot {
200
162
  return this;
201
163
  }
202
164
 
203
- // ── Internals ──────────────────────────────────────────────────────────────
165
+ // ── Internals shared by every ./bot/*.js mixin ────────────────────────────
204
166
 
205
167
  _emit(event, ...args) {
206
168
  for (const fn of this._listeners.get(event) ?? []) fn(...args);
@@ -219,109 +181,14 @@ export class Bot {
219
181
  }
220
182
  }
221
183
  }
222
-
223
- /** Boot the bot: load/create session, connect, wire up listeners. */
224
- async start() {
225
- if (this._reconnectTimer) {
226
- clearTimeout(this._reconnectTimer);
227
- this._reconnectTimer = null;
228
- }
229
-
230
- const { state, saveCreds } = await useMultiFileAuthState(
231
- this.options.sessionPath
232
- );
233
-
234
- const logger_ =
235
- this.options.socketConfig.logger ??
236
- pino({ level: this.options.logLevel });
237
-
238
- this.sock = makeWASocket({
239
- auth: state,
240
- ...this.options.socketConfig,
241
- logger: logger_,
242
- });
243
-
244
- this.sock.ev.on("creds.update", saveCreds);
245
-
246
- this.sock.ev.on("connection.update", (update) => {
247
- const { connection, lastDisconnect, qr } = update;
248
-
249
- if (qr) {
250
- if (this.options.printQR) {
251
- qrcode.generate(qr, { small: true });
252
- console.log("Scan the QR code above with WhatsApp (Linked Devices).");
253
- }
254
- this._emit("qr", qr);
255
- }
256
-
257
- if (connection === "open") {
258
- this._reconnectAttempts = 0;
259
- this._emit("ready", this.sock);
260
- }
261
-
262
- if (connection === "close") {
263
- const statusCode = lastDisconnect?.error?.output?.statusCode;
264
- const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
265
-
266
- if (shouldReconnect) {
267
- const delay = Math.min(
268
- this.options.reconnectBaseDelay * 2 ** this._reconnectAttempts,
269
- this.options.reconnectMaxDelay
270
- );
271
- this._reconnectAttempts++;
272
-
273
- this._emit("disconnect", {
274
- statusCode,
275
- willReconnect: true,
276
- reconnectDelayMs: delay,
277
- attempt: this._reconnectAttempts,
278
- });
279
-
280
- this._reconnectTimer = setTimeout(() => this.start(), delay);
281
- } else {
282
- this._emit("disconnect", { statusCode, willReconnect: false });
283
- }
284
- }
285
- });
286
-
287
- this.sock.ev.on("messages.upsert", async ({ messages, type }) => {
288
- if (type !== "notify") return;
289
-
290
- for (const raw of messages) {
291
- if (!raw.message) continue;
292
-
293
- const ctx = new Context(this.sock, raw, {
294
- prefix: this.options.prefix,
295
- owners: this.options.owners,
296
- });
297
-
298
- this._emit("message", ctx);
299
-
300
- if (!ctx.command) continue;
301
-
302
- const result = await this.plugins.dispatch(ctx.command, ctx);
303
-
304
- switch (result.status) {
305
- case "not_found":
306
- this._emit("unknownCommand", ctx);
307
- break;
308
- case "error":
309
- await this._handleError(result.error, ctx);
310
- break;
311
- // "ok" and "stopped" need no further action
312
- }
313
- }
314
- });
315
-
316
- return this.sock;
317
- }
318
-
319
- /** Gracefully close the socket. */
320
- async stop() {
321
- if (this._reconnectTimer) {
322
- clearTimeout(this._reconnectTimer);
323
- this._reconnectTimer = null;
324
- }
325
- await this.sock?.end?.(undefined);
326
- }
327
184
  }
185
+
186
+ // ── Assemble the prototype from focused, single-purpose mixins ───────────
187
+ // Order is presentation-only; grouping mirrors the file layout under ./bot/.
188
+ Object.assign(
189
+ Bot.prototype,
190
+ registerBuiltinsMethods, // _registerBuiltinMiddlewares
191
+ connectionMethods, // start, stop, _handleConnectionUpdate
192
+ dispatchMethods, // _handleMessagesUpsert, _dispatchIncoming
193
+ reconnectMethods, // _handleDisconnect, _nextReconnectDelay, _clearReconnectTimer
194
+ );
@@ -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
+ };
Binary file