botify-wa 0.2.0 → 0.4.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,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
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * sending/media
3
+ * -------------
4
+ * All outbound media types: image/video/audio/document/sticker, sticker
5
+ * packs, and albums (multi-image/video galleries).
6
+ */
7
+ import { makeStickerPack } from "../../../vendor/core/lib/index.js";
8
+ import { resolveMediaSource } from "../../media.js";
9
+
10
+ export const mediaSendingMethods = {
11
+ /** Send an image. `source`: Buffer, local file path, http(s) URL, or `{ url }`/`{ stream }`. */
12
+ async sendImage(source, opts = {}) {
13
+ const { caption, quoted, ...rest } = opts;
14
+ return this.send(
15
+ { image: resolveMediaSource(source), caption, ...rest },
16
+ quoted === false ? {} : { quoted: this.raw }
17
+ );
18
+ },
19
+
20
+ /** Send a video. Pass `{ gifPlayback: true }` to loop it like a GIF. */
21
+ async sendVideo(source, opts = {}) {
22
+ const { caption, quoted, ...rest } = opts;
23
+ return this.send(
24
+ { video: resolveMediaSource(source), caption, ...rest },
25
+ quoted === false ? {} : { quoted: this.raw }
26
+ );
27
+ },
28
+
29
+ /** Send audio. Pass `{ ptt: true }` to send as a voice note. */
30
+ async sendAudio(source, opts = {}) {
31
+ const { quoted, mimetype = "audio/mp4", ptt = false, ...rest } = opts;
32
+ return this.send(
33
+ { audio: resolveMediaSource(source), mimetype, ptt, ...rest },
34
+ quoted === false ? {} : { quoted: this.raw }
35
+ );
36
+ },
37
+
38
+ /** Send a document/file. */
39
+ async sendDocument(source, opts = {}) {
40
+ const {
41
+ quoted,
42
+ mimetype = "application/octet-stream",
43
+ fileName = "file",
44
+ caption,
45
+ ...rest
46
+ } = opts;
47
+ return this.send(
48
+ { document: resolveMediaSource(source), mimetype, fileName, caption, ...rest },
49
+ quoted === false ? {} : { quoted: this.raw }
50
+ );
51
+ },
52
+
53
+ /** Send a sticker (must be a valid animated/static WebP for best results). */
54
+ async sendSticker(source, opts = {}) {
55
+ const { quoted, ...rest } = opts;
56
+ return this.send(
57
+ { sticker: resolveMediaSource(source), ...rest },
58
+ quoted === false ? {} : { quoted: this.raw }
59
+ );
60
+ },
61
+
62
+ /** Send a sticker pack (multiple stickers grouped together). */
63
+ async sendStickerPack({ name, publisher, description, stickers, cover }, opts = {}) {
64
+ const { quoted, ...rest } = opts;
65
+ return this.send(
66
+ makeStickerPack({ name, publisher, description, stickers, cover }),
67
+ { ...(quoted === false ? {} : { quoted: this.raw }), ...rest }
68
+ );
69
+ },
70
+
71
+ /**
72
+ * Send an album (multiple images/videos grouped into one gallery message).
73
+ * @param {Array<{ image?: any, video?: any, caption?: string }>} items
74
+ */
75
+ async sendAlbum(items, opts = {}) {
76
+ const { quoted, ...rest } = opts;
77
+ const album = items.map((item) => {
78
+ const out = { ...item };
79
+ if (out.image) out.image = resolveMediaSource(out.image);
80
+ if (out.video) out.video = resolveMediaSource(out.video);
81
+ return out;
82
+ });
83
+ return this.send(
84
+ { albumMessage: album },
85
+ { ...(quoted === false ? {} : { quoted: this.raw }), ...rest }
86
+ );
87
+ },
88
+ };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * sending/other
3
+ * -------------
4
+ * Everything that doesn't fit "plain text", "media", "interactive", or
5
+ * "rich response": contacts, locations, polls, payments, calendar events,
6
+ * catalog products, and Status (story) mentions.
7
+ */
8
+ import { resolveMediaSource, toVcard } from "../../media.js";
9
+
10
+ export const otherSendingMethods = {
11
+ /**
12
+ * Send one or more contacts.
13
+ * @param {{name:string, number:string, organization?:string} | Array<{...}>} contacts
14
+ */
15
+ async sendContact(contacts, opts = {}) {
16
+ const list = Array.isArray(contacts) ? contacts : [contacts];
17
+ return this.send(
18
+ {
19
+ contacts: {
20
+ displayName: opts.displayName ?? list[0]?.name,
21
+ contacts: list.map((c) => ({ vcard: toVcard(c) })),
22
+ },
23
+ },
24
+ { quoted: this.raw }
25
+ );
26
+ },
27
+
28
+ /** Send a location pin. */
29
+ async sendLocation({ latitude, longitude, name, address }, opts = {}) {
30
+ return this.send(
31
+ { location: { degreesLatitude: latitude, degreesLongitude: longitude, name, address } },
32
+ { quoted: this.raw, ...opts }
33
+ );
34
+ },
35
+
36
+ /** Send a poll. `options.selectableCount` defaults to 1 (single-choice). */
37
+ async sendPoll({ name, options, selectableCount = 1 }, opts = {}) {
38
+ return this.send(
39
+ { poll: { name, values: options, selectableCount } },
40
+ { quoted: this.raw, ...opts }
41
+ );
42
+ },
43
+
44
+ /** Send a payment request. */
45
+ async sendPayment({ amount, currency, note, from }, opts = {}) {
46
+ return this.send(
47
+ { requestPaymentMessage: { amount, currency, note, from } },
48
+ { quoted: this.raw, ...opts }
49
+ );
50
+ },
51
+
52
+ /** Send a calendar event invite. */
53
+ async sendEvent({ name, description, startTime, endTime, location }, opts = {}) {
54
+ return this.send(
55
+ { eventMessage: { name, description, startTime, endTime, location } },
56
+ { quoted: this.raw, ...opts }
57
+ );
58
+ },
59
+
60
+ /** Send poll results (final tally, shown like WhatsApp's own poll-result summary). */
61
+ async sendPollResult({ name, votes }, opts = {}) {
62
+ return this.send(
63
+ { pollResultMessage: { name, pollVotes: votes } },
64
+ { quoted: this.raw, ...opts }
65
+ );
66
+ },
67
+
68
+ /** Send a catalog product card. */
69
+ async sendProduct(product, opts = {}) {
70
+ const { thumbnail, ...rest } = product;
71
+ return this.send(
72
+ {
73
+ productMessage: {
74
+ ...rest,
75
+ ...(thumbnail ? { thumbnail: resolveMediaSource(thumbnail) } : {}),
76
+ },
77
+ },
78
+ { quoted: this.raw, ...opts }
79
+ );
80
+ },
81
+
82
+ /**
83
+ * Post a WhatsApp Status (story) update that @mentions specific contacts,
84
+ * so it shows up highlighted for them. Unlike the other `send*()` methods
85
+ * this doesn't go to `ctx.from` — a Status isn't posted "in" a chat, it's
86
+ * broadcast, visible only to the given `jids` (must be your contacts).
87
+ * @param {object} content Same shape as `sock.sendMessage`'s content, e.g. `{ text }` or `{ image }`.
88
+ * @param {string[]} jids Contacts (and/or groups) who should see it highlighted.
89
+ */
90
+ async sendStatusMention(content, jids) {
91
+ return this.sock.sendStatusMention(content, jids);
92
+ },
93
+ };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * sending/rich
3
+ * ------------
4
+ * "AI-style" rich responses — tables, key/value lists, syntax-highlighted
5
+ * code blocks, and inline-link text. Each has a V1 (basic) and V2 (unified-
6
+ * response protocol) variant; both are thin passthroughs to the vendored
7
+ * core's own `sock.sendXxx()` builders.
8
+ */
9
+
10
+ export const richSendingMethods = {
11
+ /** Rich table (V1). `headers`: string[]; `rows`: string[][]. */
12
+ async sendTable(title, headers, rows, opts = {}) {
13
+ const { quoted, ...rest } = opts;
14
+ return this.sock.sendTable(
15
+ this.from,
16
+ title,
17
+ headers,
18
+ rows,
19
+ quoted === false ? undefined : this.raw,
20
+ rest
21
+ );
22
+ },
23
+
24
+ /**
25
+ * Rich table (V2, unified-response protocol).
26
+ * `table`: [title, "col1 | col2 | ...", "r1c1 | r1c2;;r2c1 | r2c2"]
27
+ */
28
+ async sendTableV2(table, opts = {}) {
29
+ const { quoted, ...rest } = opts;
30
+ return this.sock.sendTableV2(
31
+ this.from,
32
+ table,
33
+ quoted === false ? undefined : this.raw,
34
+ rest
35
+ );
36
+ },
37
+
38
+ /** Rich key/value list (no heading). `items`: Array<[label, value]> or string[]. */
39
+ async sendRichList(title, items, opts = {}) {
40
+ const { quoted, ...rest } = opts;
41
+ return this.sock.sendList(
42
+ this.from,
43
+ title,
44
+ items,
45
+ quoted === false ? undefined : this.raw,
46
+ rest
47
+ );
48
+ },
49
+
50
+ /** Rich code block (V1, basic highlighting). Languages: javascript, typescript, python. */
51
+ async sendCodeBlock(code, opts = {}) {
52
+ const { quoted, ...rest } = opts;
53
+ return this.sock.sendCodeBlock(
54
+ this.from,
55
+ code,
56
+ quoted === false ? undefined : this.raw,
57
+ rest
58
+ );
59
+ },
60
+
61
+ /** Rich code block (V2, unified-response protocol). Languages: javascript, python, go, lua, bash. */
62
+ async sendCodeBlockV2(code, opts = {}) {
63
+ const { quoted, ...rest } = opts;
64
+ return this.sock.sendCodeBlockV2(
65
+ this.from,
66
+ code,
67
+ quoted === false ? undefined : this.raw,
68
+ rest
69
+ );
70
+ },
71
+
72
+ /** Rich inline-link text using `{{IE_N}}display{{/IE_N}}` placeholders. `links`: string[] of URLs, matched by index N. */
73
+ async sendLink(text, links, opts = {}) {
74
+ const { quoted, ...rest } = opts;
75
+ return this.sock.sendLink(
76
+ this.from,
77
+ text,
78
+ links,
79
+ quoted === false ? undefined : this.raw,
80
+ rest
81
+ );
82
+ },
83
+
84
+ /** Rich inline-link text, search-result style. `links`: Array<{ url, displayName?, sourceDisplayName?, sourceSubtitle? }>. */
85
+ async sendLinkV2(text, links, opts = {}) {
86
+ const { quoted, ...rest } = opts;
87
+ return this.sock.sendLinkV2(
88
+ this.from,
89
+ text,
90
+ links,
91
+ quoted === false ? undefined : this.raw,
92
+ rest
93
+ );
94
+ },
95
+
96
+ /**
97
+ * Send a mixed rich message built from raw submessages (text/table/code/
98
+ * image/etc — see `RichSubMessageType` for the numeric `messageType`s).
99
+ */
100
+ async sendRichMessage(submessages, opts = {}) {
101
+ const { quoted, ...rest } = opts;
102
+ return this.sock.sendRichMessage(
103
+ this.from,
104
+ submessages,
105
+ quoted === false ? undefined : this.raw,
106
+ rest
107
+ );
108
+ },
109
+ };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * sending/text
3
+ * ------------
4
+ * The most basic outbound methods: plain replies, raw passthrough sends,
5
+ * and the "link preview card" trick.
6
+ */
7
+ import { resolveThumbnail, resolveHighQualityThumbnail } from "../../media.js";
8
+
9
+ export const textSendingMethods = {
10
+ /** Reply in the same chat, quoting the triggering message. */
11
+ async reply(text, opts = {}) {
12
+ return this.sock.sendMessage(
13
+ this.from,
14
+ { text, ...opts },
15
+ { quoted: this.raw }
16
+ );
17
+ },
18
+
19
+ /** Send any core-compatible message content to the same chat. */
20
+ async send(content, opts = {}) {
21
+ return this.sock.sendMessage(this.from, content, opts);
22
+ },
23
+
24
+ /**
25
+ * Send a lightweight "card" — text with a thumbnail/title/description
26
+ * embedded directly in the message stanza, using the same mechanism as
27
+ * WhatsApp's own link-preview cards. Unlike `image`/`video`/`document`,
28
+ * this never touches WA's media CDN — the recipient sees the whole card
29
+ * the instant the message arrives, at zero extra data cost.
30
+ *
31
+ * IMPORTANT: WhatsApp's client only renders the preview box when the
32
+ * message text actually contains the matching link — there's no way
33
+ * around that from the server side. So `url` is required, and it WILL
34
+ * show up as visible, tappable blue text in the message (appended to
35
+ * `text` automatically if not already present). If you need a card with
36
+ * **no visible link at all**, use `sendButtons({ location, thumbnail }, …)`
37
+ * instead — that renders its embedded thumbnail unconditionally, no URL
38
+ * needed (see the `locationbuttons` example).
39
+ *
40
+ * By default this also uploads `thumbnail` to WA's media CDN the same
41
+ * way WhatsApp's own client does for real link previews (a `thumbnail-link`
42
+ * upload — see `resolveHighQualityThumbnail()` in `media.js`), so the
43
+ * recipient's client re-fetches the actual full-resolution image instead
44
+ * of only ever showing the small, quality-50 embedded `jpegThumbnail`.
45
+ * That upload costs one network round-trip at send time; set
46
+ * `highQuality: false` to skip it and stay fully local/zero-network
47
+ * (same ~300px, blurrier-but-instant behavior as before). If the upload
48
+ * fails for any reason (offline, WA media host hiccup, etc.), sendCard
49
+ * silently falls back to the embedded-only thumbnail rather than throwing.
50
+ *
51
+ * @param {{ text?: string, title?: string, description?: string, thumbnail: Buffer|string, thumbnailWidth?: number, url: string, highQuality?: boolean }} content
52
+ * `thumbnail`: Buffer, local path, or http(s) URL of the card image.
53
+ * `url`: required — the link that makes WA render the card, shown as
54
+ * visible tappable text.
55
+ * `highQuality` (default `true`): upload to WA's CDN for a sharp,
56
+ * full-res preview image; `false` keeps the old embedded-only behavior.
57
+ */
58
+ async sendCard(content, opts = {}) {
59
+ const {
60
+ text = "", title, description, thumbnail, thumbnailWidth = 192, url,
61
+ highQuality = true,
62
+ } = content;
63
+ if (!url) {
64
+ throw new Error(
65
+ 'sendCard() requires a "url" — WhatsApp only renders the preview box when the message text contains a matching link. Use sendButtons({ location, thumbnail }, …) instead if you need a card with no visible link.'
66
+ );
67
+ }
68
+ const jpegThumbnail = await resolveThumbnail(thumbnail, thumbnailWidth);
69
+ let highQualityThumbnail;
70
+ if (highQuality) {
71
+ try {
72
+ highQualityThumbnail = await resolveHighQualityThumbnail(this.sock, thumbnail);
73
+ } catch (err) {
74
+ this.sock?.logger?.debug?.(
75
+ { err },
76
+ "sendCard: high-quality thumbnail upload failed, falling back to embedded-only thumbnail"
77
+ );
78
+ }
79
+ }
80
+ const fullText = text.includes(url) ? text : `${text}${text ? "\n" : ""}${url}`;
81
+ return this.send(
82
+ {
83
+ text: fullText,
84
+ linkPreview: {
85
+ "matched-text": url,
86
+ title,
87
+ description,
88
+ jpegThumbnail,
89
+ ...(highQualityThumbnail ? { highQualityThumbnail } : {}),
90
+ },
91
+ },
92
+ { quoted: this.raw, ...opts }
93
+ );
94
+ },
95
+ };
package/src/index.js CHANGED
@@ -1,8 +1,13 @@
1
1
  export { Bot } from "./Bot.js";
