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.
@@ -0,0 +1,247 @@
1
+ /**
2
+ * derive-message-state
3
+ * ---------------------
4
+ * Turns a raw connection message into every plain-data field Context
5
+ * exposes (`ctx.from`, `ctx.type`, `ctx.text`, `ctx.command`, type-specific
6
+ * shortcuts like `ctx.location`/`ctx.poll`, …). Pure with respect to the
7
+ * message itself — the only side effect is constructing a `Quoted` helper,
8
+ * which needs `sock` to lazily resolve the quoted message's own media/replies.
9
+ *
10
+ * Kept separate from the `Context` class so the constructor stays a thin
11
+ * "wire this up" step, and so this parsing logic can be unit-tested without
12
+ * spinning up a full Context.
13
+ */
14
+ import { proto } from "../../vendor/core/lib/index.js";
15
+ import { detectMessageType, isMediaType, extractNativeFlowId } from "../utils/messageTypes.js";
16
+ import { Quoted } from "../Quoted.js";
17
+ import { isLid, isPn, detectChatType } from "./jid-utils.js";
18
+ import { parseCommand, parseNativeFlowCommand } from "./command-parsing.js";
19
+
20
+ /**
21
+ * @param {import('../../vendor/core/lib/index.js').WASocket} sock
22
+ * @param {import('../../vendor/core/lib/index.js').proto.IWebMessageInfo} rawMessage
23
+ * @param {{ prefix: string, owners?: string[] }} botConfig
24
+ * @returns {object} Plain object of fields to be assigned onto a Context instance.
25
+ */
26
+ export function deriveMessageState(sock, rawMessage, botConfig) {
27
+ const state = {};
28
+ const key = rawMessage.key;
29
+
30
+ // WhatsApp is rolling out "LID" (Linked ID, @lid) as an alternate,
31
+ // non-phone-number identifier — mainly in DMs and communities, for
32
+ // privacy. When that's active, the "primary" field (participant /
33
+ // remoteJid) may hold the @lid form while the real phone-number JID
34
+ // sits in the matching "Alt" field (participantAlt / remoteJidAlt),
35
+ // or vice versa. We fall back through all four so `sender`/`from`
36
+ // are never silently empty just because WhatsApp picked a different
37
+ // field for this account/chat.
38
+ state.from = key.remoteJid || key.remoteJidAlt || "";
39
+ state.sender =
40
+ key.participant || key.remoteJid || key.participantAlt || key.remoteJidAlt || "";
41
+ state.fromMe = !!key.fromMe;
42
+
43
+ /**
44
+ * Kind of chat this message came from:
45
+ * "group" | "channel" (newsletter) | "broadcast" | "private"
46
+ */
47
+ state.chatType = detectChatType(state.from);
48
+ /** Convenience boolean, derived from chatType (kept for backwards compat). */
49
+ state.isGroup = state.chatType === "group";
50
+
51
+ /** Display name of the sender as WhatsApp reports it (may be stale/unset). */
52
+ state.pushName = rawMessage.pushName || "Unknown";
53
+
54
+ /** The sender's @lid identifier, if WhatsApp provided one — else null. */
55
+ state.senderLid = [key.participant, key.participantAlt, key.remoteJid, key.remoteJidAlt]
56
+ .find((jid) => isLid(jid)) ?? null;
57
+ /** The sender's real phone-number JID (@s.whatsapp.net), if available — else null. */
58
+ state.senderPn = [key.participant, key.participantAlt, key.remoteJid, key.remoteJidAlt]
59
+ .find((jid) => isPn(jid)) ?? null;
60
+
61
+ /**
62
+ * Sender's phone number with no @domain suffix, e.g. "6281234567890".
63
+ * Prefers the real phone-number JID over a LID (a LID's numeric part
64
+ * is NOT a phone number, so it's only used here as a last resort).
65
+ */
66
+ state.senderNumber = (state.senderPn ?? state.senderLid ?? state.sender).split("@")[0] ?? "";
67
+
68
+ // ── Message type + content ────────────────────────────────────────────
69
+ // Unwraps ephemeral/view-once/edited envelopes automatically, so
70
+ // ctx.type/ctx.text/media fields always describe the *real* message.
71
+ const { type, key: contentKey, content } = detectMessageType(rawMessage.message);
72
+ /**
73
+ * Friendly message-type string: "text" | "image" | "video" | "audio" |
74
+ * "sticker" | "document" | "contact" | "contacts" | "location" |
75
+ * "liveLocation" | "poll" | "pollUpdate" | "reaction" | "buttonsResponse" |
76
+ * "listResponse" | "templateButtonReply" | "interactiveResponse" |
77
+ * "groupInvite" | "product" | "order" | "event" | "protocol" | "call" |
78
+ * "unsupported" | "unknown"
79
+ */
80
+ state.type = type;
81
+ /** Raw WAProto content key this was detected from (e.g. "imageMessage"). */
82
+ state._contentKey = contentKey;
83
+ /** Raw inner content object for ctx.type (e.g. the imageMessage itself). */
84
+ state._content = content ?? {};
85
+
86
+ /** Whether this message carries a downloadable media attachment. */
87
+ state.isMedia = isMediaType(type);
88
+ state.mimetype = state._content.mimetype ?? null;
89
+ state.caption = state._content.caption ?? null;
90
+ state.fileName = state._content.fileName ?? null;
91
+ /** True for voice notes (audio messages sent as PTT). */
92
+ state.isPtt = type === "audio" ? !!state._content.ptt : false;
93
+ state.isAnimatedSticker = type === "sticker" ? !!state._content.isAnimated : false;
94
+ state.isViewOnce = !!state._content.viewOnce;
95
+
96
+ const contextInfo = state._content.contextInfo ?? null;
97
+
98
+ /** JIDs explicitly @mentioned in this message. */
99
+ state.mentions = contextInfo?.mentionedJid ?? [];
100
+
101
+ /** The message this one is replying to, or null. See Quoted.js. */
102
+ state.quoted = contextInfo?.quotedMessage
103
+ ? new Quoted(sock, state.from, contextInfo)
104
+ : null;
105
+
106
+ // ── Type-specific convenience fields ──────────────────────────────────
107
+ Object.assign(state, deriveTypeSpecificFields(type, state._content));
108
+
109
+ // ── Text + command parsing ────────────────────────────────────────────
110
+ // Button/list-row taps are commands by construction (the developer
111
+ // picked that id specifically to route to a command) — unlike free-typed
112
+ // text, they don't need to start with the configured prefix, and it
113
+ // doesn't matter which of WhatsApp's several reply formats echoed the
114
+ // tap back (`templateButtonReplyMessage`, `buttonsResponseMessage`,
115
+ // `listResponseMessage`, or the modern `interactiveResponseMessage`) —
116
+ // whichever it was, `ctx.buttonReply`/`ctx.listReply` above already
117
+ // normalized it down to a plain `.id`, so we just use that here too.
118
+ const tapId = state.buttonReply?.id ?? state.listReply?.id ?? null;
119
+ state.text = tapId ?? extractText(rawMessage);
120
+ const parsed = tapId
121
+ ? parseNativeFlowCommand(tapId, botConfig.prefix)
122
+ : parseCommand(state.text, botConfig.prefix);
123
+ state.command = parsed.command;
124
+ state.args = parsed.args;
125
+
126
+ /** Whether the sender is listed in Bot({ owners: [...] }). */
127
+ state.isOwner = (botConfig.owners ?? []).includes(state.sender);
128
+
129
+ return state;
130
+ }
131
+
132
+ /** Builds the type-specific convenience fields (`ctx.location`, `ctx.poll`, …). */
133
+ function deriveTypeSpecificFields(type, content) {
134
+ const fields = {};
135
+
136
+ if (type === "location" || type === "liveLocation") {
137
+ fields.location = {
138
+ latitude: content.degreesLatitude,
139
+ longitude: content.degreesLongitude,
140
+ name: content.name || null,
141
+ address: content.address || null,
142
+ };
143
+ }
144
+
145
+ if (type === "contact") {
146
+ fields.contact = {
147
+ displayName: content.displayName || null,
148
+ vcard: content.vcard,
149
+ };
150
+ }
151
+
152
+ if (type === "contacts") {
153
+ fields.contacts = (content.contacts ?? []).map((c) => ({
154
+ displayName: c.displayName || null,
155
+ vcard: c.vcard,
156
+ }));
157
+ }
158
+
159
+ if (type === "poll") {
160
+ fields.poll = {
161
+ name: content.name,
162
+ options: (content.options ?? []).map((o) => o.optionName),
163
+ selectableCount: content.selectableOptionsCount || 1,
164
+ };
165
+ }
166
+
167
+ if (type === "buttonsResponse") {
168
+ fields.buttonReply = {
169
+ id: content.selectedButtonId,
170
+ text: content.selectedDisplayText,
171
+ };
172
+ }
173
+ if (type === "templateButtonReply") {
174
+ fields.buttonReply = {
175
+ id: content.selectedId,
176
+ text: content.selectedDisplayText,
177
+ };
178
+ }
179
+ if (type === "listResponse") {
180
+ fields.listReply = {
181
+ id: content.singleSelectReply?.selectedRowId,
182
+ title: content.title,
183
+ };
184
+ }
185
+
186
+ // Native-flow response — what `ctx.sendButtons()` / `ctx.sendListMenu()`
187
+ // actually get back when tapped (WhatsApp's modern interactive-message
188
+ // format, distinct from the legacy buttonsMessage/listMessage above).
189
+ if (type === "interactiveResponse") {
190
+ const id = extractNativeFlowId(content);
191
+ fields.buttonReply = { id, name: content.nativeFlowResponseMessage?.name ?? null };
192
+ // Also mirror onto listReply when it came from a list menu, so code
193
+ // written against either legacy or native-flow list replies works.
194
+ if (content.nativeFlowResponseMessage?.name === "single_select") {
195
+ fields.listReply = { id, title: null };
196
+ }
197
+ }
198
+
199
+ if (type === "groupInvite") {
200
+ fields.groupInvite = {
201
+ jid: content.groupJid,
202
+ code: content.inviteCode,
203
+ expiration: content.inviteExpiration,
204
+ name: content.groupName,
205
+ };
206
+ }
207
+
208
+ if (type === "protocol") {
209
+ fields.protocol = describeProtocolMessage(content);
210
+ }
211
+
212
+ return fields;
213
+ }
214
+
215
+ function extractText(msg) {
216
+ const m = msg.message;
217
+ if (!m) return "";
218
+ return (
219
+ m.conversation ??
220
+ m.extendedTextMessage?.text ??
221
+ m.imageMessage?.caption ??
222
+ m.videoMessage?.caption ??
223
+ m.documentMessage?.caption ??
224
+ extractNativeFlowId(m.interactiveResponseMessage) ??
225
+ ""
226
+ );
227
+ }
228
+
229
+ /** Turns a protocolMessage's numeric `type` into a friendly description. */
230
+ function describeProtocolMessage(content) {
231
+ const Type = proto.Message.ProtocolMessage.Type;
232
+ const reverse = Object.fromEntries(Object.entries(Type).map(([k, v]) => [v, k]));
233
+
234
+ const kindMap = {
235
+ [Type.REVOKE]: "delete",
236
+ [Type.MESSAGE_EDIT]: "edit",
237
+ [Type.EPHEMERAL_SETTING]: "ephemeralSetting",
238
+ };
239
+
240
+ return {
241
+ kind: kindMap[content.type] ?? reverse[content.type] ?? "unknown",
242
+ key: content.key ?? null,
243
+ editedText: content.editedMessage?.conversation
244
+ ?? content.editedMessage?.extendedTextMessage?.text
245
+ ?? null,
246
+ };
247
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * group-info
3
+ * ----------
4
+ * Group-metadata lookups (cached per-Context so a single incoming message
5
+ * never fetches it twice) and small human-readable descriptions.
6
+ */
7
+
8
+ export const groupInfoMethods = {
9
+ /**
10
+ * Fetches (and caches) this chat's group metadata. Returns `null` outside
11
+ * of groups, or if the fetch fails (e.g. bot was removed from the group).
12
+ */
13
+ async _getGroupMetadata() {
14
+ if (this.chatType !== "group") return null;
15
+ if (this._groupMetadataCache !== undefined) return this._groupMetadataCache;
16
+
17
+ try {
18
+ this._groupMetadataCache = await this.sock.groupMetadata(this.from);
19
+ } catch {
20
+ this._groupMetadataCache = null;
21
+ }
22
+ return this._groupMetadataCache;
23
+ },
24
+
25
+ /**
26
+ * Whether the sender is an admin (or superadmin) of the current group.
27
+ * Always `false` outside of groups.
28
+ */
29
+ async isGroupAdmin() {
30
+ const metadata = await this._getGroupMetadata();
31
+ if (!metadata) return false;
32
+
33
+ const ids = [this.sender, this.senderLid, this.senderPn].filter(Boolean);
34
+ const participant = metadata.participants.find((p) => ids.includes(p.id));
35
+ return (
36
+ !!participant &&
37
+ (participant.admin === "admin" || participant.admin === "superadmin")
38
+ );
39
+ },
40
+
41
+ /**
42
+ * The current group's display name (its "subject"). Returns `null`
43
+ * outside of groups or if metadata couldn't be fetched.
44
+ */
45
+ async getGroupName() {
46
+ const metadata = await this._getGroupMetadata();
47
+ return metadata?.subject ?? null;
48
+ },
49
+
50
+ /**
51
+ * A human-readable one-liner describing where this message came from,
52
+ * handy for logging: e.g. `group "Koalisi Community"` or `private chat`.
53
+ */
54
+ async describeChat() {
55
+ if (this.chatType === "group") {
56
+ const name = await this.getGroupName();
57
+ return `group "${name ?? this.from}"`;
58
+ }
59
+ if (this.chatType === "channel") return "channel";
60
+ if (this.chatType === "broadcast") return "broadcast list";
61
+ return "private chat";
62
+ },
63
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * context (barrel)
3
+ * ----------------
4
+ * Everything needed to assemble the `Context` class lives under this
5
+ * folder, split by concern so no single file mixes unrelated logic:
6
+ *
7
+ * derive-message-state.js → raw message → plain-data fields (ctx.from, ctx.type, ...)
8
+ * command-parsing.js → text/id → { command, args }
9
+ * jid-utils.js → JID classification helpers
10
+ * sending/text.js → reply, send, sendCard
11
+ * sending/media.js → sendImage, sendVideo, sendAudio, sendDocument, sendSticker, sendStickerPack, sendAlbum
12
+ * sending/interactive.js → sendButtons, sendListMenu
13
+ * sending/rich.js → sendTable(V2), sendRichList, sendCodeBlock(V2), sendLink(V2), sendRichMessage
14
+ * sending/other.js → sendContact, sendLocation, sendPoll, sendPayment, sendEvent, sendPollResult, sendProduct, sendStatusMention
15
+ * media-transfer.js → download, saveMedia (of the *incoming* message)
16
+ * message-actions.js → react, edit(Message), delete(Message), pin, unpin, star, forward, isMentioned
17
+ * group-info.js → isGroupAdmin, getGroupName, describeChat
18
+ *
19
+ * `Context.js` (one level up) owns the class itself — constructor +
20
+ * `Object.assign(Context.prototype, ...)` — so this file only re-exports
21
+ * the pieces it needs to wire together.
22
+ */
23
+ export { deriveMessageState } from "./derive-message-state.js";
24
+
25
+ export { textSendingMethods } from "./sending/text.js";
26
+ export { mediaSendingMethods } from "./sending/media.js";
27
+ export { interactiveSendingMethods } from "./sending/interactive.js";
28
+ export { richSendingMethods } from "./sending/rich.js";
29
+ export { otherSendingMethods } from "./sending/other.js";
30
+ export { mediaTransferMethods } from "./media-transfer.js";
31
+ export { messageActionMethods } from "./message-actions.js";
32
+ export { groupInfoMethods } from "./group-info.js";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * jid-utils
3
+ * ---------
4
+ * Small, dependency-free helpers for classifying WhatsApp JIDs. Kept apart
5
+ * from Context itself so they can be reused (e.g. by middlewares) and
6
+ * tested in isolation.
7
+ */
8
+
9
+ /** True for WhatsApp's privacy-preserving "@lid" identifier form. */
10
+ export function isLid(jid) {
11
+ return typeof jid === "string" && jid.endsWith("@lid");
12
+ }
13
+
14
+ /** True for a real phone-number JID ("@s.whatsapp.net"). */
15
+ export function isPn(jid) {
16
+ return typeof jid === "string" && jid.endsWith("@s.whatsapp.net");
17
+ }
18
+
19
+ /**
20
+ * Classifies a chat JID into the four kinds Botify distinguishes.
21
+ * @param {string} jid
22
+ * @returns {"group" | "channel" | "broadcast" | "private"}
23
+ */
24
+ export function detectChatType(jid) {
25
+ if (jid.endsWith("@g.us")) return "group";
26
+ if (jid.endsWith("@newsletter")) return "channel";
27
+ if (jid.endsWith("@broadcast")) return "broadcast";
28
+ return "private";
29
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * media-transfer
3
+ * --------------
4
+ * Downloading media attached to the *incoming* triggering message
5
+ * (as opposed to `sending/media.js`, which is for outbound media).
6
+ */
7
+ import { downloadMedia, saveMedia } from "../media.js";
8
+
9
+ export const mediaTransferMethods = {
10
+ /**
11
+ * Download this message's media attachment.
12
+ * @param {{ asStream?: boolean }} [opts] `asStream: true` for large files.
13
+ * @returns {Promise<Buffer | NodeJS.ReadableStream>}
14
+ */
15
+ async download(opts) {
16
+ if (!this.isMedia) {
17
+ throw new Error(`Message of type "${this.type}" has no media to download`);
18
+ }
19
+ return downloadMedia(this.sock, this.raw, opts);
20
+ },
21
+
22
+ /** Download this message's media straight to disk. Returns the filePath. */
23
+ async saveMedia(filePath, opts) {
24
+ if (!this.isMedia) {
25
+ throw new Error(`Message of type "${this.type}" has no media to download`);
26
+ }
27
+ return saveMedia(this.sock, this.raw, filePath, opts);
28
+ },
29
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * message-actions
3
+ * ---------------
4
+ * Actions that operate on already-sent messages: reactions, edits,
5
+ * deletes, pin/unpin, star, and forwarding.
6
+ */
7
+ import { proto } from "../../vendor/core/lib/index.js";
8
+
9
+ export const messageActionMethods = {
10
+ /** React to the triggering message with an emoji. */
11
+ async react(emoji) {
12
+ return this.sock.sendMessage(this.from, {
13
+ react: { text: emoji, key: this.raw.key },
14
+ });
15
+ },
16
+
17
+ /** Remove the bot's own reaction from the triggering message. */
18
+ async removeReaction() {
19
+ return this.react("");
20
+ },
21
+
22
+ /**
23
+ * Edit any of the bot's own previously-sent messages in this chat.
24
+ * @param {{key:object}|object} target A sent-message result (from
25
+ * ctx.reply()/ctx.send()) or a raw message key.
26
+ * @param {object} content New content, e.g. `{ text: "updated" }`.
27
+ */
28
+ async editMessage(target, content) {
29
+ const key = target?.key ?? target;
30
+ return this.sock.sendMessage(this.from, { ...content, edit: key });
31
+ },
32
+
33
+ /**
34
+ * Delete a message for everyone. Only works for the bot's own messages,
35
+ * or any message in a group where the bot is admin.
36
+ * @param {{key:object}|object} [target] Defaults to the triggering message
37
+ * — handy for self-bot setups where the owner's own command message
38
+ * should be cleaned up after being processed.
39
+ */
40
+ async deleteMessage(target = this.raw.key) {
41
+ const key = target?.key ?? target;
42
+ return this.sock.sendMessage(this.from, { delete: key });
43
+ },
44
+
45
+ /** Shortcut: edit the triggering message itself (only works if it's the bot's own). */
46
+ async edit(text) {
47
+ return this.editMessage(this.raw.key, { text });
48
+ },
49
+
50
+ /** Shortcut: delete the triggering message itself. */
51
+ async delete() {
52
+ return this.deleteMessage(this.raw.key);
53
+ },
54
+
55
+ /** Pin the triggering message in the chat. `time` in seconds (default 24h). */
56
+ async pin(time = 86400) {
57
+ return this.sock.sendMessage(this.from, {
58
+ pin: this.raw.key,
59
+ type: proto.PinInChat.Type.PIN_FOR_ALL,
60
+ time,
61
+ });
62
+ },
63
+
64
+ /** Unpin the triggering message. */
65
+ async unpin() {
66
+ return this.sock.sendMessage(this.from, {
67
+ pin: this.raw.key,
68
+ type: proto.PinInChat.Type.UNPIN_FOR_ALL,
69
+ });
70
+ },
71
+
72
+ /** Star/unstar the triggering message. */
73
+ async star(starred = true) {
74
+ return this.sock.star(
75
+ this.from,
76
+ [{ id: this.raw.key.id, fromMe: this.raw.key.fromMe }],
77
+ starred
78
+ );
79
+ },
80
+
81
+ /** Forward the triggering message to another chat. */
82
+ async forward(toJid, opts = {}) {
83
+ return this.sock.sendMessage(toJid, { forward: this.raw, ...opts });
84
+ },
85
+
86
+ /** Whether `jid` (any of its JID forms) is @mentioned in this message. */
87
+ isMentioned(jid) {
88
+ const num = String(jid).split("@")[0];
89
+ return this.mentions.some((m) => String(m).split("@")[0] === num);
90
+ },
91
+ };
@@ -0,0 +1,131 @@
1
+ /**
2
+ * sending/interactive
3
+ * -------------------
4
+ * Native-flow interactive messages: quick-reply/url/copy buttons and
5
+ * WhatsApp's native list-menu (`single_select`).
6
+ */
7
+ import { resolveMediaSource, resolveThumbnail } from "../../media.js";
8
+
9
+ export const interactiveSendingMethods = {
10
+ /**
11
+ * Send native-flow buttons (quick reply / open URL / copy code).
12
+ * Accepts either the raw `{ name, buttonParamsJson }` shape from the core,
13
+ * or a friendlier shorthand per button:
14
+ * { type: "reply", text, id }
15
+ * { type: "url", text, url }
16
+ * { type: "copy", text, code }
17
+ *
18
+ * Routed through `content.interactiveButtons` (not `interactiveMessage`)
19
+ * — that's the path the core wraps with the `messageSecret` that WhatsApp
20
+ * needs to recognize a tap as a real interactive response. Without it,
21
+ * `quick_reply`/`cta_url`/`cta_copy` taps silently fall back to a plain
22
+ * text reply on the recipient's end and never reach your bot.
23
+ * @param {{ title?: string, subtitle?: string, footer?: string, header?: string, image?, video?, document?, location?, thumbnail?, thumbnailWidth?, jpegThumbnail? }} content
24
+ * `title` is the main body text; `header` is the small line above it
25
+ * (matches what `interactiveMessage.title`/`.header` rendered as before).
26
+ * `image`/`video`/`document`/`location` are mutually exclusive — pick one
27
+ * to use as the card header. `thumbnail` (Buffer, local path, or http(s)
28
+ * URL) overrides the header's preview image — most useful with
29
+ * `location`, which otherwise shows WA's auto-generated map snapshot.
30
+ * `thumbnailWidth` controls how sharp it comes out (default 192px,
31
+ * matching the core's own convention for embedded thumbnails — going
32
+ * much higher, e.g. 400+, risks WA rejecting it and falling back to a
33
+ * generic placeholder icon). Use the raw `jpegThumbnail` (pre-encoded
34
+ * JPEG Buffer/base64) instead of `thumbnail` if you want to skip the
35
+ * resize step entirely.
36
+ * @param {Array<object>} buttons Each is either the raw `{ name, buttonParamsJson }`
37
+ * shape, or shorthand: `{ type: "reply"|"url"|"copy", ... }` (see
38
+ * `normalizeButton`), or `{ type: "list", text, sections }` for a native
39
+ * list-menu button (same `sections` shape as `sendListMenu()`).
40
+ */
41
+ async sendButtons(content, buttons, opts = {}) {
42
+ const {
43
+ title, subtitle, footer, header, image, video, document, location,
44
+ mimetype, jpegThumbnail, thumbnail, thumbnailWidth = 192,
45
+ } = content;
46
+ const resolvedThumbnail = thumbnail
47
+ ? await resolveThumbnail(thumbnail, thumbnailWidth)
48
+ : jpegThumbnail;
49
+ return this.send(
50
+ {
51
+ text: title,
52
+ subtitle,
53
+ footer,
54
+ title: header,
55
+ ...(image ? { image: resolveMediaSource(image) } : {}),
56
+ ...(video ? { video: resolveMediaSource(video) } : {}),
57
+ ...(document ? { document: resolveMediaSource(document) } : {}),
58
+ ...(location ? { location } : {}),
59
+ mimetype,
60
+ jpegThumbnail: resolvedThumbnail,
61
+ interactiveButtons: buttons.map(normalizeButton),
62
+ },
63
+ { quoted: this.raw, ...opts }
64
+ );
65
+ },
66
+
67
+ /**
68
+ * Send a WhatsApp list menu (native `single_select` interactive message).
69
+ *
70
+ * Unlike `sendButtons()`, this stays on the plain `interactiveMessage`
71
+ * path (no `messageSecret` wrapping) — `single_select` list-row taps are
72
+ * recognized fine without it, so there's no need for the extra wrapping.
73
+ * @param {{ title?, footer?, header?, buttonText? }} content
74
+ * @param {Array<{ title: string, rows: Array<{ title, id, description? }> }>} sections
75
+ */
76
+ async sendListMenu(content, sections, opts = {}) {
77
+ const { title, footer, header, buttonText = "Menu" } = content;
78
+ return this.send(
79
+ {
80
+ interactiveMessage: {
81
+ title,
82
+ footer,
83
+ header,
84
+ buttons: [
85
+ {
86
+ name: "single_select",
87
+ buttonParamsJson: JSON.stringify({ title: buttonText, sections }),
88
+ },
89
+ ],
90
+ },
91
+ },
92
+ { quoted: this.raw, ...opts }
93
+ );
94
+ },
95
+ };
96
+
97
+ /**
98
+ * Normalizes one button for `ctx.sendButtons()`. Passes through the raw
99
+ * `{ name, buttonParamsJson }` shape untouched; converts the friendly
100
+ * shorthand (`{ type: "reply"|"url"|"copy"|"list", ... }`) into that shape.
101
+ */
102
+ function normalizeButton(button) {
103
+ if (button.name && button.buttonParamsJson) return button;
104
+
105
+ switch (button.type) {
106
+ case "reply":
107
+ return {
108
+ name: "quick_reply",
109
+ buttonParamsJson: JSON.stringify({ display_text: button.text, id: button.id }),
110
+ };
111
+ case "url":
112
+ return {
113
+ name: "cta_url",
114
+ buttonParamsJson: JSON.stringify({ display_text: button.text, url: button.url }),
115
+ };
116
+ case "copy":
117
+ return {
118
+ name: "cta_copy",
119
+ buttonParamsJson: JSON.stringify({ display_text: button.text, copy_code: button.code }),
120
+ };
121
+ case "list":
122
+ // Native list-menu button — tapping it opens the same row-picker UI
123
+ // as `ctx.sendListMenu()`. `sections`: Array<{ title, rows: Array<{ title, id, description? }> }>.
124
+ return {
125
+ name: "single_select",
126
+ buttonParamsJson: JSON.stringify({ title: button.text, sections: button.sections }),
127
+ };
128
+ default:
129
+ throw new Error(`Unknown button type: "${button.type}". Use "reply", "url", "copy", or "list".`);
130
+ }
131
+ }