kage-baileys 25.0.7 → 25.0.8
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/lib/Socket/index.js +122 -37
- package/lib/Utils/kage-airich.js +398 -0
- package/lib/Utils/kage-media-resolve.js +266 -0
- package/lib/Utils/kage-rich-methods.js +304 -0
- package/lib/Utils/kage-send-table.js +79 -0
- package/lib/index.js +75 -0
- package/package.json +4 -2
package/lib/Socket/index.js
CHANGED
|
@@ -5,11 +5,11 @@ const Defaults_1 = require("../Defaults");
|
|
|
5
5
|
const business_1 = require("./communities");
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* makeWASocket –
|
|
9
|
-
* -
|
|
10
|
-
* -
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
8
|
+
* makeWASocket – kage-baileys 25.0.10-compat
|
|
9
|
+
* - MessageBuilder seguro (objetos no extensibles)
|
|
10
|
+
* - AIRich integrado (sin lib externa)
|
|
11
|
+
* - Media: base64 / Buffer / URL / path + jimp/sharp opcional
|
|
12
|
+
* - Relay optimizado para pintar mensajes al instante (sin salir del chat)
|
|
13
13
|
*/
|
|
14
14
|
const makeWASocket = (config = {}) => {
|
|
15
15
|
try {
|
|
@@ -27,7 +27,6 @@ const makeWASocket = (config = {}) => {
|
|
|
27
27
|
finalConfig.shouldSyncHistoryMessage = () => !!finalConfig.syncFullHistory;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
// Protección temporal contra asignaciones a MessageBuilder en funciones no extensibles
|
|
31
30
|
const origDefineProperty = Object.defineProperty;
|
|
32
31
|
let definePatched = false;
|
|
33
32
|
try {
|
|
@@ -59,7 +58,6 @@ const makeWASocket = (config = {}) => {
|
|
|
59
58
|
try { require('../Utils/profile-tools').installProfileTools(socket, config); } catch (_) {}
|
|
60
59
|
|
|
61
60
|
// ---- MessageBuilder (seguro) ----
|
|
62
|
-
// Nunca hacemos: boundFn.MessageBuilder = ... (bound functions no son extensibles)
|
|
63
61
|
try {
|
|
64
62
|
const { MessageBuilder } = require('../Utils/message-builder');
|
|
65
63
|
let moddedFn = null;
|
|
@@ -68,7 +66,6 @@ const makeWASocket = (config = {}) => {
|
|
|
68
66
|
moddedFn = typeof mod === 'function' ? mod : (mod && mod.default);
|
|
69
67
|
} catch (_) {}
|
|
70
68
|
|
|
71
|
-
// Función usable: messageBuilder(...)
|
|
72
69
|
const builderFn = function (...args) {
|
|
73
70
|
if (typeof moddedFn === 'function') {
|
|
74
71
|
try { return moddedFn.apply(socket, args); } catch (_) {}
|
|
@@ -76,51 +73,139 @@ const makeWASocket = (config = {}) => {
|
|
|
76
73
|
return new MessageBuilder(socket, ...args);
|
|
77
74
|
};
|
|
78
75
|
|
|
79
|
-
// Objeto extensible que también es invocable
|
|
80
|
-
// Usamos Object.create(Function.prototype) + assign para máxima compatibilidad
|
|
81
76
|
const mb = Object.assign(builderFn, {
|
|
82
|
-
MessageBuilder,
|
|
77
|
+
MessageBuilder,
|
|
83
78
|
create: () => new MessageBuilder(socket),
|
|
84
|
-
VERSION: '4.
|
|
79
|
+
VERSION: '4.9-instant'
|
|
85
80
|
});
|
|
86
81
|
|
|
87
|
-
|
|
88
|
-
try {
|
|
89
|
-
socket.messageBuilder = mb;
|
|
90
|
-
} catch (_) {
|
|
82
|
+
try { socket.messageBuilder = mb; } catch (_) {
|
|
91
83
|
try {
|
|
92
|
-
Object.defineProperty(socket, 'messageBuilder', {
|
|
93
|
-
value: mb,
|
|
94
|
-
writable: true,
|
|
95
|
-
configurable: true,
|
|
96
|
-
enumerable: true
|
|
97
|
-
});
|
|
84
|
+
Object.defineProperty(socket, 'messageBuilder', { value: mb, writable: true, configurable: true, enumerable: true });
|
|
98
85
|
} catch (_) {}
|
|
99
86
|
}
|
|
100
|
-
|
|
101
|
-
try {
|
|
102
|
-
socket.createMessageBuilder = () => new MessageBuilder(socket);
|
|
103
|
-
} catch (_) {}
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
socket.MessageBuilder = MessageBuilder;
|
|
107
|
-
} catch (_) {
|
|
87
|
+
try { socket.createMessageBuilder = () => new MessageBuilder(socket); } catch (_) {}
|
|
88
|
+
try { socket.MessageBuilder = MessageBuilder; } catch (_) {
|
|
108
89
|
try {
|
|
109
|
-
Object.defineProperty(socket, 'MessageBuilder', {
|
|
110
|
-
value: MessageBuilder,
|
|
111
|
-
writable: true,
|
|
112
|
-
configurable: true,
|
|
113
|
-
enumerable: true
|
|
114
|
-
});
|
|
90
|
+
Object.defineProperty(socket, 'MessageBuilder', { value: MessageBuilder, writable: true, configurable: true, enumerable: true });
|
|
115
91
|
} catch (_) {}
|
|
116
92
|
}
|
|
117
93
|
} catch (e) {
|
|
118
|
-
// Silenciar errores de MessageBuilder para no romper el socket
|
|
119
94
|
if (config && config.logger) {
|
|
120
95
|
try { config.logger.warn?.({ err: e }, 'MessageBuilder attach failed (non-fatal)'); } catch (_) {}
|
|
121
96
|
}
|
|
122
97
|
}
|
|
123
98
|
|
|
99
|
+
// ---- AIRich + media integrados (estilo zapo, nativo kage) ----
|
|
100
|
+
try {
|
|
101
|
+
const { KageAIRich, AIRich, createAIRich } = require('../Utils/kage-airich');
|
|
102
|
+
const media = require('../Utils/kage-media-resolve');
|
|
103
|
+
|
|
104
|
+
const attach = (key, value) => {
|
|
105
|
+
try {
|
|
106
|
+
socket[key] = value;
|
|
107
|
+
} catch (_) {
|
|
108
|
+
try {
|
|
109
|
+
Object.defineProperty(socket, key, {
|
|
110
|
+
value,
|
|
111
|
+
writable: true,
|
|
112
|
+
configurable: true,
|
|
113
|
+
enumerable: true
|
|
114
|
+
});
|
|
115
|
+
} catch (_) {}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
attach('AIRich', AIRich);
|
|
120
|
+
attach('KageAIRich', KageAIRich);
|
|
121
|
+
attach('createAIRich', () => createAIRich(socket));
|
|
122
|
+
attach('airich', () => createAIRich(socket));
|
|
123
|
+
attach('resolveMedia', (src, opts) => media.toBuffer(src, opts));
|
|
124
|
+
attach('resolveRichImage', (src, opts) => media.resolveRichImage(socket, src, opts));
|
|
125
|
+
attach('resolvePublicImageUrl', (src, opts) => media.resolvePublicImageUrl(socket, src, opts));
|
|
126
|
+
attach('resolveImageForSend', (src, opts) => media.resolveImageForSend(socket, src, opts));
|
|
127
|
+
attach('DEFAULT_IMAGE', media.DEFAULT_IMAGE);
|
|
128
|
+
attach('toBuffer', (src, opts) => media.toBuffer(src, opts));
|
|
129
|
+
try { require('../Utils/kage-send-table').installSendTable(socket); } catch (_) {}
|
|
130
|
+
try { require('../Utils/kage-rich-methods').installRichMethods(socket); } catch (_) {}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
// sendMessage: acepta base64, data-URI, path, Buffer en image/video/audio/document/sticker
|
|
134
|
+
const origSend = socket.sendMessage?.bind(socket);
|
|
135
|
+
if (typeof origSend === 'function') {
|
|
136
|
+
const normalizeField = async (val) => {
|
|
137
|
+
if (val == null) return val;
|
|
138
|
+
if (Buffer.isBuffer(val) || val instanceof Uint8Array) return Buffer.from(val);
|
|
139
|
+
if (typeof val === 'string') {
|
|
140
|
+
// URL http: Baileys descarga solo; base64/data-URI/path → Buffer
|
|
141
|
+
if (/^https?:\/\//i.test(val)) return { url: val };
|
|
142
|
+
const buf = await media.toBuffer(val);
|
|
143
|
+
return buf || val;
|
|
144
|
+
}
|
|
145
|
+
if (typeof val === 'object') {
|
|
146
|
+
if (val.url || val.stream) return val;
|
|
147
|
+
if (val.base64) {
|
|
148
|
+
const buf = await media.toBuffer(val.base64);
|
|
149
|
+
return buf || val;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return val;
|
|
153
|
+
};
|
|
154
|
+
socket.sendMessage = async (jid, content, options = {}) => {
|
|
155
|
+
try {
|
|
156
|
+
if (content && typeof content === 'object') {
|
|
157
|
+
for (const key of ['image', 'video', 'audio', 'document', 'sticker']) {
|
|
158
|
+
if (content[key] != null) {
|
|
159
|
+
content = { ...content, [key]: await normalizeField(content[key]) };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
} catch (_) {}
|
|
164
|
+
return origSend(jid, content, options);
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Helpers directos en sock
|
|
169
|
+
attach('toBuffer', (src, opts) => media.toBuffer(src, opts));
|
|
170
|
+
attach('uploadPublicImage', async (src, opts) => {
|
|
171
|
+
const buf = await media.toBuffer(src, opts);
|
|
172
|
+
if (!buf) return media.DEFAULT_IMAGE;
|
|
173
|
+
const resized = await media.maybeResize(buf, opts);
|
|
174
|
+
return media.DEFAULT_IMAGE;
|
|
175
|
+
});
|
|
176
|
+
attach('prepareImage', (src, opts) => media.resolveImageForSend(socket, src, opts));
|
|
177
|
+
|
|
178
|
+
// relayMessage: asegurar options que ayudan a pintar al instante
|
|
179
|
+
const origRelay = socket.relayMessage?.bind(socket);
|
|
180
|
+
if (typeof origRelay === 'function') {
|
|
181
|
+
socket.relayMessage = async (jid, message, options = {}) => {
|
|
182
|
+
const opts = {
|
|
183
|
+
...options,
|
|
184
|
+
// no retrasar por ack de historial
|
|
185
|
+
...(options.status === undefined ? {} : { status: options.status }),
|
|
186
|
+
};
|
|
187
|
+
// messageSecret en rich ayuda a algunos clientes a renderizar sin reabrir
|
|
188
|
+
try {
|
|
189
|
+
if (message?.botForwardedMessage && !message.messageContextInfo) {
|
|
190
|
+
message = {
|
|
191
|
+
messageContextInfo: {
|
|
192
|
+
deviceListMetadata: {},
|
|
193
|
+
deviceListMetadataVersion: 2,
|
|
194
|
+
messageSecret: require('crypto').randomBytes(32),
|
|
195
|
+
},
|
|
196
|
+
...message,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
} catch (_) {}
|
|
200
|
+
return origRelay(jid, message, opts);
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
} catch (e) {
|
|
204
|
+
if (config && config.logger) {
|
|
205
|
+
try { config.logger.warn?.({ err: e }, 'AIRich/media attach failed (non-fatal)'); } catch (_) {}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
124
209
|
try {
|
|
125
210
|
return require('../Utils/automation-tools').installKageTools(socket, config.kageTools || {});
|
|
126
211
|
} catch (_) {
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kage AIRich — rich messages nativos desde kage-baileys
|
|
3
|
+
* - Un solo relay (contenido completo) → se ve al instante sin salir del chat
|
|
4
|
+
* - Imágenes product con URL pública (evita blanco)
|
|
5
|
+
* - Sin dependencia externa de chiaki-builder / zapo
|
|
6
|
+
*/
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const crypto = require('crypto');
|
|
10
|
+
const messages = require('./messages.js');
|
|
11
|
+
const generics = require('./generics.js');
|
|
12
|
+
const { resolvePublicImageUrl, resolveRichImage, DEFAULT_IMAGE } = require('./kage-media-resolve.js');
|
|
13
|
+
|
|
14
|
+
let genFromContent = messages.generateWAMessageFromContent;
|
|
15
|
+
let genId = generics.generateMessageIDV2 || messages.generateMessageIDV2;
|
|
16
|
+
if (typeof genId !== 'function') {
|
|
17
|
+
genId = () => crypto.randomBytes(8).toString('hex').toUpperCase();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const TN = {
|
|
21
|
+
TEXT: 'GenAIMarkdownTextUXPrimitive',
|
|
22
|
+
PRODUCT: 'GenAIProductUXPrimitive',
|
|
23
|
+
METADATA: 'GenAIMarkdownMetadataTextUXPrimitive',
|
|
24
|
+
FOOTER_ACTION: 'GenAIFooterActionUXPrimitive',
|
|
25
|
+
SUGGEST: 'GenAISuggestionPillUXPrimitive',
|
|
26
|
+
TABLE: 'GenAITableUXPrimitive',
|
|
27
|
+
HTML: 'GenAIaeacdsnwHtmlPrimitive',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function layout(name, data) {
|
|
31
|
+
if (Array.isArray(data)) {
|
|
32
|
+
return {
|
|
33
|
+
view_model: {
|
|
34
|
+
primitives: data,
|
|
35
|
+
__typename: `GenAI${name}LayoutViewModel`,
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
view_model: {
|
|
41
|
+
primitive: data,
|
|
42
|
+
__typename: `GenAI${name}LayoutViewModel`,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function stringifyEscaped(obj) {
|
|
48
|
+
return JSON.stringify(obj).replace(
|
|
49
|
+
/[\u007f-\uffff]/g,
|
|
50
|
+
(c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class KageAIRich {
|
|
55
|
+
constructor(sock) {
|
|
56
|
+
if (!sock || typeof sock.relayMessage !== 'function') {
|
|
57
|
+
throw new TypeError('KageAIRich requiere un socket Baileys con relayMessage');
|
|
58
|
+
}
|
|
59
|
+
this.sock = sock;
|
|
60
|
+
this._title = '';
|
|
61
|
+
this._footer = '';
|
|
62
|
+
this._sections = [];
|
|
63
|
+
this._submessages = [];
|
|
64
|
+
this._contextInfo = {};
|
|
65
|
+
this._lastKey = null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
setTitle(t) {
|
|
69
|
+
this._title = String(t || '');
|
|
70
|
+
return this;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
setFooter(t) {
|
|
74
|
+
this._footer = String(t || '');
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
setContextInfo(ci) {
|
|
79
|
+
if (ci && typeof ci === 'object') this._contextInfo = { ...this._contextInfo, ...ci };
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
addText(text) {
|
|
84
|
+
const t = String(text ?? '');
|
|
85
|
+
this._sections.push(
|
|
86
|
+
layout('Single', { text: t, __typename: TN.TEXT })
|
|
87
|
+
);
|
|
88
|
+
this._submessages.push({ messageType: 2, messageText: t });
|
|
89
|
+
return this;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
addTable(rows) {
|
|
93
|
+
if (!Array.isArray(rows)) throw new TypeError('Table must be array');
|
|
94
|
+
// Formato simple: filas de celdas string
|
|
95
|
+
const cells = rows.map((r) =>
|
|
96
|
+
(Array.isArray(r) ? r : [r]).map((c) => String(c ?? ''))
|
|
97
|
+
);
|
|
98
|
+
this._sections.push(
|
|
99
|
+
layout('Single', {
|
|
100
|
+
__typename: TN.TABLE,
|
|
101
|
+
rows: cells,
|
|
102
|
+
table: cells,
|
|
103
|
+
})
|
|
104
|
+
);
|
|
105
|
+
this._submessages.push({
|
|
106
|
+
messageType: 2,
|
|
107
|
+
messageText: cells.map((r) => r.join(' | ')).join('\n'),
|
|
108
|
+
});
|
|
109
|
+
return this;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Product cards — image debe ser URL http pública (no pps.whatsapp.net)
|
|
114
|
+
* Acepta string URL, o se normaliza con resolvePublicImageUrl en send()
|
|
115
|
+
*/
|
|
116
|
+
addProduct(data) {
|
|
117
|
+
const items = Array.isArray(data) ? data : [data];
|
|
118
|
+
this._pendingProducts = this._pendingProducts || [];
|
|
119
|
+
this._pendingProducts.push(...items);
|
|
120
|
+
return this;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
addSuggest(prompts) {
|
|
124
|
+
const list = Array.isArray(prompts) ? prompts : [prompts];
|
|
125
|
+
this._sections.push(
|
|
126
|
+
layout(
|
|
127
|
+
'HScroll',
|
|
128
|
+
list.map((p) => ({
|
|
129
|
+
prompt_text: String(p),
|
|
130
|
+
category: 'ADD',
|
|
131
|
+
__typename: TN.SUGGEST,
|
|
132
|
+
}))
|
|
133
|
+
)
|
|
134
|
+
);
|
|
135
|
+
return this;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
addFooterAction({ text, url, cta_text, cta_url } = {}) {
|
|
139
|
+
this._sections.push(
|
|
140
|
+
layout('Single', {
|
|
141
|
+
__typename: TN.FOOTER_ACTION,
|
|
142
|
+
cta_text: text || cta_text || 'Open',
|
|
143
|
+
cta_type: 'GENERATE_IMAGE',
|
|
144
|
+
cta_url: url || cta_url || '',
|
|
145
|
+
})
|
|
146
|
+
);
|
|
147
|
+
return this;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
addMetadata(text) {
|
|
151
|
+
this._sections.push(
|
|
152
|
+
layout('Single', { text: String(text || ''), __typename: TN.METADATA })
|
|
153
|
+
);
|
|
154
|
+
this._submessages.push({ messageType: 2, messageText: String(text || '') });
|
|
155
|
+
return this;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** HTML interactivo (juegos) */
|
|
159
|
+
addHtml(html, { title = 'Chiaki', url = 'https://chiaki.dev' } = {}) {
|
|
160
|
+
this._htmlPayload = { html: String(html || ''), title, url };
|
|
161
|
+
return this;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async #resolveProducts() {
|
|
165
|
+
if (!this._pendingProducts?.length) return;
|
|
166
|
+
const products = [];
|
|
167
|
+
for (const item of this._pendingProducts) {
|
|
168
|
+
const rawImg = item.image_url ?? item.image ?? DEFAULT_IMAGE;
|
|
169
|
+
let imgUrl = DEFAULT_IMAGE;
|
|
170
|
+
let thumb = null;
|
|
171
|
+
try {
|
|
172
|
+
const resolved = await resolveRichImage(this.sock, rawImg, { width: 640, height: 640 });
|
|
173
|
+
imgUrl = resolved.url || DEFAULT_IMAGE;
|
|
174
|
+
thumb = resolved.thumbBase64;
|
|
175
|
+
} catch {
|
|
176
|
+
try {
|
|
177
|
+
imgUrl = await resolvePublicImageUrl(this.sock, rawImg);
|
|
178
|
+
} catch {
|
|
179
|
+
imgUrl = DEFAULT_IMAGE;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const imageObj = { url: imgUrl || DEFAULT_IMAGE };
|
|
184
|
+
if (thumb) {
|
|
185
|
+
imageObj.thumbnail = thumb;
|
|
186
|
+
imageObj.jpegThumbnail = thumb;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
products.push({
|
|
190
|
+
title: item.title || 'Item',
|
|
191
|
+
brand: item.brand || '',
|
|
192
|
+
price: item.price || '',
|
|
193
|
+
sale_price: item.sale_price || item.salePrice || '',
|
|
194
|
+
product_url: item.product_url ?? item.url ?? '',
|
|
195
|
+
image: imageObj,
|
|
196
|
+
additional_images: [],
|
|
197
|
+
__typename: TN.PRODUCT,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
this._sections.unshift(
|
|
201
|
+
layout(products.length > 1 ? 'HScroll' : 'Single', products.length > 1 ? products : products[0])
|
|
202
|
+
);
|
|
203
|
+
this._pendingProducts = [];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async build(jid, { quoted } = {}) {
|
|
207
|
+
await this.#resolveProducts();
|
|
208
|
+
|
|
209
|
+
let sections = [...this._sections];
|
|
210
|
+
let submessages = [...this._submessages];
|
|
211
|
+
|
|
212
|
+
// HTML game payload
|
|
213
|
+
if (this._htmlPayload?.html) {
|
|
214
|
+
const { html, title, url } = this._htmlPayload;
|
|
215
|
+
const responseId = `kage_${Date.now()}_${crypto.randomBytes(3).toString('hex')}`;
|
|
216
|
+
const payload = {
|
|
217
|
+
response_id: responseId,
|
|
218
|
+
sections: [
|
|
219
|
+
{
|
|
220
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
221
|
+
view_model: {
|
|
222
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
223
|
+
primitive: {
|
|
224
|
+
__typename: 'GenAIBotProgressStatusPrimitive',
|
|
225
|
+
title,
|
|
226
|
+
is_in_progress: true,
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
],
|
|
231
|
+
embedded_screens: [
|
|
232
|
+
{
|
|
233
|
+
title,
|
|
234
|
+
content: [
|
|
235
|
+
{
|
|
236
|
+
__typename: 'FOAIDNixelButtonSheets',
|
|
237
|
+
tabs: [
|
|
238
|
+
{
|
|
239
|
+
id: 'tab_0',
|
|
240
|
+
tab_header: String(title).slice(0, 24),
|
|
241
|
+
sections: [
|
|
242
|
+
{
|
|
243
|
+
__typename: 'GenAIUnifiedResponseSection',
|
|
244
|
+
view_model: {
|
|
245
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
246
|
+
primitive: {
|
|
247
|
+
__typename: TN.HTML,
|
|
248
|
+
payload: html,
|
|
249
|
+
url: url || 'https://chiaki.dev',
|
|
250
|
+
trusted_sources: ['chiaki.dev'],
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
],
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
},
|
|
258
|
+
],
|
|
259
|
+
step_entries: [],
|
|
260
|
+
},
|
|
261
|
+
],
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const contextInfo = {
|
|
265
|
+
forwardingScore: 1,
|
|
266
|
+
isForwarded: true,
|
|
267
|
+
forwardedAiBotMessageInfo: { botJid: '0@bot' },
|
|
268
|
+
forwardOrigin: 4,
|
|
269
|
+
...this._contextInfo,
|
|
270
|
+
};
|
|
271
|
+
if (quoted?.key) {
|
|
272
|
+
contextInfo.stanzaId = quoted.key.id;
|
|
273
|
+
contextInfo.participant =
|
|
274
|
+
quoted.key.participant || quoted.participant || quoted.key.remoteJid;
|
|
275
|
+
contextInfo.quotedMessage = quoted.message;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return {
|
|
279
|
+
message: {
|
|
280
|
+
messageContextInfo: {
|
|
281
|
+
deviceListMetadata: {},
|
|
282
|
+
deviceListMetadataVersion: 2,
|
|
283
|
+
messageSecret: crypto.randomBytes(32),
|
|
284
|
+
botMetadata: {
|
|
285
|
+
messageDisclaimerText: title || this._title,
|
|
286
|
+
botResponseId: responseId,
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
botForwardedMessage: {
|
|
290
|
+
message: {
|
|
291
|
+
richResponseMessage: {
|
|
292
|
+
messageType: 1,
|
|
293
|
+
unifiedResponse: {
|
|
294
|
+
data: Buffer.from(JSON.stringify(payload)).toString('base64'),
|
|
295
|
+
},
|
|
296
|
+
contextInfo,
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
key: { remoteJid: jid, fromMe: true, id: genId() },
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (this._footer) {
|
|
306
|
+
sections.push(layout('Single', { text: this._footer, __typename: TN.TEXT }));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const responseId = crypto.randomUUID();
|
|
310
|
+
const botResponseId = crypto.randomUUID();
|
|
311
|
+
|
|
312
|
+
const contextInfo = {
|
|
313
|
+
forwardingScore: 1,
|
|
314
|
+
isForwarded: true,
|
|
315
|
+
forwardedAiBotMessageInfo: { botJid: '0@bot' },
|
|
316
|
+
forwardOrigin: 4,
|
|
317
|
+
...this._contextInfo,
|
|
318
|
+
};
|
|
319
|
+
if (quoted?.key) {
|
|
320
|
+
contextInfo.stanzaId = quoted.key.id;
|
|
321
|
+
contextInfo.participant =
|
|
322
|
+
quoted.key.participant || quoted.participant || quoted.key.remoteJid;
|
|
323
|
+
contextInfo.quotedMessage = quoted.message;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const content = {
|
|
327
|
+
messageContextInfo: {
|
|
328
|
+
deviceListMetadata: {},
|
|
329
|
+
deviceListMetadataVersion: 2,
|
|
330
|
+
messageSecret: crypto.randomBytes(32),
|
|
331
|
+
botMetadata: {
|
|
332
|
+
messageDisclaimerText: this._title || '',
|
|
333
|
+
botResponseId,
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
botForwardedMessage: {
|
|
337
|
+
message: {
|
|
338
|
+
richResponseMessage: {
|
|
339
|
+
messageType: 1,
|
|
340
|
+
submessages,
|
|
341
|
+
unifiedResponse: {
|
|
342
|
+
data: Buffer.from(
|
|
343
|
+
stringifyEscaped({ response_id: responseId, sections })
|
|
344
|
+
).toString('base64'),
|
|
345
|
+
},
|
|
346
|
+
contextInfo,
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const messageId = genId();
|
|
353
|
+
if (typeof genFromContent === 'function') {
|
|
354
|
+
try {
|
|
355
|
+
const msg = genFromContent(jid, content, { messageId });
|
|
356
|
+
return msg;
|
|
357
|
+
} catch {}
|
|
358
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
message: content,
|
|
361
|
+
key: { remoteJid: jid, fromMe: true, id: messageId },
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Envío único — contenido completo de una vez (se ve al instante, sin reabrir chat)
|
|
367
|
+
* NO hace sendEdit (evita warning de seguridad y retrasos)
|
|
368
|
+
*/
|
|
369
|
+
async send(jid, options = {}) {
|
|
370
|
+
const { quoted, mentions, additionalNodes = [] } = options;
|
|
371
|
+
if (mentions?.length) {
|
|
372
|
+
this._contextInfo.mentionedJid = mentions;
|
|
373
|
+
}
|
|
374
|
+
const msg = await this.build(jid, { quoted });
|
|
375
|
+
const messageId = msg.key?.id || genId();
|
|
376
|
+
|
|
377
|
+
await this.sock.relayMessage(jid, msg.message, {
|
|
378
|
+
messageId,
|
|
379
|
+
additionalNodes,
|
|
380
|
+
// ayuda a que el cliente pinte el mensaje de inmediato
|
|
381
|
+
status: 1,
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
this._lastKey = { remoteJid: jid, fromMe: true, id: messageId };
|
|
385
|
+
return { key: this._lastKey, message: msg.message };
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function createAIRich(sock) {
|
|
390
|
+
return new KageAIRich(sock);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
module.exports = {
|
|
394
|
+
KageAIRich,
|
|
395
|
+
AIRich: KageAIRich,
|
|
396
|
+
createAIRich,
|
|
397
|
+
DEFAULT_IMAGE,
|
|
398
|
+
};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media kage: base64, data-URI, Buffer, URL, path
|
|
3
|
+
* Para AIRich: descargar + subir a WA (mediaUrl) para que NO salga en blanco
|
|
4
|
+
*/
|
|
5
|
+
'use strict';
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
function getPrepareWAMessageMedia() {
|
|
10
|
+
return require('./messages.js').prepareWAMessageMedia;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const DEFAULT_IMAGE = 'https://i.imgur.com/TuItj4L.png';
|
|
14
|
+
|
|
15
|
+
function isHttpUrl(s) {
|
|
16
|
+
return typeof s === 'string' && /^https?:\/\//i.test(String(s).trim());
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function isDataUri(s) {
|
|
20
|
+
return typeof s === 'string' && /^data:[a-zA-Z0-9/+.-]+;base64,/i.test(s);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isProbablyBase64(s) {
|
|
24
|
+
if (typeof s !== 'string' || s.length < 32) return false;
|
|
25
|
+
const t = s.replace(/\s/g, '');
|
|
26
|
+
return /^[A-Za-z0-9+/=]+$/.test(t.slice(0, 120));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function loadSharp() {
|
|
30
|
+
try { return require('sharp'); } catch { return null; }
|
|
31
|
+
}
|
|
32
|
+
async function loadJimp() {
|
|
33
|
+
try { return require('jimp'); } catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function toBuffer(source, { timeoutMs = 15000, maxBytes = 30 * 1024 * 1024 } = {}) {
|
|
37
|
+
if (source == null) return null;
|
|
38
|
+
if (Buffer.isBuffer(source)) return source.length ? source : null;
|
|
39
|
+
if (source instanceof Uint8Array) return Buffer.from(source);
|
|
40
|
+
|
|
41
|
+
if (typeof source === 'object') {
|
|
42
|
+
if (Buffer.isBuffer(source.buffer)) return source.buffer;
|
|
43
|
+
if (typeof source.base64 === 'string') return toBuffer(source.base64, { timeoutMs, maxBytes });
|
|
44
|
+
if (typeof source.data === 'string') return toBuffer(source.data, { timeoutMs, maxBytes });
|
|
45
|
+
if (typeof source.url === 'string') return toBuffer(source.url, { timeoutMs, maxBytes });
|
|
46
|
+
if (typeof source.path === 'string') return toBuffer(source.path, { timeoutMs, maxBytes });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (typeof source !== 'string') return null;
|
|
50
|
+
const s = source.trim();
|
|
51
|
+
|
|
52
|
+
if (isDataUri(s)) {
|
|
53
|
+
const buf = Buffer.from(s.split(',')[1] || '', 'base64');
|
|
54
|
+
return buf.length ? buf : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (isHttpUrl(s)) {
|
|
58
|
+
try {
|
|
59
|
+
const ctrl = new AbortController();
|
|
60
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
61
|
+
const res = await fetch(s, {
|
|
62
|
+
signal: ctrl.signal,
|
|
63
|
+
headers: {
|
|
64
|
+
'User-Agent': 'Mozilla/5.0 (compatible; kage-baileys/25)',
|
|
65
|
+
Accept: 'image/*,video/*,*/*',
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
clearTimeout(t);
|
|
69
|
+
if (!res.ok) return null;
|
|
70
|
+
const ab = await res.arrayBuffer();
|
|
71
|
+
if (ab.byteLength > maxBytes) return null;
|
|
72
|
+
return Buffer.from(ab);
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
const p = path.isAbsolute(s) ? s : path.resolve(s);
|
|
80
|
+
if (fs.existsSync(p) && fs.statSync(p).isFile()) {
|
|
81
|
+
if (fs.statSync(p).size > maxBytes) return null;
|
|
82
|
+
return fs.readFileSync(p);
|
|
83
|
+
}
|
|
84
|
+
} catch {}
|
|
85
|
+
|
|
86
|
+
if (isProbablyBase64(s)) {
|
|
87
|
+
try {
|
|
88
|
+
const buf = Buffer.from(s.replace(/\s/g, ''), 'base64');
|
|
89
|
+
return buf.length > 16 ? buf : null;
|
|
90
|
+
} catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function maybeResize(buffer, { width = 800, height = 800, quality = 85, format = 'jpeg' } = {}) {
|
|
98
|
+
if (!buffer) return buffer;
|
|
99
|
+
const sharp = await loadSharp();
|
|
100
|
+
if (sharp) {
|
|
101
|
+
try {
|
|
102
|
+
let p = sharp(buffer).rotate();
|
|
103
|
+
if (width || height) {
|
|
104
|
+
p = p.resize(width || null, height || null, { fit: 'inside', withoutEnlargement: true });
|
|
105
|
+
}
|
|
106
|
+
if (format === 'png') return await p.png().toBuffer();
|
|
107
|
+
if (format === 'webp') return await p.webp({ quality }).toBuffer();
|
|
108
|
+
return await p.jpeg({ quality, mozjpeg: true }).toBuffer();
|
|
109
|
+
} catch {}
|
|
110
|
+
}
|
|
111
|
+
const Jimp = await loadJimp();
|
|
112
|
+
if (Jimp) {
|
|
113
|
+
try {
|
|
114
|
+
const img = await Jimp.read(buffer);
|
|
115
|
+
if (width || height) img.scaleToFit(width || Jimp.AUTO, height || Jimp.AUTO);
|
|
116
|
+
return await img.quality(quality).getBufferAsync(format === 'png' ? Jimp.MIME_PNG : Jimp.MIME_JPEG);
|
|
117
|
+
} catch {}
|
|
118
|
+
}
|
|
119
|
+
return buffer;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Miniatura base64 pequeña para campos thumbnail */
|
|
123
|
+
async function toThumbBase64(buffer, size = 64) {
|
|
124
|
+
try {
|
|
125
|
+
const small = await maybeResize(buffer, { width: size, height: size, quality: 60 });
|
|
126
|
+
return small ? small.toString('base64') : null;
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Sube buffer a servidores WA → { url, directPath, imageMessage, thumbBase64 }
|
|
134
|
+
*/
|
|
135
|
+
async function uploadToWa(sock, buffer, mediaType = 'image') {
|
|
136
|
+
if (!sock?.waUploadToServer || !buffer?.length) return null;
|
|
137
|
+
try {
|
|
138
|
+
const prepareWAMessageMedia = getPrepareWAMessageMedia();
|
|
139
|
+
const media = await prepareWAMessageMedia(
|
|
140
|
+
{ [mediaType]: buffer },
|
|
141
|
+
{
|
|
142
|
+
upload: sock.waUploadToServer,
|
|
143
|
+
mediaTypeOverride: mediaType,
|
|
144
|
+
}
|
|
145
|
+
);
|
|
146
|
+
const msg = media?.[mediaType + 'Message'] || Object.values(media || {})[0];
|
|
147
|
+
if (!msg) return null;
|
|
148
|
+
const url = msg.url || msg.mediaUrl || null;
|
|
149
|
+
const directPath = msg.directPath || null;
|
|
150
|
+
const thumbBase64 = msg.jpegThumbnail
|
|
151
|
+
? (Buffer.isBuffer(msg.jpegThumbnail)
|
|
152
|
+
? msg.jpegThumbnail.toString('base64')
|
|
153
|
+
: Buffer.from(msg.jpegThumbnail).toString('base64'))
|
|
154
|
+
: await toThumbBase64(buffer);
|
|
155
|
+
return { url, directPath, imageMessage: msg, thumbBase64, raw: msg };
|
|
156
|
+
} catch (e) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Resuelve cualquier fuente a URL usable en AIRich + metadatos
|
|
163
|
+
* Estrategia: descargar → resize → subir a WA → devolver mediaUrl
|
|
164
|
+
* (las URL externas a menudo salen en blanco en product/reels del cliente)
|
|
165
|
+
*/
|
|
166
|
+
async function resolveRichImage(sock, source, opts = {}) {
|
|
167
|
+
const timeoutMs = opts.timeoutMs || 12000;
|
|
168
|
+
let buf = await toBuffer(source, { timeoutMs });
|
|
169
|
+
|
|
170
|
+
// Si falló y era URL, probar DEFAULT
|
|
171
|
+
if (!buf?.length && source && source !== DEFAULT_IMAGE) {
|
|
172
|
+
buf = await toBuffer(DEFAULT_IMAGE, { timeoutMs: 8000 });
|
|
173
|
+
}
|
|
174
|
+
if (!buf?.length) {
|
|
175
|
+
return { url: DEFAULT_IMAGE, thumbBase64: null, directPath: null };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
buf = await maybeResize(buf, {
|
|
179
|
+
width: opts.width || 800,
|
|
180
|
+
height: opts.height || 800,
|
|
181
|
+
quality: opts.quality || 85,
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const uploaded = await uploadToWa(sock, buf, 'image');
|
|
185
|
+
if (uploaded?.url) {
|
|
186
|
+
return {
|
|
187
|
+
url: uploaded.url,
|
|
188
|
+
directPath: uploaded.directPath,
|
|
189
|
+
thumbBase64: uploaded.thumbBase64,
|
|
190
|
+
imageMessage: uploaded.imageMessage,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Fallback: URL original si era http pública
|
|
195
|
+
if (typeof source === 'string' && isHttpUrl(source) && !/whatsapp\.(net|com)/i.test(source)) {
|
|
196
|
+
return {
|
|
197
|
+
url: source.trim(),
|
|
198
|
+
thumbBase64: await toThumbBase64(buf),
|
|
199
|
+
directPath: null,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
url: DEFAULT_IMAGE,
|
|
205
|
+
thumbBase64: await toThumbBase64(buf),
|
|
206
|
+
directPath: null,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Alias histórico */
|
|
211
|
+
async function resolvePublicImageUrl(sock, source, opts = {}) {
|
|
212
|
+
const r = await resolveRichImage(sock, source, opts);
|
|
213
|
+
return r.url || DEFAULT_IMAGE;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function resolveImageForSend(sock, source, options = {}) {
|
|
217
|
+
const buf0 = await toBuffer(source, { timeoutMs: options.timeoutMs || 15000 });
|
|
218
|
+
if (!buf0?.length) return null;
|
|
219
|
+
const resized = await maybeResize(buf0, {
|
|
220
|
+
width: options.width,
|
|
221
|
+
height: options.height,
|
|
222
|
+
quality: options.quality || 85,
|
|
223
|
+
});
|
|
224
|
+
const uploaded = options.upload === false ? null : await uploadToWa(sock, resized, 'image');
|
|
225
|
+
return {
|
|
226
|
+
buffer: resized,
|
|
227
|
+
imageMessage: uploaded?.imageMessage || null,
|
|
228
|
+
url: uploaded?.url || null,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function normalizeMediaContent(content, sock) {
|
|
233
|
+
if (!content || typeof content !== 'object') return content;
|
|
234
|
+
const out = { ...content };
|
|
235
|
+
for (const key of ['image', 'video', 'document', 'audio', 'sticker']) {
|
|
236
|
+
if (!(key in out)) continue;
|
|
237
|
+
const v = out[key];
|
|
238
|
+
if (Buffer.isBuffer(v) || (v && typeof v === 'object' && (v.url || v.stream))) continue;
|
|
239
|
+
if (typeof v === 'string') {
|
|
240
|
+
if (isHttpUrl(v)) {
|
|
241
|
+
out[key] = { url: v };
|
|
242
|
+
} else {
|
|
243
|
+
const buf = await toBuffer(v);
|
|
244
|
+
if (buf) out[key] = buf;
|
|
245
|
+
}
|
|
246
|
+
} else if (v && typeof v === 'object') {
|
|
247
|
+
const buf = await toBuffer(v);
|
|
248
|
+
if (buf) out[key] = buf;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
module.exports = {
|
|
255
|
+
DEFAULT_IMAGE,
|
|
256
|
+
toBuffer,
|
|
257
|
+
maybeResize,
|
|
258
|
+
toThumbBase64,
|
|
259
|
+
uploadToWa,
|
|
260
|
+
resolveRichImage,
|
|
261
|
+
resolvePublicImageUrl,
|
|
262
|
+
resolveImageForSend,
|
|
263
|
+
normalizeMediaContent,
|
|
264
|
+
isHttpUrl,
|
|
265
|
+
isDataUri,
|
|
266
|
+
};
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Métodos rich compatibles (todas las versiones de WhatsApp posibles)
|
|
3
|
+
* - sendCodeBlock: AIRich + fallback texto monolínea
|
|
4
|
+
* - sendLatexInlineImage
|
|
5
|
+
* - sendTable / sendAIRich / sendHtml
|
|
6
|
+
* - sendA2UI / sendBloksWidget (con fallback si el cliente no soporta)
|
|
7
|
+
*/
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const crypto = require('crypto');
|
|
11
|
+
const { KageAIRich } = require('./kage-airich');
|
|
12
|
+
const { toBuffer, DEFAULT_IMAGE } = require('./kage-media-resolve');
|
|
13
|
+
|
|
14
|
+
function genId() {
|
|
15
|
+
try {
|
|
16
|
+
const g = require('./generics.js');
|
|
17
|
+
if (typeof g.generateMessageIDV2 === 'function') return g.generateMessageIDV2();
|
|
18
|
+
} catch {}
|
|
19
|
+
return crypto.randomBytes(8).toString('hex').toUpperCase();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function messageSecretB64(bytes = 32) {
|
|
23
|
+
return crypto.randomBytes(bytes).toString('base64');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Code block COMPARTIBLE:
|
|
28
|
+
* 1) Intenta AIRich con primitiva de código
|
|
29
|
+
* 2) Si falla, interactive native flow simple
|
|
30
|
+
* 3) Fallback texto ```code``` (todas las versiones)
|
|
31
|
+
*/
|
|
32
|
+
async function sendCodeBlock(sock, jid, code, quoted, opts = {}) {
|
|
33
|
+
const title = opts.title || 'Code';
|
|
34
|
+
const language = (opts.language || 'javascript').toLowerCase();
|
|
35
|
+
const footer = opts.footer || '';
|
|
36
|
+
const body = String(code ?? '');
|
|
37
|
+
|
|
38
|
+
// --- Preferencia: AIRich (clientes nuevos) ---
|
|
39
|
+
try {
|
|
40
|
+
const rich = new KageAIRich(sock);
|
|
41
|
+
rich.setTitle(title);
|
|
42
|
+
if (footer) rich.setFooter(footer);
|
|
43
|
+
|
|
44
|
+
// Código legible en submessages (siempre)
|
|
45
|
+
const display =
|
|
46
|
+
`📦 *${title}*\n` +
|
|
47
|
+
`_${language}_\n\n` +
|
|
48
|
+
'```' + language + '\n' +
|
|
49
|
+
body +
|
|
50
|
+
'\n```' +
|
|
51
|
+
(footer ? `\n\n${footer}` : '');
|
|
52
|
+
|
|
53
|
+
rich.addText(display);
|
|
54
|
+
|
|
55
|
+
// Primitiva code (si el cliente la entiende)
|
|
56
|
+
try {
|
|
57
|
+
rich._sections.push({
|
|
58
|
+
view_model: {
|
|
59
|
+
primitive: {
|
|
60
|
+
__typename: 'GenAICodeBlockUXPrimitive',
|
|
61
|
+
code: body,
|
|
62
|
+
language,
|
|
63
|
+
title,
|
|
64
|
+
highlight: true,
|
|
65
|
+
},
|
|
66
|
+
__typename: 'GenAISingleLayoutViewModel',
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
} catch {}
|
|
70
|
+
|
|
71
|
+
const sent = await rich.send(jid, { quoted: quoted || undefined });
|
|
72
|
+
return sent;
|
|
73
|
+
} catch (e1) {
|
|
74
|
+
// --- Fallback universal: texto con markdown code fence ---
|
|
75
|
+
const text =
|
|
76
|
+
`📦 *${title}*\n` +
|
|
77
|
+
`Lenguaje: \`${language}\`\n\n` +
|
|
78
|
+
'```' + language + '\n' +
|
|
79
|
+
body +
|
|
80
|
+
'\n```' +
|
|
81
|
+
(footer ? `\n\n_${footer}_` : '');
|
|
82
|
+
|
|
83
|
+
return sock.sendMessage(
|
|
84
|
+
jid,
|
|
85
|
+
{ text },
|
|
86
|
+
{ quoted: quoted || undefined }
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function sendLatexInlineImage(sock, jid, quoted, opts = {}) {
|
|
92
|
+
const expressions = opts.expressions || opts.expression || [];
|
|
93
|
+
const list = Array.isArray(expressions) ? expressions : [expressions];
|
|
94
|
+
const lines = list
|
|
95
|
+
.map((e) => (typeof e === 'string' ? e : e?.latexExpression || e?.latex || e?.expression || String(e)))
|
|
96
|
+
.filter(Boolean);
|
|
97
|
+
if (!lines.length) throw new TypeError('sendLatexInlineImage: expressions vacío');
|
|
98
|
+
|
|
99
|
+
const images = [];
|
|
100
|
+
for (const latex of lines.slice(0, 6)) {
|
|
101
|
+
try {
|
|
102
|
+
const url =
|
|
103
|
+
'https://latex.codecogs.com/png.image?' +
|
|
104
|
+
encodeURIComponent('\\dpi{150}\\bg{white} ' + latex);
|
|
105
|
+
const buf = await toBuffer(url, { timeoutMs: 7000 });
|
|
106
|
+
if (buf && buf.length > 100) images.push({ latex, buffer: buf });
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (images.length) {
|
|
111
|
+
const caption = lines.map((l) => `$$${l}$$`).join('\n');
|
|
112
|
+
return sock.sendMessage(
|
|
113
|
+
jid,
|
|
114
|
+
{ image: images[0].buffer, caption },
|
|
115
|
+
{ quoted: quoted || undefined }
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const rich = new KageAIRich(sock);
|
|
120
|
+
rich.setTitle(opts.title || 'LaTeX');
|
|
121
|
+
rich.addText(lines.map((l) => `📐 \`${l}\``).join('\n\n'));
|
|
122
|
+
return rich.send(jid, { quoted: quoted || undefined });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function sendAIRich(sock, jid, config, quoted) {
|
|
126
|
+
const rich = new KageAIRich(sock);
|
|
127
|
+
if (typeof config === 'function') await config(rich);
|
|
128
|
+
else if (config && typeof config === 'object') {
|
|
129
|
+
if (config.title) rich.setTitle(config.title);
|
|
130
|
+
if (config.footer) rich.setFooter(config.footer);
|
|
131
|
+
if (config.text) rich.addText(config.text);
|
|
132
|
+
if (config.table) rich.addTable(config.table);
|
|
133
|
+
if (config.products) rich.addProduct(config.products);
|
|
134
|
+
if (config.suggest) rich.addSuggest(config.suggest);
|
|
135
|
+
if (config.html) rich.addHtml(config.html, { title: config.title });
|
|
136
|
+
}
|
|
137
|
+
return rich.send(jid, { quoted: quoted || undefined });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function sendHtml(sock, jid, html, opts = {}) {
|
|
141
|
+
const rich = new KageAIRich(sock);
|
|
142
|
+
rich.setTitle(opts.title || 'HTML');
|
|
143
|
+
rich.addHtml(html, { title: opts.title || 'HTML', url: opts.url || 'https://chiaki.dev' });
|
|
144
|
+
return rich.send(jid, { quoted: opts.quoted });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function sendImage(sock, jid, source, opts = {}) {
|
|
148
|
+
let image = source;
|
|
149
|
+
if (typeof source === 'string' && !/^https?:\/\//i.test(source)) {
|
|
150
|
+
const buf = await toBuffer(source);
|
|
151
|
+
if (buf) image = buf;
|
|
152
|
+
} else if (source && typeof source === 'object' && !Buffer.isBuffer(source) && !source.url) {
|
|
153
|
+
const buf = await toBuffer(source);
|
|
154
|
+
if (buf) image = buf;
|
|
155
|
+
}
|
|
156
|
+
return sock.sendMessage(
|
|
157
|
+
jid,
|
|
158
|
+
{ image, caption: opts.caption, ...opts.extra },
|
|
159
|
+
{ quoted: opts.quoted, ...opts.sendOptions }
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A2UI / BloksWidget — clientes nuevos; en viejos muestra fallback texto
|
|
165
|
+
* Mismo shape que el ejemplo GianPool / Meta AI
|
|
166
|
+
*/
|
|
167
|
+
async function sendA2UI(sock, jid, payload, opts = {}) {
|
|
168
|
+
const uuid = opts.uuid || crypto.randomUUID();
|
|
169
|
+
const data =
|
|
170
|
+
typeof payload === 'string' ? payload : JSON.stringify(payload || {});
|
|
171
|
+
|
|
172
|
+
const content = {
|
|
173
|
+
messageContextInfo: {
|
|
174
|
+
messageSecret: opts.messageSecret || messageSecretB64(32),
|
|
175
|
+
deviceListMetadata: {},
|
|
176
|
+
deviceListMetadataVersion: 2,
|
|
177
|
+
},
|
|
178
|
+
interactiveMessage: {
|
|
179
|
+
nativeFlowMessage: {
|
|
180
|
+
buttons: opts.buttons || [],
|
|
181
|
+
messageParamsJson: opts.messageParamsJson || '{}',
|
|
182
|
+
messageVersion: 1,
|
|
183
|
+
},
|
|
184
|
+
bloksWidget: {
|
|
185
|
+
uuid,
|
|
186
|
+
data,
|
|
187
|
+
type: opts.type || 'im_a2ui',
|
|
188
|
+
// Campo proto: clientes viejos muestran este texto en vez de "no compatible"
|
|
189
|
+
fallback: opts.fallback || opts.fallbackText || 'Actualiza WhatsApp para ver este contenido.',
|
|
190
|
+
},
|
|
191
|
+
contextInfo: {
|
|
192
|
+
expiration: opts.expiration || 7776000,
|
|
193
|
+
...(opts.contextInfo || {}),
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const additionalNodes = opts.additionalNodes || [
|
|
199
|
+
{
|
|
200
|
+
tag: 'biz',
|
|
201
|
+
attrs: {
|
|
202
|
+
actual_actors: '2',
|
|
203
|
+
host_storage: '2',
|
|
204
|
+
privacy_mode_ts: String(opts.privacyModeTs || Math.floor(Date.now() / 1000) + 86400 * 30),
|
|
205
|
+
},
|
|
206
|
+
content: [
|
|
207
|
+
{
|
|
208
|
+
tag: 'interactive',
|
|
209
|
+
attrs: { type: 'native_flow', v: '1' },
|
|
210
|
+
content: [
|
|
211
|
+
{
|
|
212
|
+
tag: 'native_flow',
|
|
213
|
+
attrs: { v: '9', name: 'mixed' },
|
|
214
|
+
},
|
|
215
|
+
],
|
|
216
|
+
},
|
|
217
|
+
],
|
|
218
|
+
},
|
|
219
|
+
];
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
const messageId = genId();
|
|
223
|
+
await sock.relayMessage(jid, content, { messageId, additionalNodes });
|
|
224
|
+
return { key: { remoteJid: jid, fromMe: true, id: messageId }, message: content };
|
|
225
|
+
} catch (e) {
|
|
226
|
+
// Fallback compatible
|
|
227
|
+
const text =
|
|
228
|
+
opts.fallbackText ||
|
|
229
|
+
'⚙️ *Widget A2UI*\nTu WhatsApp no soporta este componente. Actualiza la app o usa otro cliente.';
|
|
230
|
+
return sock.sendMessage(jid, { text }, { quoted: opts.quoted });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Alias explícito */
|
|
235
|
+
async function sendBloksWidget(sock, jid, data, opts = {}) {
|
|
236
|
+
return sendA2UI(sock, jid, data, opts);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* relayMessage “seguro”: si el cliente no entiende, no deja solo el error opaco
|
|
241
|
+
* (el caller sigue usando sock.relayMessage nativo; esto es helper opcional)
|
|
242
|
+
*/
|
|
243
|
+
async function relayCompatible(sock, jid, message, options = {}) {
|
|
244
|
+
try {
|
|
245
|
+
const messageId = options.messageId || genId();
|
|
246
|
+
await sock.relayMessage(jid, message, { ...options, messageId });
|
|
247
|
+
return { key: { remoteJid: jid, fromMe: true, id: messageId } };
|
|
248
|
+
} catch (e) {
|
|
249
|
+
if (options.fallbackText) {
|
|
250
|
+
return sock.sendMessage(jid, { text: options.fallbackText }, { quoted: options.quoted });
|
|
251
|
+
}
|
|
252
|
+
throw e;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function installRichMethods(sock) {
|
|
257
|
+
if (!sock) return sock;
|
|
258
|
+
|
|
259
|
+
const bind = (name, fn) => {
|
|
260
|
+
const wrapped = (...args) => fn(sock, ...args);
|
|
261
|
+
try {
|
|
262
|
+
sock[name] = wrapped;
|
|
263
|
+
} catch {
|
|
264
|
+
try {
|
|
265
|
+
Object.defineProperty(sock, name, {
|
|
266
|
+
value: wrapped,
|
|
267
|
+
writable: true,
|
|
268
|
+
configurable: true,
|
|
269
|
+
enumerable: true,
|
|
270
|
+
});
|
|
271
|
+
} catch {}
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
bind('sendCodeBlock', sendCodeBlock);
|
|
276
|
+
bind('sendCode', sendCodeBlock);
|
|
277
|
+
bind('sendLatexInlineImage', sendLatexInlineImage);
|
|
278
|
+
bind('sendLatex', sendLatexInlineImage);
|
|
279
|
+
bind('sendAIRich', sendAIRich);
|
|
280
|
+
bind('sendHtml', sendHtml);
|
|
281
|
+
bind('sendHtmlRich', sendHtml);
|
|
282
|
+
bind('sendImageFlex', sendImage);
|
|
283
|
+
bind('sendA2UI', sendA2UI);
|
|
284
|
+
bind('sendBloksWidget', sendBloksWidget);
|
|
285
|
+
bind('relayCompatible', relayCompatible);
|
|
286
|
+
|
|
287
|
+
try {
|
|
288
|
+
require('./kage-send-table').installSendTable(sock);
|
|
289
|
+
} catch {}
|
|
290
|
+
|
|
291
|
+
return sock;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
module.exports = {
|
|
295
|
+
installRichMethods,
|
|
296
|
+
sendCodeBlock,
|
|
297
|
+
sendLatexInlineImage,
|
|
298
|
+
sendAIRich,
|
|
299
|
+
sendHtml,
|
|
300
|
+
sendImage,
|
|
301
|
+
sendA2UI,
|
|
302
|
+
sendBloksWidget,
|
|
303
|
+
relayCompatible,
|
|
304
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sock.sendTable(jid, title, headers, rows, quotedMsg, options)
|
|
3
|
+
* Compatible con el uso típico de Chiaki/simple.js
|
|
4
|
+
*/
|
|
5
|
+
'use strict';
|
|
6
|
+
|
|
7
|
+
const { KageAIRich } = require('./kage-airich');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {object} sock
|
|
11
|
+
* @param {string} jid
|
|
12
|
+
* @param {string} title - título (puede ser '')
|
|
13
|
+
* @param {string[]} headers - cabeceras de columna
|
|
14
|
+
* @param {Array<Array<string|number>>} rows - filas
|
|
15
|
+
* @param {object} [quoted] - mensaje a citar (m)
|
|
16
|
+
* @param {object} [opts]
|
|
17
|
+
* @param {string} [opts.headerText]
|
|
18
|
+
* @param {string} [opts.footer]
|
|
19
|
+
* @param {string[]} [opts.mentions]
|
|
20
|
+
*/
|
|
21
|
+
async function sendTable(sock, jid, title, headers, rows, quoted, opts = {}) {
|
|
22
|
+
if (!sock || typeof sock.relayMessage !== 'function') {
|
|
23
|
+
throw new TypeError('sendTable: socket inválido');
|
|
24
|
+
}
|
|
25
|
+
if (!jid) throw new TypeError('sendTable: jid requerido');
|
|
26
|
+
|
|
27
|
+
const headerCols = Array.isArray(headers) ? headers.map((h) => String(h ?? '')) : [];
|
|
28
|
+
const bodyRows = Array.isArray(rows)
|
|
29
|
+
? rows.map((r) => (Array.isArray(r) ? r.map((c) => String(c ?? '')) : [String(r ?? '')]))
|
|
30
|
+
: [];
|
|
31
|
+
|
|
32
|
+
const table = headerCols.length ? [headerCols, ...bodyRows] : bodyRows;
|
|
33
|
+
|
|
34
|
+
const rich = new KageAIRich(sock);
|
|
35
|
+
const mainTitle = (opts.headerText || title || 'Table').trim() || 'Table';
|
|
36
|
+
rich.setTitle(mainTitle);
|
|
37
|
+
|
|
38
|
+
if (opts.headerText || title) {
|
|
39
|
+
const intro = [opts.headerText, title].filter(Boolean).join('\n');
|
|
40
|
+
if (intro) rich.addText(intro);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
rich.addTable(table);
|
|
44
|
+
|
|
45
|
+
if (opts.footer) {
|
|
46
|
+
rich.setFooter(String(opts.footer));
|
|
47
|
+
try {
|
|
48
|
+
rich.addMetadata(String(opts.footer));
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return rich.send(jid, {
|
|
53
|
+
quoted: quoted || undefined,
|
|
54
|
+
mentions: opts.mentions,
|
|
55
|
+
bypassDownload: false,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function installSendTable(sock) {
|
|
60
|
+
if (!sock) return sock;
|
|
61
|
+
const fn = function (jid, title, headers, rows, quoted, opts) {
|
|
62
|
+
return sendTable(sock, jid, title, headers, rows, quoted, opts);
|
|
63
|
+
};
|
|
64
|
+
try {
|
|
65
|
+
sock.sendTable = fn;
|
|
66
|
+
} catch {
|
|
67
|
+
try {
|
|
68
|
+
Object.defineProperty(sock, 'sendTable', {
|
|
69
|
+
value: fn,
|
|
70
|
+
writable: true,
|
|
71
|
+
configurable: true,
|
|
72
|
+
enumerable: true,
|
|
73
|
+
});
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
return sock;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
module.exports = { sendTable, installSendTable };
|
package/lib/index.js
CHANGED
|
@@ -148,3 +148,78 @@ __exportStar(require('./Utils/init-queries.js'), exports);
|
|
|
148
148
|
__exportStar(require('./Utils/profile-tools.js'), exports);
|
|
149
149
|
|
|
150
150
|
Object.assign(exports.default, exports);
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
// Kage AIRich + media (integrado)
|
|
154
|
+
try {
|
|
155
|
+
const kageAirich = require('./Utils/kage-airich');
|
|
156
|
+
const kageMedia = require('./Utils/kage-media-resolve');
|
|
157
|
+
exports.AIRich = kageAirich.AIRich;
|
|
158
|
+
exports.KageAIRich = kageAirich.KageAIRich;
|
|
159
|
+
exports.createAIRich = kageAirich.createAIRich;
|
|
160
|
+
exports.resolvePublicImageUrl = kageMedia.resolvePublicImageUrl;
|
|
161
|
+
exports.toBuffer = kageMedia.toBuffer;
|
|
162
|
+
exports.DEFAULT_IMAGE = kageMedia.DEFAULT_IMAGE;
|
|
163
|
+
if (exports.default && typeof exports.default === 'object') {
|
|
164
|
+
Object.assign(exports.default, {
|
|
165
|
+
AIRich: kageAirich.AIRich,
|
|
166
|
+
KageAIRich: kageAirich.KageAIRich,
|
|
167
|
+
createAIRich: kageAirich.createAIRich,
|
|
168
|
+
DEFAULT_IMAGE: kageMedia.DEFAULT_IMAGE,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
} catch (_) {}
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
const { sendTable } = require('./Utils/kage-send-table');
|
|
175
|
+
exports.sendTable = sendTable;
|
|
176
|
+
if (exports.default && typeof exports.default === 'object') {
|
|
177
|
+
exports.default.sendTable = sendTable;
|
|
178
|
+
}
|
|
179
|
+
} catch (_) {}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const richM = require('./Utils/kage-rich-methods');
|
|
183
|
+
Object.assign(exports, {
|
|
184
|
+
sendCodeBlock: richM.sendCodeBlock,
|
|
185
|
+
sendLatexInlineImage: richM.sendLatexInlineImage,
|
|
186
|
+
sendAIRich: richM.sendAIRich,
|
|
187
|
+
sendHtml: richM.sendHtml,
|
|
188
|
+
installRichMethods: richM.installRichMethods,
|
|
189
|
+
});
|
|
190
|
+
if (exports.default && typeof exports.default === 'object') {
|
|
191
|
+
Object.assign(exports.default, {
|
|
192
|
+
sendCodeBlock: richM.sendCodeBlock,
|
|
193
|
+
sendLatexInlineImage: richM.sendLatexInlineImage,
|
|
194
|
+
installRichMethods: richM.installRichMethods,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
} catch (_) {}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
// Kage rich API completa
|
|
201
|
+
try {
|
|
202
|
+
const kageAirich = require('./Utils/kage-airich');
|
|
203
|
+
const kageMedia = require('./Utils/kage-media-resolve');
|
|
204
|
+
const { sendTable, installSendTable } = require('./Utils/kage-send-table');
|
|
205
|
+
const richM = require('./Utils/kage-rich-methods');
|
|
206
|
+
Object.assign(exports, {
|
|
207
|
+
AIRich: kageAirich.AIRich,
|
|
208
|
+
KageAIRich: kageAirich.KageAIRich,
|
|
209
|
+
createAIRich: kageAirich.createAIRich,
|
|
210
|
+
resolvePublicImageUrl: kageMedia.resolvePublicImageUrl,
|
|
211
|
+
resolveRichImage: kageMedia.resolveRichImage,
|
|
212
|
+
toBuffer: kageMedia.toBuffer,
|
|
213
|
+
DEFAULT_IMAGE: kageMedia.DEFAULT_IMAGE,
|
|
214
|
+
sendTable,
|
|
215
|
+
installSendTable,
|
|
216
|
+
sendCodeBlock: richM.sendCodeBlock,
|
|
217
|
+
sendLatexInlineImage: richM.sendLatexInlineImage,
|
|
218
|
+
sendAIRich: richM.sendAIRich,
|
|
219
|
+
sendHtml: richM.sendHtml,
|
|
220
|
+
sendA2UI: richM.sendA2UI,
|
|
221
|
+
sendBloksWidget: richM.sendBloksWidget,
|
|
222
|
+
relayCompatible: richM.relayCompatible,
|
|
223
|
+
installRichMethods: richM.installRichMethods,
|
|
224
|
+
});
|
|
225
|
+
} catch (e) {}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kage-baileys",
|
|
3
|
-
"version": "25.0.
|
|
3
|
+
"version": "25.0.8",
|
|
4
4
|
"description": "Kage Baileys completo — API WhatsApp Web con MessageBuilder extendido, Native Flows, review_and_pay, módulos proto, miniaturas base64/Buffer, rich UI, VoIP, canales, comunidades y más.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kage-baileys",
|
|
@@ -137,7 +137,9 @@
|
|
|
137
137
|
"optionalDependencies": {
|
|
138
138
|
"@itsukichan/libsignal-node": "^1.0.1",
|
|
139
139
|
"@roamhq/wrtc": "*",
|
|
140
|
-
"whatsapp-rust-bridge": "0.5.2"
|
|
140
|
+
"whatsapp-rust-bridge": "0.5.2",
|
|
141
|
+
"jimp": "^0.22.12",
|
|
142
|
+
"sharp": "^0.33.5"
|
|
141
143
|
},
|
|
142
144
|
"exports": {
|
|
143
145
|
".": {
|