kage-baileys 25.3.19 → 25.3.20
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/Example/plugins/audiosticker.js +1134 -0
- package/WAProto/index.js +118 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1134 @@
|
|
|
1
|
+
import { sticker } from '../lib/sticker.js'
|
|
2
|
+
import {
|
|
3
|
+
prepareWAMessageMedia,
|
|
4
|
+
proto,
|
|
5
|
+
downloadMediaMessage,
|
|
6
|
+
downloadContentFromMessage
|
|
7
|
+
} from 'kage-baileys'
|
|
8
|
+
import { randomBytes } from 'node:crypto'
|
|
9
|
+
import { execFile } from 'node:child_process'
|
|
10
|
+
import { promisify } from 'node:util'
|
|
11
|
+
import fs from 'node:fs/promises'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import os from 'node:os'
|
|
14
|
+
|
|
15
|
+
const execFileAsync = promisify(execFile)
|
|
16
|
+
const MAX_DURATION = 25
|
|
17
|
+
const SESSION_SECONDS = 60
|
|
18
|
+
const MAX_STICKER_SIZE = 880 * 1024
|
|
19
|
+
|
|
20
|
+
if (!globalThis.__audioStickerSessions) {
|
|
21
|
+
globalThis.__audioStickerSessions = new Map()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const sessions = globalThis.__audioStickerSessions
|
|
25
|
+
|
|
26
|
+
function patchProtoInstance(p) {
|
|
27
|
+
const M = p?.Message
|
|
28
|
+
|
|
29
|
+
if (!M || M.__audioStickerKagePatchedV2 || M.__audioStickerKagePatchedV3) return
|
|
30
|
+
|
|
31
|
+
if (!M.StickerMessage || !M.AudioMessage || !M.FutureProofMessage) {
|
|
32
|
+
throw new Error('La versión instalada de Kage Baileys no contiene las clases protobuf necesarias para Audio Sticker.')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const previousStickerEncode = M.StickerMessage.encode
|
|
36
|
+
|
|
37
|
+
M.StickerMessage.encode = function (message, writer) {
|
|
38
|
+
const hasAudio = message && Object.prototype.hasOwnProperty.call(message, 'audioMessage')
|
|
39
|
+
const audio = hasAudio ? message.audioMessage : null
|
|
40
|
+
|
|
41
|
+
if (hasAudio) delete message.audioMessage
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const result = previousStickerEncode.call(this, message, writer)
|
|
45
|
+
|
|
46
|
+
if (audio) {
|
|
47
|
+
M.AudioMessage.encode(audio, result.uint32(210).fork()).ldelim()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return result
|
|
51
|
+
} finally {
|
|
52
|
+
if (hasAudio) message.audioMessage = audio
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (typeof M.StickerMessage.fromObject === 'function') {
|
|
57
|
+
const previousStickerFromObject = M.StickerMessage.fromObject
|
|
58
|
+
|
|
59
|
+
M.StickerMessage.fromObject = function (object) {
|
|
60
|
+
const message = previousStickerFromObject.call(this, object)
|
|
61
|
+
|
|
62
|
+
if (object?.audioMessage) {
|
|
63
|
+
message.audioMessage = M.AudioMessage.fromObject
|
|
64
|
+
? M.AudioMessage.fromObject(object.audioMessage)
|
|
65
|
+
: object.audioMessage
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return message
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const previousMessageEncode = M.encode
|
|
73
|
+
|
|
74
|
+
M.encode = function (message, writer) {
|
|
75
|
+
const hasAudioSticker = message && Object.prototype.hasOwnProperty.call(message, 'audioStickerMessage')
|
|
76
|
+
const hasSticker = message && Object.prototype.hasOwnProperty.call(message, 'stickerMessage')
|
|
77
|
+
const audioSticker = hasAudioSticker ? message.audioStickerMessage : null
|
|
78
|
+
const stickerMessage = hasSticker ? message.stickerMessage : null
|
|
79
|
+
|
|
80
|
+
if (hasAudioSticker) {
|
|
81
|
+
delete message.audioStickerMessage
|
|
82
|
+
if (hasSticker) delete message.stickerMessage
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
const result = previousMessageEncode.call(this, message, writer)
|
|
87
|
+
|
|
88
|
+
if (audioSticker) {
|
|
89
|
+
M.FutureProofMessage.encode(
|
|
90
|
+
audioSticker,
|
|
91
|
+
result.uint32(1074).fork()
|
|
92
|
+
).ldelim()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return result
|
|
96
|
+
} finally {
|
|
97
|
+
if (hasAudioSticker && hasSticker) message.stickerMessage = stickerMessage
|
|
98
|
+
if (hasAudioSticker) message.audioStickerMessage = audioSticker
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (typeof M.fromObject === 'function') {
|
|
103
|
+
const previousMessageFromObject = M.fromObject
|
|
104
|
+
|
|
105
|
+
M.fromObject = function (object) {
|
|
106
|
+
const message = previousMessageFromObject.call(this, object)
|
|
107
|
+
|
|
108
|
+
if (object?.audioStickerMessage) {
|
|
109
|
+
const inner = object.audioStickerMessage.message || object.audioStickerMessage
|
|
110
|
+
message.audioStickerMessage = M.FutureProofMessage.fromObject
|
|
111
|
+
? M.FutureProofMessage.fromObject({ message: inner })
|
|
112
|
+
: { message: inner }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return message
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
M.__audioStickerKagePatchedV2 = true
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function ensurePatched() {
|
|
123
|
+
patchProtoInstance(proto)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function getSessionKey(m) {
|
|
127
|
+
return `${m.chat}:${m.sender}`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function clearUserSession(key) {
|
|
131
|
+
const session = sessions.get(key)
|
|
132
|
+
if (session?.timer) clearTimeout(session.timer)
|
|
133
|
+
sessions.delete(key)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function unwrapMessageContainer(raw) {
|
|
137
|
+
let current = raw
|
|
138
|
+
|
|
139
|
+
for (let i = 0; i < 6 && current; i++) {
|
|
140
|
+
const next =
|
|
141
|
+
current.ephemeralMessage?.message ||
|
|
142
|
+
current.viewOnceMessageV2?.message ||
|
|
143
|
+
current.viewOnceMessageV2Extension?.message ||
|
|
144
|
+
current.viewOnceMessage?.message ||
|
|
145
|
+
current.documentWithCaptionMessage?.message ||
|
|
146
|
+
current.editedMessage?.message
|
|
147
|
+
|
|
148
|
+
if (!next) break
|
|
149
|
+
current = next
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return current || {}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function detectMediaInfo(node) {
|
|
156
|
+
if (!node) {
|
|
157
|
+
return { kind: null, mime: '', seconds: 0, mediaObj: null, dlType: null }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const container = unwrapMessageContainer(node.message || node.fakeObj?.message || {})
|
|
161
|
+
const mtype =
|
|
162
|
+
node.mtype ||
|
|
163
|
+
node.type ||
|
|
164
|
+
Object.keys(container).find(key =>
|
|
165
|
+
/imageMessage|videoMessage|stickerMessage|audioMessage|documentMessage/i.test(key)
|
|
166
|
+
) ||
|
|
167
|
+
''
|
|
168
|
+
|
|
169
|
+
const directMessage =
|
|
170
|
+
node.msg &&
|
|
171
|
+
typeof node.msg === 'object' &&
|
|
172
|
+
(node.msg.mediaKey || node.msg.url || node.msg.directPath || node.msg.mimetype)
|
|
173
|
+
? node.msg
|
|
174
|
+
: null
|
|
175
|
+
|
|
176
|
+
const mediaObj =
|
|
177
|
+
directMessage ||
|
|
178
|
+
container[mtype] ||
|
|
179
|
+
container.videoMessage ||
|
|
180
|
+
container.imageMessage ||
|
|
181
|
+
container.stickerMessage ||
|
|
182
|
+
container.audioMessage ||
|
|
183
|
+
container.documentMessage ||
|
|
184
|
+
(node.mediaKey || node.url || node.directPath ? node : null)
|
|
185
|
+
|
|
186
|
+
const mime = String(node.mimetype || mediaObj?.mimetype || '').toLowerCase()
|
|
187
|
+
const seconds = Number(mediaObj?.seconds || node.seconds || node.msg?.seconds || 0)
|
|
188
|
+
|
|
189
|
+
if (/video/i.test(mime) || /videoMessage/i.test(mtype)) {
|
|
190
|
+
return {
|
|
191
|
+
kind: 'video',
|
|
192
|
+
mime: mime || 'video/mp4',
|
|
193
|
+
seconds,
|
|
194
|
+
mediaObj,
|
|
195
|
+
dlType: /documentMessage/i.test(mtype) ? 'document' : 'video'
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (/webp/i.test(mime) || /stickerMessage/i.test(mtype)) {
|
|
200
|
+
return {
|
|
201
|
+
kind: 'webp',
|
|
202
|
+
mime: 'image/webp',
|
|
203
|
+
seconds,
|
|
204
|
+
isAnimated: Boolean(mediaObj?.isAnimated),
|
|
205
|
+
mediaObj,
|
|
206
|
+
dlType: 'sticker'
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (/image/i.test(mime) || /imageMessage/i.test(mtype)) {
|
|
211
|
+
return {
|
|
212
|
+
kind: 'image',
|
|
213
|
+
mime: mime || 'image/jpeg',
|
|
214
|
+
seconds: 0,
|
|
215
|
+
mediaObj,
|
|
216
|
+
dlType: /documentMessage/i.test(mtype) ? 'document' : 'image'
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (/audio|ogg|opus|mpeg|mp3|wav|m4a|aac/i.test(mime) || /audioMessage/i.test(mtype)) {
|
|
221
|
+
return {
|
|
222
|
+
kind: 'audio',
|
|
223
|
+
mime: mime || 'audio/mpeg',
|
|
224
|
+
seconds,
|
|
225
|
+
mediaObj,
|
|
226
|
+
dlType: /documentMessage/i.test(mtype) ? 'document' : 'audio'
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return { kind: null, mime: '', seconds: 0, mediaObj: null, dlType: null }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function downloadBuffer(node, info, client) {
|
|
234
|
+
if (!node) return null
|
|
235
|
+
|
|
236
|
+
if (
|
|
237
|
+
info?.mediaObj &&
|
|
238
|
+
info?.dlType &&
|
|
239
|
+
(info.mediaObj.mediaKey || info.mediaObj.directPath || info.mediaObj.url)
|
|
240
|
+
) {
|
|
241
|
+
try {
|
|
242
|
+
const stream = await downloadContentFromMessage(info.mediaObj, info.dlType)
|
|
243
|
+
const chunks = []
|
|
244
|
+
|
|
245
|
+
for await (const chunk of stream) chunks.push(chunk)
|
|
246
|
+
|
|
247
|
+
const buffer = Buffer.concat(chunks)
|
|
248
|
+
if (buffer.length) return buffer
|
|
249
|
+
} catch {}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (node.fakeObj?.message || node.message) {
|
|
253
|
+
try {
|
|
254
|
+
const messageObject = node.fakeObj?.message ? node.fakeObj : node
|
|
255
|
+
const buffer = await downloadMediaMessage(
|
|
256
|
+
messageObject,
|
|
257
|
+
'buffer',
|
|
258
|
+
{},
|
|
259
|
+
{
|
|
260
|
+
logger: { info: () => {}, error: () => {}, warn: () => {} },
|
|
261
|
+
reuploadRequest: client?.updateMediaMessage
|
|
262
|
+
}
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
if (buffer?.length) return buffer
|
|
266
|
+
} catch {}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (info?.mediaObj && info?.dlType) {
|
|
270
|
+
try {
|
|
271
|
+
const synthetic = {
|
|
272
|
+
key: node.key || { remoteJid: node.chat || 'status@broadcast', id: '0' },
|
|
273
|
+
message: { [`${info.dlType}Message`]: info.mediaObj }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const buffer = await downloadMediaMessage(
|
|
277
|
+
synthetic,
|
|
278
|
+
'buffer',
|
|
279
|
+
{},
|
|
280
|
+
{
|
|
281
|
+
logger: { info: () => {}, error: () => {}, warn: () => {} },
|
|
282
|
+
reuploadRequest: client?.updateMediaMessage
|
|
283
|
+
}
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
if (buffer?.length) return buffer
|
|
287
|
+
} catch {}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (typeof node.download === 'function') {
|
|
291
|
+
try {
|
|
292
|
+
const buffer = await node.download()
|
|
293
|
+
if (buffer?.length) return buffer
|
|
294
|
+
} catch {}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return null
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function buildExifPayload(packname, author) {
|
|
301
|
+
const json = {
|
|
302
|
+
'sticker-pack-id': 'com.mahiru.audiosticker',
|
|
303
|
+
'sticker-pack-name': String(packname ?? ''),
|
|
304
|
+
'sticker-pack-publisher': String(author ?? ''),
|
|
305
|
+
emojis: ['🔊']
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const exifAttr = Buffer.from([
|
|
309
|
+
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00,
|
|
310
|
+
0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00,
|
|
311
|
+
0x00, 0x00, 0x16, 0x00, 0x00, 0x00
|
|
312
|
+
])
|
|
313
|
+
|
|
314
|
+
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf-8')
|
|
315
|
+
const exif = Buffer.concat([exifAttr, jsonBuffer])
|
|
316
|
+
exif.writeUIntLE(jsonBuffer.length, 14, 4)
|
|
317
|
+
|
|
318
|
+
return exif
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function injectExifRiffFallback(webpBuffer, exifData) {
|
|
322
|
+
if (
|
|
323
|
+
!Buffer.isBuffer(webpBuffer) ||
|
|
324
|
+
webpBuffer.length < 16 ||
|
|
325
|
+
webpBuffer.toString('ascii', 0, 4) !== 'RIFF' ||
|
|
326
|
+
webpBuffer.toString('ascii', 8, 12) !== 'WEBP'
|
|
327
|
+
) {
|
|
328
|
+
return webpBuffer
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const chunks = []
|
|
332
|
+
let offset = 12
|
|
333
|
+
let hasVp8x = false
|
|
334
|
+
let isAnimated = false
|
|
335
|
+
|
|
336
|
+
while (offset + 8 <= webpBuffer.length) {
|
|
337
|
+
const id = webpBuffer.toString('ascii', offset, offset + 4)
|
|
338
|
+
const size = webpBuffer.readUInt32LE(offset + 4)
|
|
339
|
+
const padded = size + (size % 2)
|
|
340
|
+
const end = Math.min(webpBuffer.length, offset + 8 + padded)
|
|
341
|
+
const rawChunk = Buffer.from(webpBuffer.subarray(offset, end))
|
|
342
|
+
|
|
343
|
+
if (id === 'VP8X') hasVp8x = true
|
|
344
|
+
if (id === 'ANIM' || id === 'ANMF') isAnimated = true
|
|
345
|
+
if (id !== 'EXIF') chunks.push({ id, rawChunk })
|
|
346
|
+
|
|
347
|
+
offset = end
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (!hasVp8x) {
|
|
351
|
+
const vp8x = Buffer.alloc(18)
|
|
352
|
+
vp8x.write('VP8X', 0, 4, 'ascii')
|
|
353
|
+
vp8x.writeUInt32LE(10, 4)
|
|
354
|
+
vp8x[8] = 0x18
|
|
355
|
+
vp8x.writeUIntLE(511, 12, 3)
|
|
356
|
+
vp8x.writeUIntLE(511, 15, 3)
|
|
357
|
+
chunks.unshift({ id: 'VP8X', rawChunk: vp8x })
|
|
358
|
+
} else {
|
|
359
|
+
const entry = chunks.find(chunk => chunk.id === 'VP8X')
|
|
360
|
+
|
|
361
|
+
if (entry && entry.rawChunk.length >= 18) {
|
|
362
|
+
entry.rawChunk[8] |= 0x08
|
|
363
|
+
if (isAnimated) entry.rawChunk[8] |= 0x02
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const padding = exifData.length % 2 ? Buffer.from([0]) : Buffer.alloc(0)
|
|
368
|
+
const exifHeader = Buffer.alloc(8)
|
|
369
|
+
exifHeader.write('EXIF', 0, 4, 'ascii')
|
|
370
|
+
exifHeader.writeUInt32LE(exifData.length, 4)
|
|
371
|
+
|
|
372
|
+
chunks.push({
|
|
373
|
+
id: 'EXIF',
|
|
374
|
+
rawChunk: Buffer.concat([exifHeader, exifData, padding])
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
const body = Buffer.concat(chunks.map(chunk => chunk.rawChunk))
|
|
378
|
+
const header = Buffer.alloc(12)
|
|
379
|
+
header.write('RIFF', 0, 4, 'ascii')
|
|
380
|
+
header.writeUInt32LE(body.length + 4, 4)
|
|
381
|
+
header.write('WEBP', 8, 4, 'ascii')
|
|
382
|
+
|
|
383
|
+
return Buffer.concat([header, body])
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function addStickerExif(webpBuffer, packname, author) {
|
|
387
|
+
const exifData = buildExifPayload(packname, author)
|
|
388
|
+
|
|
389
|
+
try {
|
|
390
|
+
const module = await import('node-webpmux')
|
|
391
|
+
const WebpImage = module.default?.Image || module.Image || module.default
|
|
392
|
+
|
|
393
|
+
if (WebpImage) {
|
|
394
|
+
const image = new WebpImage()
|
|
395
|
+
await image.load(webpBuffer)
|
|
396
|
+
image.exif = exifData
|
|
397
|
+
return await image.save(null)
|
|
398
|
+
}
|
|
399
|
+
} catch {}
|
|
400
|
+
|
|
401
|
+
return injectExifRiffFallback(webpBuffer, exifData)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function isWebpAnimated(buffer) {
|
|
405
|
+
if (!Buffer.isBuffer(buffer) || buffer.length < 22) return false
|
|
406
|
+
if (buffer.toString('ascii', 12, 16) === 'VP8X' && (buffer[20] & 0x02) !== 0) return true
|
|
407
|
+
return buffer.includes(Buffer.from('ANIM'))
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function getBufferDuration(buffer, ext = 'mp4') {
|
|
411
|
+
const id = randomBytes(6).toString('hex')
|
|
412
|
+
const inputPath = path.join(os.tmpdir(), `as_duration_${id}.${ext}`)
|
|
413
|
+
|
|
414
|
+
try {
|
|
415
|
+
await fs.writeFile(inputPath, buffer)
|
|
416
|
+
const { stdout } = await execFileAsync('ffprobe', [
|
|
417
|
+
'-v', 'error',
|
|
418
|
+
'-show_entries', 'format=duration',
|
|
419
|
+
'-of', 'default=noprint_wrappers=1:nokey=1',
|
|
420
|
+
inputPath
|
|
421
|
+
])
|
|
422
|
+
|
|
423
|
+
const duration = Number(String(stdout).trim())
|
|
424
|
+
return Number.isFinite(duration) ? duration : 0
|
|
425
|
+
} catch {
|
|
426
|
+
return 0
|
|
427
|
+
} finally {
|
|
428
|
+
await fs.unlink(inputPath).catch(() => {})
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function videoBufferToAnimatedWebp(buffer) {
|
|
433
|
+
const id = randomBytes(6).toString('hex')
|
|
434
|
+
const inputPath = path.join(os.tmpdir(), `as_video_${id}.mp4`)
|
|
435
|
+
const outputPath = path.join(os.tmpdir(), `as_output_${id}.webp`)
|
|
436
|
+
|
|
437
|
+
const encode = async (fps, quality, size = 512) => {
|
|
438
|
+
await execFileAsync('ffmpeg', [
|
|
439
|
+
'-y',
|
|
440
|
+
'-i', inputPath,
|
|
441
|
+
'-t', String(MAX_DURATION),
|
|
442
|
+
'-vf',
|
|
443
|
+
`fps=${fps},scale=${size}:${size}:force_original_aspect_ratio=decrease,format=rgba,pad=${size}:${size}:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1`,
|
|
444
|
+
'-c:v', 'libwebp',
|
|
445
|
+
'-lossless', '0',
|
|
446
|
+
'-compression_level', '6',
|
|
447
|
+
'-q:v', String(quality),
|
|
448
|
+
'-loop', '0',
|
|
449
|
+
'-preset', 'picture',
|
|
450
|
+
'-an',
|
|
451
|
+
'-vsync', '0',
|
|
452
|
+
outputPath
|
|
453
|
+
])
|
|
454
|
+
|
|
455
|
+
return await fs.readFile(outputPath)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
try {
|
|
459
|
+
await fs.writeFile(inputPath, buffer)
|
|
460
|
+
|
|
461
|
+
const profiles = [
|
|
462
|
+
[10, 50, 512],
|
|
463
|
+
[8, 36, 512],
|
|
464
|
+
[6, 24, 512],
|
|
465
|
+
[5, 16, 512],
|
|
466
|
+
[5, 14, 448],
|
|
467
|
+
[4, 12, 384]
|
|
468
|
+
]
|
|
469
|
+
|
|
470
|
+
let result = null
|
|
471
|
+
|
|
472
|
+
for (const [fps, quality, size] of profiles) {
|
|
473
|
+
result = await encode(fps, quality, size)
|
|
474
|
+
if (result.length <= MAX_STICKER_SIZE) break
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (!result?.length || result.length > MAX_STICKER_SIZE) {
|
|
478
|
+
throw new Error('El video no se pudo reducir al tamaño permitido para un sticker animado.')
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
return result
|
|
482
|
+
} finally {
|
|
483
|
+
await fs.unlink(inputPath).catch(() => {})
|
|
484
|
+
await fs.unlink(outputPath).catch(() => {})
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async function imageBufferToWebp(buffer) {
|
|
489
|
+
try {
|
|
490
|
+
const sharp = (await import('sharp')).default
|
|
491
|
+
return await sharp(buffer, { animated: true })
|
|
492
|
+
.rotate()
|
|
493
|
+
.resize(512, 512, {
|
|
494
|
+
fit: 'contain',
|
|
495
|
+
background: { r: 0, g: 0, b: 0, alpha: 0 }
|
|
496
|
+
})
|
|
497
|
+
.webp({ quality: 82 })
|
|
498
|
+
.toBuffer()
|
|
499
|
+
} catch {
|
|
500
|
+
const id = randomBytes(6).toString('hex')
|
|
501
|
+
const inputPath = path.join(os.tmpdir(), `as_image_${id}.jpg`)
|
|
502
|
+
const outputPath = path.join(os.tmpdir(), `as_image_${id}.webp`)
|
|
503
|
+
|
|
504
|
+
try {
|
|
505
|
+
await fs.writeFile(inputPath, buffer)
|
|
506
|
+
await execFileAsync('ffmpeg', [
|
|
507
|
+
'-y',
|
|
508
|
+
'-i', inputPath,
|
|
509
|
+
'-vf', 'scale=512:512:force_original_aspect_ratio=decrease,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1',
|
|
510
|
+
'-c:v', 'libwebp',
|
|
511
|
+
'-lossless', '0',
|
|
512
|
+
'-q:v', '80',
|
|
513
|
+
'-an',
|
|
514
|
+
outputPath
|
|
515
|
+
])
|
|
516
|
+
|
|
517
|
+
return await fs.readFile(outputPath)
|
|
518
|
+
} finally {
|
|
519
|
+
await fs.unlink(inputPath).catch(() => {})
|
|
520
|
+
await fs.unlink(outputPath).catch(() => {})
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function buildStickerWithExif(buffer, kind, packname, author) {
|
|
526
|
+
let webpBuffer
|
|
527
|
+
|
|
528
|
+
if (kind === 'video') {
|
|
529
|
+
webpBuffer = await videoBufferToAnimatedWebp(buffer)
|
|
530
|
+
} else if (kind === 'image') {
|
|
531
|
+
try {
|
|
532
|
+
webpBuffer = await sticker(buffer, false, packname, author)
|
|
533
|
+
if (!Buffer.isBuffer(webpBuffer)) webpBuffer = Buffer.from(webpBuffer)
|
|
534
|
+
} catch {
|
|
535
|
+
webpBuffer = await imageBufferToWebp(buffer)
|
|
536
|
+
}
|
|
537
|
+
} else if (kind === 'webp') {
|
|
538
|
+
webpBuffer = buffer
|
|
539
|
+
} else {
|
|
540
|
+
throw new Error('Formato de imagen no compatible.')
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (!webpBuffer?.length) throw new Error('No se pudo generar el sticker WebP.')
|
|
544
|
+
|
|
545
|
+
return await addStickerExif(webpBuffer, packname, author)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function parseFfmpegDuration(stderrText) {
|
|
549
|
+
const matches = [...String(stderrText || '').matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)]
|
|
550
|
+
if (!matches.length) return 0
|
|
551
|
+
|
|
552
|
+
const last = matches[matches.length - 1]
|
|
553
|
+
const seconds = Number(last[1]) * 3600 + Number(last[2]) * 60 + Number(last[3])
|
|
554
|
+
|
|
555
|
+
return Number.isFinite(seconds) ? seconds : 0
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function generateWaveform(seedBuffer, length = 64) {
|
|
559
|
+
const waveform = Buffer.alloc(length)
|
|
560
|
+
|
|
561
|
+
for (let i = 0; i < length; i++) {
|
|
562
|
+
const value = seedBuffer?.length ? seedBuffer[(i * 19 + 7) % seedBuffer.length] : i * 11
|
|
563
|
+
waveform[i] = 18 + (value % 76)
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
return waveform
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
async function convertToOggOpus(buffer, ext = 'mp3') {
|
|
570
|
+
const id = randomBytes(6).toString('hex')
|
|
571
|
+
const inputPath = path.join(os.tmpdir(), `as_audio_${id}.${ext}`)
|
|
572
|
+
const outputPath = path.join(os.tmpdir(), `as_audio_${id}.ogg`)
|
|
573
|
+
|
|
574
|
+
try {
|
|
575
|
+
await fs.writeFile(inputPath, buffer)
|
|
576
|
+
|
|
577
|
+
const { stderr } = await execFileAsync('ffmpeg', [
|
|
578
|
+
'-y',
|
|
579
|
+
'-i', inputPath,
|
|
580
|
+
'-vn',
|
|
581
|
+
'-map', '0:a:0',
|
|
582
|
+
'-t', String(MAX_DURATION),
|
|
583
|
+
'-af', 'aresample=48000:async=1:first_pts=0',
|
|
584
|
+
'-c:a', 'libopus',
|
|
585
|
+
'-b:a', '48k',
|
|
586
|
+
'-vbr', 'on',
|
|
587
|
+
'-compression_level', '10',
|
|
588
|
+
'-ac', '1',
|
|
589
|
+
'-ar', '48000',
|
|
590
|
+
'-application', 'audio',
|
|
591
|
+
'-avoid_negative_ts', 'make_zero',
|
|
592
|
+
'-f', 'ogg',
|
|
593
|
+
outputPath
|
|
594
|
+
])
|
|
595
|
+
|
|
596
|
+
const oggBuffer = await fs.readFile(outputPath)
|
|
597
|
+
if (!oggBuffer || oggBuffer.length < 200) {
|
|
598
|
+
throw new Error('No se encontró audio válido en el archivo.')
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
return { oggBuffer, realSeconds: parseFfmpegDuration(stderr) }
|
|
602
|
+
} finally {
|
|
603
|
+
await fs.unlink(inputPath).catch(() => {})
|
|
604
|
+
await fs.unlink(outputPath).catch(() => {})
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function buildAudioMessageFromBuffer(client, buffer, ext, fallbackSeconds = 0) {
|
|
609
|
+
const { oggBuffer, realSeconds } = await convertToOggOpus(buffer, ext)
|
|
610
|
+
const prepared = await prepareWAMessageMedia(
|
|
611
|
+
{
|
|
612
|
+
audio: oggBuffer,
|
|
613
|
+
mimetype: 'audio/ogg; codecs=opus',
|
|
614
|
+
ptt: true
|
|
615
|
+
},
|
|
616
|
+
{
|
|
617
|
+
upload: client.waUploadToServer,
|
|
618
|
+
logger: client.logger
|
|
619
|
+
}
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
if (!prepared?.audioMessage) throw new Error('No se pudo preparar el audio para WhatsApp.')
|
|
623
|
+
|
|
624
|
+
const chosenSeconds = realSeconds > 0
|
|
625
|
+
? realSeconds
|
|
626
|
+
: fallbackSeconds > 0
|
|
627
|
+
? fallbackSeconds
|
|
628
|
+
: 5
|
|
629
|
+
|
|
630
|
+
const audioMessage = prepared.audioMessage
|
|
631
|
+
audioMessage.seconds = Math.max(1, Math.min(MAX_DURATION, Math.round(chosenSeconds)))
|
|
632
|
+
audioMessage.ptt = true
|
|
633
|
+
audioMessage.mimetype = 'audio/ogg; codecs=opus'
|
|
634
|
+
|
|
635
|
+
if (!audioMessage.waveform?.length) {
|
|
636
|
+
audioMessage.waveform = generateWaveform(oggBuffer)
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
return audioMessage
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async function sendCombinedAudioSticker(client, chat, stickerBuffer, isAnimated, audioMessage) {
|
|
643
|
+
ensurePatched()
|
|
644
|
+
|
|
645
|
+
if (typeof client?.waUploadToServer !== 'function') {
|
|
646
|
+
throw new Error('La conexión Kage Baileys no tiene waUploadToServer disponible.')
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
if (typeof client?.relayMessage !== 'function') {
|
|
650
|
+
throw new Error('La conexión Kage Baileys no tiene relayMessage disponible.')
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const prepared = await prepareWAMessageMedia(
|
|
654
|
+
{
|
|
655
|
+
sticker: stickerBuffer,
|
|
656
|
+
isAnimated: Boolean(isAnimated)
|
|
657
|
+
},
|
|
658
|
+
{
|
|
659
|
+
upload: client.waUploadToServer,
|
|
660
|
+
logger: client.logger
|
|
661
|
+
}
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
if (!prepared?.stickerMessage) {
|
|
665
|
+
throw new Error('Kage Baileys no pudo preparar el sticker.')
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const stickerMessage = {
|
|
669
|
+
...prepared.stickerMessage,
|
|
670
|
+
isAnimated: Boolean(isAnimated),
|
|
671
|
+
audioMessage
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
const innerMessage = {
|
|
675
|
+
stickerMessage
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const payload = {
|
|
679
|
+
stickerMessage,
|
|
680
|
+
audioStickerMessage: {
|
|
681
|
+
message: innerMessage
|
|
682
|
+
},
|
|
683
|
+
messageContextInfo: {
|
|
684
|
+
messageSecret: randomBytes(32)
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const encoded = proto.Message.encode(payload).finish()
|
|
689
|
+
const audioStickerTag = Buffer.from([0xb2, 0x08])
|
|
690
|
+
|
|
691
|
+
if (!Buffer.from(encoded).includes(audioStickerTag)) {
|
|
692
|
+
throw new Error('Kage Baileys no pudo serializar el campo audioStickerMessage (134).')
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
if (!Buffer.from(encoded).includes(Buffer.from([0xd2, 0x01]))) {
|
|
696
|
+
throw new Error('Kage Baileys no pudo serializar el audio dentro de StickerMessage (26).')
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
await client.relayMessage(chat, payload, {})
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function getReplyFunction(m, conn) {
|
|
703
|
+
return async text => {
|
|
704
|
+
if (typeof m.reply === 'function') return m.reply(text)
|
|
705
|
+
if (typeof conn.reply === 'function') return conn.reply(m.chat, text, m)
|
|
706
|
+
return conn.sendMessage(m.chat, { text }, { quoted: m })
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async function reactMessage(m, conn, emoji) {
|
|
711
|
+
try {
|
|
712
|
+
if (typeof m.react === 'function') return await m.react(emoji)
|
|
713
|
+
if (conn?.sendMessage) {
|
|
714
|
+
return await conn.sendMessage(m.chat, {
|
|
715
|
+
react: { text: emoji, key: m.key }
|
|
716
|
+
})
|
|
717
|
+
}
|
|
718
|
+
} catch {}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function makeStatus(rows) {
|
|
722
|
+
let txt = `み❑ *A U D I O - S T I C K E R* ✿\n\n`
|
|
723
|
+
|
|
724
|
+
for (const [label, value] of rows) {
|
|
725
|
+
txt += `> *₊·や✿ね ${label}* » ${value}\n`
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
return txt.trimEnd()
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function startStickerSession({ m, client, send, stickerBuffer, isAnimated, packname, author, usedPrefix, command }) {
|
|
732
|
+
const key = getSessionKey(m)
|
|
733
|
+
clearUserSession(key)
|
|
734
|
+
|
|
735
|
+
const timer = setTimeout(() => {
|
|
736
|
+
if (!sessions.has(key)) return
|
|
737
|
+
sessions.delete(key)
|
|
738
|
+
|
|
739
|
+
client.sendMessage(m.chat, {
|
|
740
|
+
text: makeStatus([
|
|
741
|
+
['Resultado', '⏰ Sesión finalizada'],
|
|
742
|
+
['Tiempo', `${SESSION_SECONDS} segundos agotados`]
|
|
743
|
+
])
|
|
744
|
+
}, { quoted: m }).catch(() => {})
|
|
745
|
+
}, SESSION_SECONDS * 1000)
|
|
746
|
+
|
|
747
|
+
sessions.set(key, {
|
|
748
|
+
stickerBuffer,
|
|
749
|
+
isAnimated,
|
|
750
|
+
packname,
|
|
751
|
+
author,
|
|
752
|
+
expiresAt: Date.now() + SESSION_SECONDS * 1000,
|
|
753
|
+
processing: false,
|
|
754
|
+
timer
|
|
755
|
+
})
|
|
756
|
+
|
|
757
|
+
return send(makeStatus([
|
|
758
|
+
['Resultado', '✅ Sesión activada'],
|
|
759
|
+
['Paquete', packname],
|
|
760
|
+
['Autor', author],
|
|
761
|
+
['Tipo', isAnimated ? 'GIF animado' : 'Imagen estática'],
|
|
762
|
+
['Audio máximo', `${MAX_DURATION} segundos`],
|
|
763
|
+
['Tiempo disponible', `${SESSION_SECONDS} segundos`],
|
|
764
|
+
['Siguiente paso', 'Envía un audio, nota de voz o video'],
|
|
765
|
+
['Cancelar', `${usedPrefix}${command} cancelar`]
|
|
766
|
+
]))
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
async function consumeSessionWithMedia(m, client, send, session, mediaNode, mediaInfo) {
|
|
770
|
+
const key = getSessionKey(m)
|
|
771
|
+
session.processing = true
|
|
772
|
+
|
|
773
|
+
await reactMessage(m, client, '🕓')
|
|
774
|
+
|
|
775
|
+
try {
|
|
776
|
+
const mediaBuffer = await downloadBuffer(mediaNode, mediaInfo, client)
|
|
777
|
+
if (!mediaBuffer?.length) throw new Error('No se pudo descargar el audio o video.')
|
|
778
|
+
|
|
779
|
+
const ext = mediaInfo.kind === 'video'
|
|
780
|
+
? 'mp4'
|
|
781
|
+
: /ogg|opus/i.test(mediaInfo.mime)
|
|
782
|
+
? 'ogg'
|
|
783
|
+
: /mp4|m4a|aac/i.test(mediaInfo.mime)
|
|
784
|
+
? 'm4a'
|
|
785
|
+
: /wav/i.test(mediaInfo.mime)
|
|
786
|
+
? 'wav'
|
|
787
|
+
: 'mp3'
|
|
788
|
+
|
|
789
|
+
const realDuration = await getBufferDuration(mediaBuffer, ext)
|
|
790
|
+
const duration = realDuration || mediaInfo.seconds || 0
|
|
791
|
+
|
|
792
|
+
if (duration > MAX_DURATION) {
|
|
793
|
+
throw new Error(`El audio o video supera el máximo de ${MAX_DURATION} segundos.`)
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const audioMessage = await buildAudioMessageFromBuffer(
|
|
797
|
+
client,
|
|
798
|
+
mediaBuffer,
|
|
799
|
+
ext,
|
|
800
|
+
duration
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
await sendCombinedAudioSticker(
|
|
804
|
+
client,
|
|
805
|
+
m.chat,
|
|
806
|
+
session.stickerBuffer,
|
|
807
|
+
session.isAnimated,
|
|
808
|
+
audioMessage
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
clearUserSession(key)
|
|
812
|
+
await reactMessage(m, client, '✅')
|
|
813
|
+
|
|
814
|
+
await send(makeStatus([
|
|
815
|
+
['Estado', '✅ Audio Sticker enviado'],
|
|
816
|
+
['Audio', 'Incorporado al sticker'],
|
|
817
|
+
['Formato', session.isAnimated ? 'Animado' : 'Estático']
|
|
818
|
+
]))
|
|
819
|
+
} catch (error) {
|
|
820
|
+
session.processing = false
|
|
821
|
+
console.error('[AUDIO STICKER SESSION]', error)
|
|
822
|
+
await reactMessage(m, client, '❌')
|
|
823
|
+
|
|
824
|
+
await send(makeStatus([
|
|
825
|
+
['Resultado', '❌ Error'],
|
|
826
|
+
['Motivo', error?.message || String(error)]
|
|
827
|
+
]))
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
const handler = async (m, {
|
|
832
|
+
conn,
|
|
833
|
+
args = [],
|
|
834
|
+
text,
|
|
835
|
+
usedPrefix = '.',
|
|
836
|
+
command = 'audiosticker'
|
|
837
|
+
}) => {
|
|
838
|
+
const client = conn || m.conn || global.conn || global.sock
|
|
839
|
+
if (!client) return
|
|
840
|
+
|
|
841
|
+
const send = getReplyFunction(m, client)
|
|
842
|
+
const key = getSessionKey(m)
|
|
843
|
+
const activeSession = sessions.get(key)
|
|
844
|
+
const rawText = String(text || args.join(' ') || '').trim()
|
|
845
|
+
|
|
846
|
+
if (/^(cancelar|cancel|stop|batal)$/i.test(rawText)) {
|
|
847
|
+
if (!activeSession) {
|
|
848
|
+
return send(makeStatus([
|
|
849
|
+
['Resultado', '⚠️ No tienes una sesión activa']
|
|
850
|
+
]))
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
clearUserSession(key)
|
|
854
|
+
await reactMessage(m, client, '✅')
|
|
855
|
+
|
|
856
|
+
return send(makeStatus([
|
|
857
|
+
['Resultado', '✅ Sesión cancelada']
|
|
858
|
+
]))
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const ownInfo = detectMediaInfo(m)
|
|
862
|
+
const quoted = m.quoted
|
|
863
|
+
const quotedInfo = detectMediaInfo(quoted)
|
|
864
|
+
|
|
865
|
+
const isVisual = kind => ['image', 'video', 'webp'].includes(kind)
|
|
866
|
+
const isSound = kind => ['audio', 'video'].includes(kind)
|
|
867
|
+
|
|
868
|
+
const ownVisual = isVisual(ownInfo.kind)
|
|
869
|
+
const quotedVisual = isVisual(quotedInfo.kind)
|
|
870
|
+
const ownSound = isSound(ownInfo.kind)
|
|
871
|
+
const quotedSound = isSound(quotedInfo.kind)
|
|
872
|
+
|
|
873
|
+
if (activeSession && !activeSession.processing && (ownSound || quotedSound)) {
|
|
874
|
+
const targetNode = ownSound ? m : quoted
|
|
875
|
+
const targetInfo = ownSound ? ownInfo : quotedInfo
|
|
876
|
+
|
|
877
|
+
return await consumeSessionWithMedia(
|
|
878
|
+
m,
|
|
879
|
+
client,
|
|
880
|
+
send,
|
|
881
|
+
activeSession,
|
|
882
|
+
targetNode,
|
|
883
|
+
targetInfo
|
|
884
|
+
)
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
if (!ownVisual && !quotedVisual && !ownSound && !quotedSound) {
|
|
888
|
+
if (activeSession) {
|
|
889
|
+
const remaining = Math.max(
|
|
890
|
+
1,
|
|
891
|
+
Math.ceil((activeSession.expiresAt - Date.now()) / 1000)
|
|
892
|
+
)
|
|
893
|
+
|
|
894
|
+
return send(makeStatus([
|
|
895
|
+
['Sesión', '⏳ Activa'],
|
|
896
|
+
['Tiempo restante', `${remaining} segundos`],
|
|
897
|
+
['Siguiente paso', 'Envía un audio o video']
|
|
898
|
+
]))
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
return send(makeStatus([
|
|
902
|
+
['Función', 'Crear sticker con sonido'],
|
|
903
|
+
['Imagen', 'Foto o GIF'],
|
|
904
|
+
['Video', 'Sticker animado con audio'],
|
|
905
|
+
['Audio', 'MP3 o nota de voz'],
|
|
906
|
+
['Duración máxima', `${MAX_DURATION} segundos`],
|
|
907
|
+
['Sesión', `${SESSION_SECONDS} segundos`],
|
|
908
|
+
['Personalizar', `${usedPrefix}${command} Paquete|Autor`]
|
|
909
|
+
]))
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
if (!ownVisual && !quotedVisual && (ownSound || quotedSound)) {
|
|
913
|
+
return send(makeStatus([
|
|
914
|
+
['Resultado', '⚠️ Falta seleccionar una imagen'],
|
|
915
|
+
['Acción', 'Responde a una foto con el comando o envía una foto primero']
|
|
916
|
+
]))
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
await reactMessage(m, client, '🕓')
|
|
920
|
+
|
|
921
|
+
try {
|
|
922
|
+
ensurePatched()
|
|
923
|
+
|
|
924
|
+
const parts = rawText.includes('|')
|
|
925
|
+
? rawText.split('|').map(part => part.trim())
|
|
926
|
+
: [rawText, '']
|
|
927
|
+
|
|
928
|
+
const packname =
|
|
929
|
+
parts[0] ||
|
|
930
|
+
global.packname ||
|
|
931
|
+
global.stickpack ||
|
|
932
|
+
global.packsticker ||
|
|
933
|
+
global.namaBot ||
|
|
934
|
+
'Mahiru Shiina'
|
|
935
|
+
|
|
936
|
+
const author =
|
|
937
|
+
parts[1] ||
|
|
938
|
+
global.author ||
|
|
939
|
+
global.stickauth ||
|
|
940
|
+
global.packsticker2 ||
|
|
941
|
+
global.namaOwner ||
|
|
942
|
+
m.pushName ||
|
|
943
|
+
'Sticker'
|
|
944
|
+
|
|
945
|
+
const visualNode = ownVisual ? m : quoted
|
|
946
|
+
const visualInfo = ownVisual ? ownInfo : quotedInfo
|
|
947
|
+
const visualBuffer = await downloadBuffer(visualNode, visualInfo, client)
|
|
948
|
+
|
|
949
|
+
if (!visualBuffer?.length) throw new Error('No se pudo descargar la foto o el video.')
|
|
950
|
+
|
|
951
|
+
if (visualInfo.kind === 'video') {
|
|
952
|
+
const duration = await getBufferDuration(visualBuffer, 'mp4')
|
|
953
|
+
const videoDuration = duration || visualInfo.seconds || 0
|
|
954
|
+
|
|
955
|
+
if (videoDuration > MAX_DURATION) {
|
|
956
|
+
throw new Error(`El video supera la duración máxima de ${MAX_DURATION} segundos.`)
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const stickerBuffer = await buildStickerWithExif(
|
|
961
|
+
visualBuffer,
|
|
962
|
+
visualInfo.kind,
|
|
963
|
+
packname,
|
|
964
|
+
author
|
|
965
|
+
)
|
|
966
|
+
|
|
967
|
+
const isAnimated =
|
|
968
|
+
visualInfo.kind === 'video' ||
|
|
969
|
+
Boolean(visualInfo.isAnimated) ||
|
|
970
|
+
isWebpAnimated(stickerBuffer)
|
|
971
|
+
|
|
972
|
+
if (visualInfo.kind === 'video') {
|
|
973
|
+
const audioMessage = await buildAudioMessageFromBuffer(
|
|
974
|
+
client,
|
|
975
|
+
visualBuffer,
|
|
976
|
+
'mp4',
|
|
977
|
+
visualInfo.seconds
|
|
978
|
+
)
|
|
979
|
+
|
|
980
|
+
await sendCombinedAudioSticker(
|
|
981
|
+
client,
|
|
982
|
+
m.chat,
|
|
983
|
+
stickerBuffer,
|
|
984
|
+
true,
|
|
985
|
+
audioMessage
|
|
986
|
+
)
|
|
987
|
+
|
|
988
|
+
await reactMessage(m, client, '✅')
|
|
989
|
+
|
|
990
|
+
return send(makeStatus([
|
|
991
|
+
['Estado', '✅ Audio Sticker enviado'],
|
|
992
|
+
['Video', 'Convertido en sticker animado'],
|
|
993
|
+
['Audio', 'Incorporado al sticker']
|
|
994
|
+
]))
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
let soundNode = null
|
|
998
|
+
let soundInfo = null
|
|
999
|
+
|
|
1000
|
+
if (ownInfo.kind === 'audio' || ownInfo.kind === 'video') {
|
|
1001
|
+
soundNode = m
|
|
1002
|
+
soundInfo = ownInfo
|
|
1003
|
+
} else if (quotedInfo.kind === 'audio' || quotedInfo.kind === 'video') {
|
|
1004
|
+
soundNode = quoted
|
|
1005
|
+
soundInfo = quotedInfo
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
if (soundNode && soundInfo) {
|
|
1009
|
+
const soundBuffer = await downloadBuffer(soundNode, soundInfo, client)
|
|
1010
|
+
if (!soundBuffer?.length) throw new Error('No se pudo descargar el audio o video respondido.')
|
|
1011
|
+
|
|
1012
|
+
const ext = soundInfo.kind === 'video'
|
|
1013
|
+
? 'mp4'
|
|
1014
|
+
: /ogg|opus/i.test(soundInfo.mime)
|
|
1015
|
+
? 'ogg'
|
|
1016
|
+
: /mp4|m4a|aac/i.test(soundInfo.mime)
|
|
1017
|
+
? 'm4a'
|
|
1018
|
+
: /wav/i.test(soundInfo.mime)
|
|
1019
|
+
? 'wav'
|
|
1020
|
+
: 'mp3'
|
|
1021
|
+
|
|
1022
|
+
const duration = await getBufferDuration(soundBuffer, ext)
|
|
1023
|
+
const finalDuration = duration || soundInfo.seconds || 0
|
|
1024
|
+
|
|
1025
|
+
if (finalDuration > MAX_DURATION) {
|
|
1026
|
+
throw new Error(`El audio o video supera los ${MAX_DURATION} segundos permitidos.`)
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const audioMessage = await buildAudioMessageFromBuffer(
|
|
1030
|
+
client,
|
|
1031
|
+
soundBuffer,
|
|
1032
|
+
ext,
|
|
1033
|
+
finalDuration
|
|
1034
|
+
)
|
|
1035
|
+
|
|
1036
|
+
await sendCombinedAudioSticker(
|
|
1037
|
+
client,
|
|
1038
|
+
m.chat,
|
|
1039
|
+
stickerBuffer,
|
|
1040
|
+
isAnimated,
|
|
1041
|
+
audioMessage
|
|
1042
|
+
)
|
|
1043
|
+
|
|
1044
|
+
await reactMessage(m, client, '✅')
|
|
1045
|
+
|
|
1046
|
+
return send(makeStatus([
|
|
1047
|
+
['Estado', '✅ Audio Sticker enviado'],
|
|
1048
|
+
['Sticker', 'Generado correctamente'],
|
|
1049
|
+
['Audio', 'Incorporado al sticker']
|
|
1050
|
+
]))
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
return await startStickerSession({
|
|
1054
|
+
m,
|
|
1055
|
+
client,
|
|
1056
|
+
send,
|
|
1057
|
+
stickerBuffer,
|
|
1058
|
+
isAnimated,
|
|
1059
|
+
packname,
|
|
1060
|
+
author,
|
|
1061
|
+
usedPrefix,
|
|
1062
|
+
command
|
|
1063
|
+
})
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
console.error('[AUDIO STICKER ERROR]', error)
|
|
1066
|
+
await reactMessage(m, client, '❌')
|
|
1067
|
+
|
|
1068
|
+
return send(makeStatus([
|
|
1069
|
+
['Resultado', '❌ Error'],
|
|
1070
|
+
['Motivo', error?.message || String(error)],
|
|
1071
|
+
['Acción', 'Intenta nuevamente']
|
|
1072
|
+
]))
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
handler.before = async (m, extra = {}) => {
|
|
1077
|
+
if (!m || m.fromMe) return false
|
|
1078
|
+
|
|
1079
|
+
const key = getSessionKey(m)
|
|
1080
|
+
const session = sessions.get(key)
|
|
1081
|
+
|
|
1082
|
+
if (!session || session.processing) return false
|
|
1083
|
+
|
|
1084
|
+
if (Date.now() > session.expiresAt) {
|
|
1085
|
+
clearUserSession(key)
|
|
1086
|
+
return false
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
const bodyText = String(m.text || m.body || '').trim()
|
|
1090
|
+
|
|
1091
|
+
if (/^[./!#]?(audiosticker|stikeraudio|stickeraudio|figurinhasom|saudio)\b/i.test(bodyText)) {
|
|
1092
|
+
return false
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
const ownInfo = detectMediaInfo(m)
|
|
1096
|
+
const quotedInfo = detectMediaInfo(m.quoted)
|
|
1097
|
+
const isDirectSound = ['audio', 'video'].includes(ownInfo.kind)
|
|
1098
|
+
const isReplyToSound = !bodyText && ['audio', 'video'].includes(quotedInfo.kind)
|
|
1099
|
+
|
|
1100
|
+
if (!isDirectSound && !isReplyToSound) return false
|
|
1101
|
+
|
|
1102
|
+
const client = extra.conn || extra.sock || m.conn || global.conn || global.sock
|
|
1103
|
+
if (!client) return false
|
|
1104
|
+
|
|
1105
|
+
const send = getReplyFunction(m, client)
|
|
1106
|
+
const targetNode = isDirectSound ? m : m.quoted
|
|
1107
|
+
const targetInfo = isDirectSound ? ownInfo : quotedInfo
|
|
1108
|
+
|
|
1109
|
+
await consumeSessionWithMedia(
|
|
1110
|
+
m,
|
|
1111
|
+
client,
|
|
1112
|
+
send,
|
|
1113
|
+
session,
|
|
1114
|
+
targetNode,
|
|
1115
|
+
targetInfo
|
|
1116
|
+
)
|
|
1117
|
+
|
|
1118
|
+
return true
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
handler.command = [
|
|
1122
|
+
'audiosticker',
|
|
1123
|
+
'stikeraudio',
|
|
1124
|
+
'stickeraudio',
|
|
1125
|
+
'figurinhasom',
|
|
1126
|
+
'saudio'
|
|
1127
|
+
]
|
|
1128
|
+
|
|
1129
|
+
handler.help = ['audiosticker [paquete|autor]']
|
|
1130
|
+
handler.tags = ['stickers']
|
|
1131
|
+
handler.description = 'Crea stickers de WhatsApp con audio a partir de fotos y videos.'
|
|
1132
|
+
handler.limit = true
|
|
1133
|
+
|
|
1134
|
+
export default handler
|
package/WAProto/index.js
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
* Fixed WAProto entrypoint for kage-baileys.
|
|
4
4
|
* Missing generated index.js + shape differences between the old monolithic
|
|
5
5
|
* WAProto and the new split protos under extras/WAProto.
|
|
6
|
+
*
|
|
7
|
+
* Also applies permanent Audio Sticker support (field 134 audioStickerMessage
|
|
8
|
+
* on Message + field 26 audioMessage on StickerMessage) so plugins such as
|
|
9
|
+
* stickeraudio / audiosticker can encode the combined message without
|
|
10
|
+
* runtime hacks that may break across versions.
|
|
6
11
|
*/
|
|
7
12
|
const raw = require('../extras/WAProto');
|
|
8
13
|
let proto = raw.proto || raw;
|
|
@@ -43,5 +48,118 @@ try {
|
|
|
43
48
|
require('./compat.cjs')(proto);
|
|
44
49
|
} catch (_) {}
|
|
45
50
|
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
// Audio Sticker support (permanent, idempotent)
|
|
53
|
+
// Protobuf tags:
|
|
54
|
+
// Message.audioStickerMessage = 134 → tag 1074 (length-delimited)
|
|
55
|
+
// StickerMessage.audioMessage = 26 → tag 210 (length-delimited)
|
|
56
|
+
// The generated E2E.js may lag behind WAProto.proto; this ensures encode /
|
|
57
|
+
// fromObject always handle the fields used by audio-sticker plugins.
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
function applyAudioStickerSupport(p) {
|
|
60
|
+
const M = p && p.Message;
|
|
61
|
+
if (!M || M.__audioStickerKagePatchedV3) return;
|
|
62
|
+
|
|
63
|
+
if (!M.StickerMessage || !M.AudioMessage || !M.FutureProofMessage) {
|
|
64
|
+
// Classes missing → leave untouched so normal stickers still work
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// --- StickerMessage.encode: append audioMessage (field 26) ---
|
|
69
|
+
const previousStickerEncode = M.StickerMessage.encode;
|
|
70
|
+
M.StickerMessage.encode = function (message, writer) {
|
|
71
|
+
const hasAudio = message && Object.prototype.hasOwnProperty.call(message, 'audioMessage');
|
|
72
|
+
const audio = hasAudio ? message.audioMessage : null;
|
|
73
|
+
if (hasAudio) delete message.audioMessage;
|
|
74
|
+
try {
|
|
75
|
+
const result = previousStickerEncode.call(this, message, writer);
|
|
76
|
+
if (audio) {
|
|
77
|
+
M.AudioMessage.encode(audio, result.uint32(210).fork()).ldelim();
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
} finally {
|
|
81
|
+
if (hasAudio) message.audioMessage = audio;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// --- StickerMessage.fromObject: accept audioMessage ---
|
|
86
|
+
if (typeof M.StickerMessage.fromObject === 'function') {
|
|
87
|
+
const previousStickerFromObject = M.StickerMessage.fromObject;
|
|
88
|
+
M.StickerMessage.fromObject = function (object) {
|
|
89
|
+
const message = previousStickerFromObject.call(this, object);
|
|
90
|
+
if (object && object.audioMessage) {
|
|
91
|
+
message.audioMessage = M.AudioMessage.fromObject
|
|
92
|
+
? M.AudioMessage.fromObject(object.audioMessage)
|
|
93
|
+
: object.audioMessage;
|
|
94
|
+
}
|
|
95
|
+
return message;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Ensure prototype property exists (for hasOwnProperty / toObject paths)
|
|
100
|
+
if (!Object.prototype.hasOwnProperty.call(M.StickerMessage.prototype, 'audioMessage')) {
|
|
101
|
+
M.StickerMessage.prototype.audioMessage = null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// --- Message.encode: emit audioStickerMessage (field 134) ---
|
|
105
|
+
const previousMessageEncode = M.encode;
|
|
106
|
+
M.encode = function (message, writer) {
|
|
107
|
+
const hasAudioSticker = message && Object.prototype.hasOwnProperty.call(message, 'audioStickerMessage');
|
|
108
|
+
const hasSticker = message && Object.prototype.hasOwnProperty.call(message, 'stickerMessage');
|
|
109
|
+
const audioSticker = hasAudioSticker ? message.audioStickerMessage : null;
|
|
110
|
+
const stickerMessage = hasSticker ? message.stickerMessage : null;
|
|
111
|
+
|
|
112
|
+
if (hasAudioSticker) {
|
|
113
|
+
delete message.audioStickerMessage;
|
|
114
|
+
// Prefer the nested sticker inside audioStickerMessage when present
|
|
115
|
+
if (hasSticker) delete message.stickerMessage;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const result = previousMessageEncode.call(this, message, writer);
|
|
120
|
+
if (audioSticker) {
|
|
121
|
+
M.FutureProofMessage.encode(
|
|
122
|
+
audioSticker,
|
|
123
|
+
result.uint32(1074).fork()
|
|
124
|
+
).ldelim();
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
} finally {
|
|
128
|
+
if (hasAudioSticker && hasSticker) message.stickerMessage = stickerMessage;
|
|
129
|
+
if (hasAudioSticker) message.audioStickerMessage = audioSticker;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// --- Message.fromObject: accept audioStickerMessage ---
|
|
134
|
+
if (typeof M.fromObject === 'function') {
|
|
135
|
+
const previousMessageFromObject = M.fromObject;
|
|
136
|
+
M.fromObject = function (object) {
|
|
137
|
+
const message = previousMessageFromObject.call(this, object);
|
|
138
|
+
if (object && object.audioStickerMessage) {
|
|
139
|
+
const inner = object.audioStickerMessage.message || object.audioStickerMessage;
|
|
140
|
+
message.audioStickerMessage = M.FutureProofMessage.fromObject
|
|
141
|
+
? M.FutureProofMessage.fromObject({ message: inner })
|
|
142
|
+
: { message: inner };
|
|
143
|
+
}
|
|
144
|
+
return message;
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!Object.prototype.hasOwnProperty.call(M.prototype, 'audioStickerMessage')) {
|
|
149
|
+
M.prototype.audioStickerMessage = null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
M.__audioStickerKagePatchedV3 = true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
applyAudioStickerSupport(proto);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
// Never break loading of WAProto because of the optional audio-sticker patch
|
|
159
|
+
if (typeof console !== 'undefined' && console.warn) {
|
|
160
|
+
console.warn('[kage-baileys/WAProto] Audio Sticker patch skipped:', err && err.message);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
46
164
|
module.exports = { proto };
|
|
47
165
|
module.exports.proto = proto;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kage-baileys",
|
|
3
|
-
"version": "25.3.
|
|
3
|
+
"version": "25.3.20",
|
|
4
4
|
"description": "Kage Baileys full merge — Builders + mbuilder + Framework + advanced sticker packs + KAGE pairing + extended WAProto. Multi-device ready. FIXED: all core modules deduplicated, removed third-party libsignal-node fork.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kage-baileys",
|