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
|
@@ -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";
|
package/src/media.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* media
|
|
3
|
+
* -----
|
|
4
|
+
* Thin, framework-friendly wrapper around the vendored core's media
|
|
5
|
+
* download utility, plus a helper to normalise "give me an image from
|
|
6
|
+
* anywhere" input into the shape `sock.sendMessage` expects.
|
|
7
|
+
*/
|
|
8
|
+
import { createWriteStream } from "fs";
|
|
9
|
+
import { pipeline } from "stream/promises";
|
|
10
|
+
import { downloadMediaMessage, extractImageThumb, prepareWAMessageMedia } from "../vendor/core/lib/index.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Download the media attached to a WA message (image/video/audio/sticker/
|
|
14
|
+
* document — including inside view-once/ephemeral wrappers, which the core
|
|
15
|
+
* unwraps automatically).
|
|
16
|
+
*
|
|
17
|
+
* @param {import('../vendor/core/lib/index.js').WASocket} sock
|
|
18
|
+
* @param {import('../vendor/core/lib/index.js').proto.IWebMessageInfo} rawMessage
|
|
19
|
+
* A full WA message object (`{ key, message, ... }`) — either the
|
|
20
|
+
* triggering message (`ctx.raw`) or a reconstructed quoted message
|
|
21
|
+
* (`ctx.quoted.raw`).
|
|
22
|
+
* @param {{ asStream?: boolean }} [opts]
|
|
23
|
+
* `asStream: true` returns a readable stream instead of buffering the
|
|
24
|
+
* whole file in memory — use this for large files.
|
|
25
|
+
* @returns {Promise<Buffer | NodeJS.ReadableStream>}
|
|
26
|
+
*/
|
|
27
|
+
export async function downloadMedia(sock, rawMessage, opts = {}) {
|
|
28
|
+
return downloadMediaMessage(
|
|
29
|
+
rawMessage,
|
|
30
|
+
opts.asStream ? "stream" : "buffer",
|
|
31
|
+
{},
|
|
32
|
+
{
|
|
33
|
+
logger: sock?.logger,
|
|
34
|
+
// Lets the core automatically re-fetch + retry once if WA's media
|
|
35
|
+
// host returns 404/410 (link expired) — transparent to the caller.
|
|
36
|
+
reuploadRequest: sock?.updateMediaMessage,
|
|
37
|
+
}
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Download media straight to disk. Streams internally, so it's memory-safe
|
|
43
|
+
* for large files.
|
|
44
|
+
* @returns {Promise<string>} the filePath, for convenient chaining
|
|
45
|
+
*/
|
|
46
|
+
export async function saveMedia(sock, rawMessage, filePath, opts = {}) {
|
|
47
|
+
const stream = await downloadMedia(sock, rawMessage, {
|
|
48
|
+
...opts,
|
|
49
|
+
asStream: true,
|
|
50
|
+
});
|
|
51
|
+
await pipeline(stream, createWriteStream(filePath));
|
|
52
|
+
return filePath;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Normalises a "media source" into whatever `sock.sendMessage`'s
|
|
57
|
+
* `AnyMediaMessageContent` expects (`Buffer | { url } | { stream }`).
|
|
58
|
+
*
|
|
59
|
+
* Accepts:
|
|
60
|
+
* - a Buffer → passed through
|
|
61
|
+
* - a local file path (string) → `{ url: path }` (core reads it via fs)
|
|
62
|
+
* - an http(s) URL (string) → `{ url }` (core streams it)
|
|
63
|
+
* - a data: URL (string) → `{ url }` (core decodes it)
|
|
64
|
+
* - an already-shaped object → `{ url }` / `{ stream }` passed through
|
|
65
|
+
*/
|
|
66
|
+
export function resolveMediaSource(source) {
|
|
67
|
+
if (source === null || source === undefined) {
|
|
68
|
+
throw new TypeError("Media source is required");
|
|
69
|
+
}
|
|
70
|
+
if (typeof source === "string") return { url: source };
|
|
71
|
+
return source;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Turns "any image" (Buffer, local file path, or http(s) URL) into a small
|
|
76
|
+
* JPEG thumbnail Buffer — the shape `jpegThumbnail` fields on the proto
|
|
77
|
+
* (interactive-message headers, location cards, etc.) expect.
|
|
78
|
+
*
|
|
79
|
+
* Unlike `resolveMediaSource()` (which just wraps a source for WA's normal
|
|
80
|
+
* media-upload pipeline), this actually resizes + JPEG-encodes the image,
|
|
81
|
+
* since `jpegThumbnail` is embedded inline in the message rather than
|
|
82
|
+
* uploaded, and WA expects it small (default width mirrors what the core
|
|
83
|
+
* generates for its own auto-thumbnails).
|
|
84
|
+
*
|
|
85
|
+
* @param {Buffer | string} source
|
|
86
|
+
* @param {number} [width] Thumbnail width in px (default 192 — matches the
|
|
87
|
+
* core's own convention for embedded, non-uploaded thumbnails like link
|
|
88
|
+
* previews; safe and reliably accepted by WhatsApp). This field is
|
|
89
|
+
* embedded directly in the message rather than uploaded, so WA caps it
|
|
90
|
+
* hard — confirmed safe up to ~300px, confirmed rejected (falls back to
|
|
91
|
+
* a generic placeholder icon) at 400px. If you need a genuinely crisp
|
|
92
|
+
* image, use an `image` header (normal media upload, no such cap) with
|
|
93
|
+
* a Maps-link button instead of `location` — see the `locationhdbuttons`
|
|
94
|
+
* example in examples/simple-bot.js.
|
|
95
|
+
* @returns {Promise<Buffer>}
|
|
96
|
+
*/
|
|
97
|
+
export async function resolveThumbnail(source, width = 730) {
|
|
98
|
+
if (source === null || source === undefined) {
|
|
99
|
+
throw new TypeError("Thumbnail source is required");
|
|
100
|
+
}
|
|
101
|
+
let input = source;
|
|
102
|
+
if (typeof source === "string" && /^https?:\/\//i.test(source)) {
|
|
103
|
+
const res = await fetch(source);
|
|
104
|
+
if (!res.ok) {
|
|
105
|
+
throw new Error(`Failed to fetch thumbnail from ${source}: ${res.status}`);
|
|
106
|
+
}
|
|
107
|
+
input = Buffer.from(await res.arrayBuffer());
|
|
108
|
+
}
|
|
109
|
+
const { buffer } = await extractImageThumb(input, width);
|
|
110
|
+
return buffer;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Uploads a thumbnail image to WA's media CDN as a `thumbnail-link` — the
|
|
115
|
+
* exact mechanism WhatsApp's own client uses for real link-preview cards
|
|
116
|
+
* (`getUrlInfo()` + `uploadImage` in the vendored core). Returns an object
|
|
117
|
+
* shape ready to spread into a `linkPreview` content object as
|
|
118
|
+
* `highQualityThumbnail`, so the recipient's client re-fetches the actual
|
|
119
|
+
* full-resolution image from WA's servers instead of only ever seeing the
|
|
120
|
+
* small, quality-50 embedded `jpegThumbnail`.
|
|
121
|
+
*
|
|
122
|
+
* Requires network access (an upload round-trip), unlike `resolveThumbnail()`
|
|
123
|
+
* which is purely local/embedded. If the upload fails (offline, WA media
|
|
124
|
+
* host hiccup, etc.), the caller should catch and fall back to embedded-only
|
|
125
|
+
* — the card will still send, just blurrier.
|
|
126
|
+
*
|
|
127
|
+
* @param {import('../vendor/core/lib/index.js').WASocket} sock
|
|
128
|
+
* @param {Buffer|string} source Buffer, local file path, or http(s) URL.
|
|
129
|
+
* @returns {Promise<{directPath, mediaKey, mediaKeyTimestamp, width, height, fileSha256, fileEncSha256}|undefined>}
|
|
130
|
+
*/
|
|
131
|
+
export async function resolveHighQualityThumbnail(sock, source) {
|
|
132
|
+
if (source === null || source === undefined) {
|
|
133
|
+
throw new TypeError("Thumbnail source is required");
|
|
134
|
+
}
|
|
135
|
+
if (typeof sock?.waUploadToServer !== "function") {
|
|
136
|
+
throw new Error(
|
|
137
|
+
"resolveHighQualityThumbnail() requires sock.waUploadToServer — pass the live socket instance."
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
const { imageMessage } = await prepareWAMessageMedia(
|
|
141
|
+
{ image: resolveMediaSource(source) },
|
|
142
|
+
{ upload: sock.waUploadToServer, mediaTypeOverride: "thumbnail-link" }
|
|
143
|
+
);
|
|
144
|
+
if (!imageMessage) return undefined;
|
|
145
|
+
return {
|
|
146
|
+
directPath: imageMessage.directPath,
|
|
147
|
+
mediaKey: imageMessage.mediaKey,
|
|
148
|
+
mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
|
|
149
|
+
width: imageMessage.width,
|
|
150
|
+
height: imageMessage.height,
|
|
151
|
+
fileSha256: imageMessage.fileSha256,
|
|
152
|
+
fileEncSha256: imageMessage.fileEncSha256,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Builds a minimal WhatsApp-compatible vCard from a simple {name, number}. */
|
|
157
|
+
export function toVcard({ name, number, organization }) {
|
|
158
|
+
const waid = String(number).replace(/[^\d]/g, "");
|
|
159
|
+
const lines = [
|
|
160
|
+
"BEGIN:VCARD",
|
|
161
|
+
"VERSION:3.0",
|
|
162
|
+
`FN:${name}`,
|
|
163
|
+
...(organization ? [`ORG:${organization}`] : []),
|
|
164
|
+
`TEL;type=CELL;type=VOICE;waid=${waid}:${waid}`,
|
|
165
|
+
"END:VCARD",
|
|
166
|
+
];
|
|
167
|
+
return lines.join("\n");
|
|
168
|
+
}
|