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