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.
- package/README.md +216 -47
- package/package.json +15 -6
- package/src/Context.js +41 -157
- package/src/Quoted.js +86 -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/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
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* messageTypes
|
|
3
|
+
* ------------
|
|
4
|
+
* Maps a raw WA message (`rawMessage.message`) to a friendly Botify type
|
|
5
|
+
* string, plus the inner content object for that type.
|
|
6
|
+
*
|
|
7
|
+
* Uses the vendored core's own `getContentType` / `normalizeMessageContent`
|
|
8
|
+
* so ephemeral messages, view-once wrappers (v1/v2/v3), edited-message
|
|
9
|
+
* wrappers, and "document with caption" wrappers are all unwrapped
|
|
10
|
+
* automatically — the returned type/content always describes the *real*
|
|
11
|
+
* message, not the envelope around it.
|
|
12
|
+
*
|
|
13
|
+
* Covers every message type a bot realistically needs to branch on. Types
|
|
14
|
+
* that exist in the protocol but aren't meaningful for bot logic (delivery
|
|
15
|
+
* receipts, history sync payloads, low-level sender-key distribution, etc.)
|
|
16
|
+
* fall through to "unsupported" rather than getting their own case.
|
|
17
|
+
*/
|
|
18
|
+
import {
|
|
19
|
+
getContentType,
|
|
20
|
+
normalizeMessageContent,
|
|
21
|
+
} from "../../vendor/core/lib/index.js";
|
|
22
|
+
|
|
23
|
+
/** Raw WAProto content key → friendly Botify `ctx.type`. */
|
|
24
|
+
const TYPE_MAP = {
|
|
25
|
+
conversation: "text",
|
|
26
|
+
extendedTextMessage: "text",
|
|
27
|
+
|
|
28
|
+
imageMessage: "image",
|
|
29
|
+
videoMessage: "video",
|
|
30
|
+
ptvMessage: "video", // "video note" — still a video under the hood
|
|
31
|
+
audioMessage: "audio", // ctx.isPtt distinguishes voice notes
|
|
32
|
+
stickerMessage: "sticker",
|
|
33
|
+
documentMessage: "document",
|
|
34
|
+
|
|
35
|
+
contactMessage: "contact",
|
|
36
|
+
contactsArrayMessage: "contacts",
|
|
37
|
+
locationMessage: "location",
|
|
38
|
+
liveLocationMessage: "liveLocation",
|
|
39
|
+
|
|
40
|
+
pollCreationMessage: "poll",
|
|
41
|
+
pollCreationMessageV2: "poll",
|
|
42
|
+
pollCreationMessageV3: "poll",
|
|
43
|
+
pollCreationMessageV4: "poll",
|
|
44
|
+
pollCreationMessageV5: "poll",
|
|
45
|
+
pollCreationMessageV6: "poll",
|
|
46
|
+
pollUpdateMessage: "pollUpdate",
|
|
47
|
+
|
|
48
|
+
reactionMessage: "reaction",
|
|
49
|
+
|
|
50
|
+
buttonsMessage: "buttons",
|
|
51
|
+
buttonsResponseMessage: "buttonsResponse",
|
|
52
|
+
listMessage: "list",
|
|
53
|
+
listResponseMessage: "listResponse",
|
|
54
|
+
templateMessage: "template",
|
|
55
|
+
templateButtonReplyMessage: "templateButtonReply",
|
|
56
|
+
interactiveMessage: "interactive",
|
|
57
|
+
interactiveResponseMessage: "interactiveResponse",
|
|
58
|
+
|
|
59
|
+
groupInviteMessage: "groupInvite",
|
|
60
|
+
productMessage: "product",
|
|
61
|
+
orderMessage: "order",
|
|
62
|
+
eventMessage: "event",
|
|
63
|
+
|
|
64
|
+
protocolMessage: "protocol", // edit / delete(revoke) / disappearing-mode change
|
|
65
|
+
call: "call",
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Content keys that represent an actual media attachment. */
|
|
69
|
+
const MEDIA_TYPES = new Set(["image", "video", "audio", "sticker", "document"]);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {object | null | undefined} rawMessageContent `rawMessage.message`
|
|
73
|
+
* @returns {{ type: string, key: string | null, content: object | null }}
|
|
74
|
+
*/
|
|
75
|
+
export function detectMessageType(rawMessageContent) {
|
|
76
|
+
const normalized = normalizeMessageContent(rawMessageContent);
|
|
77
|
+
if (!normalized) return { type: "unknown", key: null, content: null };
|
|
78
|
+
|
|
79
|
+
const key = getContentType(normalized);
|
|
80
|
+
if (!key) return { type: "unknown", key: null, content: null };
|
|
81
|
+
|
|
82
|
+
const content = normalized[key];
|
|
83
|
+
const type = TYPE_MAP[key] ?? "unsupported";
|
|
84
|
+
|
|
85
|
+
return { type, key, content: content ?? {} };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Whether a Botify `type` string represents a downloadable media attachment. */
|
|
89
|
+
export function isMediaType(type) {
|
|
90
|
+
return MEDIA_TYPES.has(type);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Best-effort plain-text extraction — used for `ctx.text` / quoted text.
|
|
95
|
+
* Falls back through captions so `!command` still works if someone sends
|
|
96
|
+
* an image/video/document with the command in the caption.
|
|
97
|
+
*/
|
|
98
|
+
export function extractPlainText(rawMessageContent) {
|
|
99
|
+
const normalized = normalizeMessageContent(rawMessageContent);
|
|
100
|
+
if (!normalized) return "";
|
|
101
|
+
return (
|
|
102
|
+
normalized.conversation ??
|
|
103
|
+
normalized.extendedTextMessage?.text ??
|
|
104
|
+
normalized.imageMessage?.caption ??
|
|
105
|
+
normalized.videoMessage?.caption ??
|
|
106
|
+
normalized.documentMessage?.caption ??
|
|
107
|
+
normalized.buttonsResponseMessage?.selectedDisplayText ??
|
|
108
|
+
normalized.listResponseMessage?.title ??
|
|
109
|
+
normalized.templateButtonReplyMessage?.selectedDisplayText ??
|
|
110
|
+
extractNativeFlowId(normalized.interactiveResponseMessage) ??
|
|
111
|
+
""
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Native-flow buttons/list menus (`interactiveMessage`, sent via
|
|
117
|
+
* `ctx.sendButtons()` / `ctx.sendListMenu()`) don't reply with a
|
|
118
|
+
* `selectedDisplayText` — WhatsApp echoes back an `interactiveResponseMessage`
|
|
119
|
+
* whose `nativeFlowResponseMessage.paramsJson` is a JSON string containing
|
|
120
|
+
* the tapped button/row's `id`. This pulls that `id` out (or `null` if the
|
|
121
|
+
* message isn't a native-flow response, or the JSON is malformed).
|
|
122
|
+
*/
|
|
123
|
+
export function extractNativeFlowId(interactiveResponseMessage) {
|
|
124
|
+
const paramsJson = interactiveResponseMessage?.nativeFlowResponseMessage?.paramsJson;
|
|
125
|
+
if (!paramsJson) return null;
|
|
126
|
+
try {
|
|
127
|
+
return JSON.parse(paramsJson)?.id ?? null;
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -322,6 +322,16 @@ export class Dugong {
|
|
|
322
322
|
degreesLongitude:
|
|
323
323
|
location.degressLongitude || location.degreesLongitude || 0,
|
|
324
324
|
name: location.name || "",
|
|
325
|
+
address: location.address || "",
|
|
326
|
+
// Custom thumbnail overrides WA's auto-generated map snapshot.
|
|
327
|
+
...(jpegThumbnail
|
|
328
|
+
? {
|
|
329
|
+
jpegThumbnail:
|
|
330
|
+
typeof jpegThumbnail === "string"
|
|
331
|
+
? Buffer.from(jpegThumbnail, "base64")
|
|
332
|
+
: jpegThumbnail,
|
|
333
|
+
}
|
|
334
|
+
: {}),
|
|
325
335
|
},
|
|
326
336
|
};
|
|
327
337
|
mediaAttached =
|
|
@@ -765,4 +775,4 @@ export class Dugong {
|
|
|
765
775
|
return msg;
|
|
766
776
|
}
|
|
767
777
|
}
|
|
768
|
-
//# sourceMappingURL=dugong.js.map
|
|
778
|
+
//# sourceMappingURL=dugong.js.map
|