2
2
  export { Context } from "./Context.js";
3
+ export { Quoted } from "./Quoted.js";
3
4
  export { PluginManager } from "./PluginManager.js";
4
5
  export { loadPlugins } from "./loader.js";
5
6
 
7
+ // Media + message-type utilities (advanced use — Context wraps these already).
8
+ export { downloadMedia, saveMedia, resolveMediaSource, toVcard } from "./media.js";
9
+ export { detectMessageType, isMediaType, extractPlainText } from "./utils/messageTypes.js";
10
+
6
11
  // Built-in middlewares (auto-registered by Bot).
7
12
  // Exported here for advanced users who need manual composition.
8
13
  export * as middlewares from "./middlewares/index.js";
@@ -16,3 +21,25 @@ export {
16
21
  useMultiFileAuthState,
17
22
  Dugong,
18
23
  } from "../vendor/core/lib/index.js";
24
+
25
+ // Rich-message re-exports (advanced use — Context's send* methods wrap
26
+ // these already; grab these directly if you need to build content by hand,
27
+ // e.g. outside of a Context, in a cron job, or for sock.sendMessage()).
28
+ export {
29
+ makeStickerPack,
30
+ RichSubMessageType,
31
+ CodeHighlightType,
32
+ tokenizeCode,
33
+ tokenizeCodeV2,
34
+ generateTableContent,
35
+ generateTableContentV2,
36
+ toTableMetadataV2,
37
+ generateListContent,
38
+ generateCodeBlockContent,
39
+ generateCodeBlockContentV2,
40
+ generateLinkContent,
41
+ generateLinkContentV2,
42
+ generateRichMessageContent,
43
+ generateUnifiedResponseContent,
44
+ captureUnifiedResponse,
45
+ } from "../vendor/core/lib/index.js";