buatscrape.js
buatscrape — pabrik plugin downloader. Kasih URL website → bot otomatis generate plugin scraper multi-engine (yt-dlp, API, Playwright, Scrape).
JSJavaScriptPublicPluginsMIT1 file · 720 baris · 31.2 KBDiperbarui 24 Okt 202665 views
https://codeku.itsuki-nakano.my.id/repo/alwayslenzz/buatscrape-jscurl -s https://codeku.itsuki-nakano.my.id/raw/alwayslenzz/buatscrape-jsFILES
buatscrape.js · javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/**
* ─────────────────────────────────────────────────────────────
* buatscrape
* Multi-Engine Scraper Generator
* ─────────────────────────────────────────────────────────────
*
* Authors : Nakano Itsuki, AlwaysLennz
* Version : 2.0.0
* License : MIT
* Runtime : Node.js ≥ 18
* Created : 2026
*
* Engines : yt-dlp · API Downloader · Playwright · Cheerio
* Dependencies: yt-dlp, ffmpeg, playwright (all optional —
* engine auto-skips if the binary is unavailable)
*
* ─────────────────────────────────────────────────────────────
* CARA KERJA
* ─────────────────────────────────────────────────────────────
* Plugin ini adalah generator — dia mencetak plugin downloader
* baru berdasarkan URL website yang diberikan.
*
* FASE 1 — Generate Plugin:
* 1. Owner kirim `.buatscrape <nama> | <url>`
* 2. Bot menganalisis website target:
* • Deteksi search form + parameter query
* • Skoring 40+ selector untuk list konten terbaik
* • Deteksi framework (WP/Next/Nuxt) & Cloudflare
* • Cek keberadaan tag <video> / <iframe>
* 3. Bot men-generate file plugin baru di folder downloader/
* dengan konfigurasi hasil analisis + engine download
* 4. Hot reload → plugin langsung aktif tanpa restart bot
*
* FASE 2 — Pakai Plugin Hasil Generate:
* Plugin baru punya 4 lapis engine download (waterfall):
* 1. yt-dlp → engine utama, cepat & akurat
* 2. API Downloader → endpoint API (jika dikonfigurasi)
* 3. Playwright → headless browser, sadap network
* 4. HTML scrape → rekursif ke iframe player
*
* Jika hasil HLS (.m3u8) → auto-convert ke mp4 via ffmpeg.
* Jika file > 64 MB → kirim link saja (bukan file).
*
* ─────────────────────────────────────────────────────────────
* CARA PEMAKAIAN
* ─────────────────────────────────────────────────────────────
*
* [1] Generate plugin baru (owner only):
* .buatscrape nekopoi | https://nekopoi.care
* .buatscrape otakudesu | https://otakudesu.cloud
*
* [2] Setelah plugin jadi, gunakan di chat:
* .<nama> → Lihat list konten terbaru
* .<nama>srch <judul> → Cari konten
* .<nama>dl <url> → Download video dari URL
*
* Contoh (jika nama = nekopoi):
* .nekopoi
* .nekopoi srch one piece
* .nekopoi dl https://nekopoi.care/xxx
*
* [3] Konfigurasi API (opsional):
* Isi BASE_URL + API_KEY di bawah untuk mengaktifkan
* engine API downloader. Kosongkan ('') untuk skip.
*
* ─────────────────────────────────────────────────────────────
* ⚠️ JANGAN HAPUS CREDITS — HARGAILAH DEVELOPER
* ─────────────────────────────────────────────────────────────
* Plugin ini dibuat dengan usaha & waktu. Jika kamu memakai,
* memodifikasi, atau membagikan ulang, mohon tetap
* mencantumkan nama developer asli.
*
* Menghapus credits = tidak menghargai kerja orang lain.
* ─────────────────────────────────────────────────────────────
*
* © 2026 Nakano Itsuki · AlwaysLennz
* ─────────────────────────────────────────────────────────────
*/
// ─────────────────────────────────────────────────────────────
// API CONFIGURATION
// Set BASE_URL + API_KEY to enable the API download engine.
// Leave both empty ('') to disable the API engine entirely.
//
// Expected response schema:
// {
// "status": true,
// "result": {
// "title": "string",
// "formats": [{ "type": "video", "ext": "mp4", "url": "string" }]
// }
// }
// ─────────────────────────────────────────────────────────────
const BASE_URL = '' // e.g. 'https://api.example.com'
const API_KEY = '' // e.g. 'sk_live_xxxxxxxxxxxxxxxx'
// ─────────────────────────────────────────────────────────────
const cheerio = require('cheerio')
const codegen = require('../../src/lib/fixkit/codegen')
const ui = require('../../src/lib/fixkit/ui')
const { validateUrl } = require('../../src/lib/fixkit/scrape')
const { argText, splitPipe } = require('../../src/lib/fixkit/args')
const { hotReloadPlugin } = require('../../src/lib/plugins')
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
const HEADERS = {
'User-Agent': USER_AGENT,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9,id;q=0.8',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Upgrade-Insecure-Requests': '1',
}
const LIST_CANDIDATES = [
'article h2 a', 'article h3 a', 'article .title a', 'article a[href]',
'.post-title a', '.entry-title a', '.post-item h2 a', '.post-item a',
'.video-title a', '.movie-title a', '.film-title a', '.anime-title a',
'.title a', '.card-title a', '.item-title a', '.media-title a',
'.post h2 a', '.entry h2 a', '.card a', '.item a', '.grid a[href]',
'h2 a', 'h3 a', 'h4 a',
'[class*="title"] a', '[class*="post"] a[href]', '[class*="item"] a[href]',
'main a[href]', 'a[href]'
]
const pluginConfig = {
name: 'buatscrape',
alias: ['makescrape', 'scrapebuat', 'genplugin'],
category: 'owner',
description: 'Generate plugin scraper multi-engine (yt-dlp + Playwright + API opsional)',
usage: '.buatscrape <nama> | <url>',
example: '.buatscrape nekopoi | https://nekopoi.care',
isOwner: true,
cooldown: 5,
isEnabled: true,
}
function detectCloudflare(html) {
if (!html) return false
return /cf-browser-verification|cf-challenge|just a moment|checking your browser|cf_clearance|__cf_chl|attention required/i.test(html)
}
function detectFrameworks(html) {
const fw = []
if (/wp-content|wordpress/i.test(html)) fw.push('WordPress')
if (/__NEXT_DATA__|next\/static/i.test(html)) fw.push('Next.js')
if (/__NUXT__|nuxt-link/i.test(html)) fw.push('Nuxt')
if (/__sveltekit|svelte-/i.test(html)) fw.push('SvelteKit')
return fw
}
async function analyzeTarget(url) {
const result = {
host: new URL(url).hostname,
searchUrl: null,
searchParam: 'q',
listSelector: 'a[href]',
samples: [],
hasVideo: false,
hasIframe: false,
cloudflare: false,
frameworks: [],
ogImage: '',
title: '',
error: null,
isFallback: false,
}
try {
const res = await fetch(url, {
headers: HEADERS,
redirect: 'follow',
signal: AbortSignal.timeout(15000),
})
if (!res.ok) {
result.error = `HTTP ${res.status} ${res.statusText}`
result.isFallback = true
return result
}
const html = await res.text()
const $ = cheerio.load(html)
result.cloudflare = detectCloudflare(html)
result.frameworks = detectFrameworks(html)
result.title = $('title').text().trim().slice(0, 120)
result.ogImage = $('meta[property="og:image"]').attr('content') || ''
result.hasVideo = $('video').length > 0
result.hasIframe = $('iframe[src]').length > 0
$('form').each((_, el) => {
if (result.searchUrl) return false
const action = $(el).attr('action') || ''
const $input = $(el).find(
'input[type="search"], input[name*="search" i], input[name*="q" i], input[name*="cari" i], input[name="s" i]'
).first()
const inputName = $input.attr('name')
if (!inputName) return
try {
result.searchParam = inputName
result.searchUrl = action ? new URL(action, url).toString() : `${new URL(url).origin}/search`
} catch {}
})
if (!result.searchUrl) {
try { result.searchUrl = new URL('/search', url).toString() } catch {}
}
let listSelector = 'a[href]'
let bestScore = 0
for (const sel of LIST_CANDIDATES) {
let els
try { els = $(sel) } catch { continue }
if (!els || els.length < 3) continue
let score = 0
els.slice(0, 25).each((_, el) => {
const t = $(el).text().trim()
if (t.length > 3 && t.length < 200) score++
})
if (score > bestScore) {
bestScore = score
listSelector = sel
}
}
result.listSelector = listSelector
$(listSelector).slice(0, 5).each((_, el) => {
const text = $(el).text().trim().replace(/\s+/g, ' ').slice(0, 80)
let link = $(el).attr('href') || $(el).find('a').attr('href') || ''
if (link && !/^https?:\/\//i.test(link)) {
try { link = new URL(link, url).toString() } catch {}
}
if (text && link) result.samples.push({ text, link })
})
return result
} catch (e) {
result.error = e.message
result.isFallback = true
return result
}
}
function buildPluginCode({ name, url, analysis }) {
const cfg = {
name,
sourceUrl: url,
host: analysis.host,
searchUrl: analysis.searchUrl || '',
searchParam: analysis.searchParam || 'q',
listSelector: analysis.listSelector || 'a[href]',
}
const cfgJson = JSON.stringify(cfg, null, 2)
const aliasJson = JSON.stringify([
`${name}srch`, `${name}search`,
`${name}dl`, `${name}download`,
])
const L = []
const p = (s = '') => L.push(s)
// ───── Generated plugin: header + metadata + API config ─────
p("/**")
p(" * ─────────────────────────────────────────────────────────────")
p(` * ${name}`)
p(" * Auto-generated downloader plugin")
p(" * ─────────────────────────────────────────────────────────────")
p(" *")
p(" * Authors : Nakano Itsuki, AlwaysLennz")
p(` * Target : ${analysis.host}`)
p(` * Build : ${new Date().toISOString().split('T')[0]}`)
p(" * Generated by: buatscrape v2.0.0")
p(" * License : MIT")
p(" *")
p(" * Engines : yt-dlp → API → Playwright → HTML scrape")
p(" *")
p(" * ─────────────────────────────────────────────────────────")
p(" * CARA PAKAI")
p(" * ─────────────────────────────────────────────────────────")
p(` * .${name} → List konten terbaru`)
p(` * .${name}srch <judul> → Cari konten`)
p(` * .${name}dl <url> → Download video`)
p(" *")
p(" * ─────────────────────────────────────────────────────────")
p(" * ⚠️ JANGAN HAPUS CREDITS — HARGAILAH DEVELOPER")
p(" * ─────────────────────────────────────────────────────────")
p(" * Plugin ini di-generate otomatis. Jika kamu memakai,")
p(" * memodifikasi, atau membagikan ulang plugin ini, mohon")
p(" * tetap mencantumkan nama developer asli.")
p(" *")
p(" * Menghapus credits = tidak menghargai kerja orang lain.")
p(" * ─────────────────────────────────────────────────────────")
p(" *")
p(" * © 2026 Nakano Itsuki · AlwaysLennz")
p(" * ─────────────────────────────────────────────────────────────")
p(" */")
p("")
p("// ─────────────────────────────────────────────────────────────")
p("// API CONFIGURATION (optional)")
p("// Leave empty ('') to disable the API engine.")
p("// ─────────────────────────────────────────────────────────────")
p(`const API_BASE_URL = ${JSON.stringify(BASE_URL)}`)
p(`const API_KEY = ${JSON.stringify(API_KEY)}`)
p("// ─────────────────────────────────────────────────────────────")
p("")
// ───── Imports ─────
p("const cheerio = require('cheerio')")
p("const { argText } = require('../../src/lib/fixkit/args')")
p("const { execFile } = require('child_process')")
p("const { promisify } = require('util')")
p("const fs = require('fs')")
p("const os = require('os')")
p("const path = require('path')")
p("const pExec = promisify(execFile)")
p("")
p("let chromium = null")
p("try { chromium = require('playwright').chromium } catch {}")
p("")
p(`const CFG = ${cfgJson}`)
p(`const UA = ${JSON.stringify(USER_AGENT)}`)
p("const MAX_FILE_MB = 64")
p("")
p("const pluginConfig = {")
p(" isOwner: false, isPremium: false, isGroup: false, isPrivate: false,")
p(" energi: 0,")
p(` name: ${JSON.stringify(name)},`)
p(` alias: ${aliasJson},`)
p(" category: 'downloader',")
p(` description: 'Super Scraper (yt-dlp + Playwright) - ' + CFG.host,`)
p(` usage: '.${name} [limit] | .${name}srch <query> | .${name}dl <url>',`)
p(` example: '.${name}srch anime',`)
p(" cooldown: 10, isEnabled: true,")
p("}")
p("")
// ───── Helpers ─────
p("const sleep = (ms) => new Promise(r => setTimeout(r, ms))")
p("")
p("function cleanUrl(u) {")
p(" try { const o = new URL(u); o.hash = ''; return o.toString() } catch { return u }")
p("}")
p("")
p("function absUrl(base, u) {")
p(" if (!u) return ''")
p(" if (/^https?:\\/\\//i.test(u)) return u")
p(" try { return new URL(u, base).toString() } catch { return '' }")
p("}")
p("")
p("function isPureVideoUrl(u) {")
p(" if (!u) return false")
p(" if (!/\\.(mp4|m3u8|webm|mkv|mov)(\\?|$)/i.test(u)) return false")
p(" if (/(playmogo|dood|streamtape|vidhide|filemoon|streama|embed)/i.test(u)) return false")
p(" return true")
p("}")
p("")
p("function buildSearchUrl(base, param, q) {")
p(" try { const u = new URL(base); u.searchParams.set(param, q); return u.toString() }")
p(" catch { return base + (base.includes('?') ? '&' : '?') + param + '=' + encodeURIComponent(q) }")
p("}")
p("")
p("function sanitizeTitle(t) {")
p(" return (t || 'media').replace(/[\\\\/:*?\"<>|]+/g, '_').slice(0, 80)")
p("}")
p("")
// ───── yt-dlp ─────
p("async function tryYtdlp(targetUrl) {")
p(" try {")
p(" const { stdout } = await pExec('yt-dlp', ['-j', '--no-warnings', '--no-check-certificates', '--no-playlist', targetUrl],")
p(" { timeout: 60000, maxBuffer: 20 * 1024 * 1024 })")
p(" const info = JSON.parse(stdout)")
p(" const title = info.title || 'Media'")
p(" if (info.url && /^https?:\\/\\//.test(info.url)) {")
p(" if (/\\.m3u8(\\?|$)/i.test(info.url) && Array.isArray(info.formats)) {")
p(" const mp4 = info.formats.filter(f => f.ext === 'mp4' && f.acodec !== 'none' && f.vcodec !== 'none')")
p(" .sort((a, b) => (b.height || 0) - (a.height || 0))[0]")
p(" if (mp4 && mp4.url) return { title, bestVideo: mp4.url, ext: 'mp4' }")
p(" }")
p(" return { title, bestVideo: info.url, ext: info.ext || 'mp4' }")
p(" }")
p(" if (Array.isArray(info.formats) && info.formats.length) {")
p(" const mp4s = info.formats.filter(f => f.url && f.ext === 'mp4' && f.acodec !== 'none' && f.vcodec !== 'none')")
p(" .sort((a, b) => (b.height || 0) - (a.height || 0))")
p(" if (mp4s[0]) return { title, bestVideo: mp4s[0].url, ext: 'mp4' }")
p(" const any = info.formats.find(f => f.url)")
p(" if (any) return { title, bestVideo: any.url, ext: any.ext || 'mp4' }")
p(" }")
p(" return null")
p(" } catch { return null }")
p("}")
p("")
// ───── API Downloader (configurable) ─────
p("async function apiDownload(targetUrl) {")
p(" if (!API_BASE_URL || !API_KEY) return null")
p(" try {")
p(" const url = API_BASE_URL.replace(/\\/+$/, '') + '/api/v1/download/aio?url=' + encodeURIComponent(targetUrl)")
p(" const res = await fetch(url, {")
p(" headers: { 'x-api-key': API_KEY, 'Accept': 'application/json' },")
p(" signal: AbortSignal.timeout(30000),")
p(" })")
p(" if (!res.ok) return null")
p(" const json = await res.json()")
p(" return json.status ? (json.result || json.data) : null")
p(" } catch { return null }")
p("}")
p("")
// ───── Playwright ─────
p("const PLAY_SELECTORS = [")
p(" 'button[aria-label*=\"play\" i]', '.vjs-big-play-button', '.jw-icon-display',")
p(" '.play-button', '.btn-play', '.player-play', '[class*=\"play-btn\"]',")
p(" 'video'")
p("]")
p("const VIDEO_PATTERNS = /\\.(mp4|m3u8|webm|mkv|mov)(\\?|$)/i")
p("const BLOCK_PATTERNS = /(playmogo|dood|streamtape|vidhide|filemoon|streama|embed|ads|doubleclick|googlesyndication|analytics)/i")
p("")
p("async function playwrightExtract(targetUrl) {")
p(" if (!chromium) return null")
p(" let browser")
p(" try {")
p(" browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'] })")
p(" const context = await browser.newContext({ userAgent: UA, viewport: { width: 1280, height: 720 }, ignoreHTTPSErrors: true })")
p(" const page = await context.newPage()")
p("")
p(" let videoUrl = null")
p(" page.on('response', (resp) => {")
p(" if (videoUrl) return")
p(" try {")
p(" const u = resp.url()")
p(" const ct = (resp.headers()['content-type'] || '').toLowerCase()")
p(" if (BLOCK_PATTERNS.test(u)) return")
p(" if (resp.status() >= 400) return")
p(" if (ct.startsWith('video/') || ct.includes('mpegurl') || VIDEO_PATTERNS.test(u)) videoUrl = u")
p(" } catch {}")
p(" })")
p("")
p(" await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {})")
p("")
p(" for (const sel of PLAY_SELECTORS) {")
p(" try {")
p(" const el = await page.$(sel)")
p(" if (el) { await el.click({ timeout: 1500 }).catch(() => {}); break }")
p(" } catch {}")
p(" }")
p("")
p(" const started = Date.now()")
p(" while (!videoUrl && Date.now() - started < 12000) await sleep(500)")
p("")
p(" if (!videoUrl) {")
p(" const dom = await page.evaluate(() => {")
p(" const v = document.querySelector('video')")
p(" if (v) {")
p(" if (v.src && !v.src.startsWith('blob:')) return v.src")
p(" const s = v.querySelector('source')")
p(" if (s && s.src && !s.src.startsWith('blob:')) return s.src")
p(" for (const a of ['data-src', 'data-video', 'data-url', 'data-file']) {")
p(" const x = v.getAttribute(a); if (x) return x")
p(" }")
p(" }")
p(" const s2 = document.querySelector('source[src]')")
p(" return s2 && !s2.src.startsWith('blob:') ? s2.src : null")
p(" }).catch(() => null)")
p(" if (dom) videoUrl = dom")
p(" }")
p("")
p(" const title = await page.title().catch(() => 'Video')")
p(" return { title, videoUrl }")
p(" } catch { return null }")
p(" finally { if (browser) await browser.close().catch(() => {}) }")
p("}")
p("")
// ───── HLS to MP4 ─────
p("async function hlsToMp4(m3u8Url, referer) {")
p(" let out = null")
p(" try {")
p(" out = path.join(os.tmpdir(), `hls_${Date.now()}.mp4`)")
p(" const hdr = `User-Agent: ${UA}\\r\\nReferer: ${referer || ''}\\r\\n`")
p(" await pExec('ffmpeg', ['-y', '-i', m3u8Url, '-c', 'copy', '-bsf:a', 'aac_adtstoasc',")
p(" '-headers', hdr, '-t', '300', out], { timeout: 180000 })")
p(" const buf = fs.readFileSync(out)")
p(" return buf")
p(" } catch { return null }")
p(" finally { try { if (out) fs.unlinkSync(out) } catch {} }")
p("}")
p("")
// ───── fetchBuffer ─────
p("async function fetchBuffer(u, referer) {")
p(" const headers = { 'User-Agent': UA, 'Accept': '*/*' }")
p(" if (referer) {")
p(" headers['Referer'] = referer")
p(" try { headers['Origin'] = new URL(referer).origin } catch {}")
p(" }")
p(" const res = await fetch(u, { headers, redirect: 'follow', signal: AbortSignal.timeout(120000) })")
p(" if (!res.ok) throw new Error('HTTP ' + res.status)")
p(" const ct = res.headers.get('content-type') || ''")
p(" if (ct.includes('text/html')) throw new Error('Bukan file video (HTML)')")
p(" const len = parseInt(res.headers.get('content-length') || '0', 10)")
p(" if (len && len > MAX_FILE_MB * 1024 * 1024) throw new Error(`File ${(len/1024/1024).toFixed(1)}MB melebihi batas`)")
p(" const buf = Buffer.from(await res.arrayBuffer())")
p(" if (buf.length > MAX_FILE_MB * 1024 * 1024) throw new Error('File terlalu besar')")
p(" return buf")
p("}")
p("")
// ───── extractMedia ─────
p("async function extractMedia(targetUrl) {")
p(" targetUrl = cleanUrl(targetUrl)")
p("")
p(" // 1. yt-dlp")
p(" const yt = await tryYtdlp(targetUrl)")
p(" if (yt && yt.bestVideo) return { title: yt.title, bestVideo: yt.bestVideo, ext: yt.ext, allLinks: [], method: 'yt-dlp' }")
p("")
p(" // 2. API Downloader (kalau dikonfigurasi)")
p(" if (API_BASE_URL && API_KEY) {")
p(" const aio = await apiDownload(targetUrl)")
p(" if (aio && Array.isArray(aio.formats)) {")
p(" const best = aio.formats.filter(f => f.type === 'video' && f.ext === 'mp4').sort((a, b) => (b.size || 0) - (a.size || 0))[0]")
p(" if (best && best.url) {")
p(" const abs = absUrl(API_BASE_URL, best.url)")
p(" if (isPureVideoUrl(abs)) return { title: aio.title || 'Media', bestVideo: abs, ext: 'mp4', allLinks: [], method: 'api' }")
p(" }")
p(" }")
p(" }")
p("")
p(" // 3. Playwright")
p(" const pw = await playwrightExtract(targetUrl)")
p(" if (pw && pw.videoUrl && isPureVideoUrl(pw.videoUrl))")
p(" return { title: pw.title, bestVideo: pw.videoUrl, ext: /\\.m3u8/i.test(pw.videoUrl) ? 'm3u8' : 'mp4', allLinks: [], method: 'playwright' }")
p("")
p(" // 4. HTML iframe scrape + rekursif playwright")
p(" try {")
p(" const res = await fetch(targetUrl, { headers: { 'User-Agent': UA } })")
p(" const html = await res.text()")
p(" const $ = cheerio.load(html)")
p(" const playerLinks = new Set()")
p(" $('iframe').each((_, el) => {")
p(" const src = $(el).attr('src')")
p(" if (src) playerLinks.add(absUrl(targetUrl, src))")
p(" })")
p(" for (const play of playerLinks) {")
p(" const r = await playwrightExtract(play)")
p(" if (r && r.videoUrl && isPureVideoUrl(r.videoUrl))")
p(" return { title: r.title, bestVideo: r.videoUrl, ext: /\\.m3u8/i.test(r.videoUrl) ? 'm3u8' : 'mp4', allLinks: [], method: 'playwright-iframe' }")
p(" }")
p(" return { title: $('title').text(), bestVideo: null, allLinks: Array.from(playerLinks), method: 'none' }")
p(" } catch {")
p(" return { title: 'Unknown', bestVideo: null, allLinks: [], method: 'none' }")
p(" }")
p("}")
p("")
// ───── parseList ─────
p("async function parseList(targetUrl) {")
p(" const res = await fetch(targetUrl, { headers: { 'User-Agent': UA } })")
p(" const html = await res.text()")
p(" const $ = cheerio.load(html)")
p(" const items = []")
p(" $(CFG.listSelector).each((_, el) => {")
p(" const text = $(el).text().trim().replace(/\\s+/g, ' ')")
p(" const link = absUrl(targetUrl, $(el).attr('href') || $(el).find('a').attr('href') || '')")
p(" if (text.length > 3 && link && !/^#/.test(link) && !items.some(x => x.link === link))")
p(" items.push({ text, link })")
p(" })")
p(" return items")
p("}")
p("")
// ───── Handler ─────
p("async function handler(m, { sock }) {")
p(" const cmd = m.command || ''")
p(" const args = argText(m).trim()")
p(" try {")
p(" // SEARCH")
p(" if (cmd.includes('srch') || cmd.includes('search') || /^search\\b/i.test(args)) {")
p(" const q = args.replace(/^search\\s+/i, '').trim()")
p(" if (!q) return m.reply('Format: .' + CFG.name + 'srch <judul>')")
p(" if (!CFG.searchUrl) return m.reply('⚠️ Endpoint pencarian tidak terdeteksi.')")
p(" await m.reply('🔍 Mencari \"' + q + '\"...')")
p(" const items = await parseList(buildSearchUrl(CFG.searchUrl, CFG.searchParam, q))")
p(" if (!items.length) return m.reply('❌ Tidak ada hasil ditemukan.')")
p(" let out = '🔍 *Hasil Pencarian: ' + q + '*\\n\\n'")
p(" items.slice(0, 10).forEach((it, i) => { out += (i + 1) + '. ' + it.text + '\\n🔗 ' + it.link + '\\n\\n' })")
p(" out += '> Ketik .' + CFG.name + 'dl <url> untuk mendownload.'")
p(" return m.reply(out.trim())")
p(" }")
p("")
p(" // DOWNLOAD")
p(" if (cmd.includes('dl') || cmd.includes('download') || /^https?:\\/\\//i.test(args)) {")
p(" const target = args.split(/\\s+/)[0]")
p(" if (!/^https?:\\/\\//i.test(target)) return m.reply('Format: .' + CFG.name + 'dl <url>')")
p(" await m.reply('⏳ [1/3] Membongkar URL video (yt-dlp → API → Playwright)...')")
p("")
p(" const media = await extractMedia(target)")
p(" if (!media.bestVideo) {")
p(" let msg = '❌ *Gagal membongkar video.*\\n\\nSemua engine gagal. Website mungkin butuh login/captcha manual.\\n\\n'")
p(" if (media.allLinks?.length) {")
p(" msg += '*Iframe Alternatif:*\\n'")
p(" media.allLinks.slice(0, 5).forEach((l, i) => { msg += (i + 1) + '. ' + l + '\\n' })")
p(" }")
p(" return m.reply(msg)")
p(" }")
p("")
p(" try {")
p(" await m.reply(`📥 [2/3] Link ditemukan (${media.method}), mengunduh...`)")
p(" let buf")
p(" if (media.ext === 'm3u8' || /\\.m3u8(\\?|$)/i.test(media.bestVideo)) {")
p(" await m.reply('🔄 [HLS] Mengonversi m3u8 → mp4 via ffmpeg...')")
p(" buf = await hlsToMp4(media.bestVideo, target)")
p(" if (!buf) throw new Error('Konversi HLS gagal (ffmpeg tidak tersedia?)')")
p(" } else {")
p(" buf = await fetchBuffer(media.bestVideo, target)")
p(" }")
p(" const sizeMB = buf.length / (1024 * 1024)")
p(" if (sizeMB > MAX_FILE_MB) return m.reply(`⚠️ File ${sizeMB.toFixed(2)}MB > ${MAX_FILE_MB}MB.\\n\\n🔗 ${media.bestVideo}`)")
p(" await m.reply('📤 [3/3] Mengirim...')")
p(" const safeTitle = sanitizeTitle(media.title)")
p(" try {")
p(" await sock.sendMessage(m.chat, { video: buf, mimetype: 'video/mp4', caption: '🎬 *' + safeTitle + '*\\n\\n✅ via ' + media.method }, { quoted: m })")
p(" } catch {")
p(" await sock.sendMessage(m.chat, { document: buf, mimetype: 'video/mp4', fileName: safeTitle + '.mp4', caption: '🎬 *' + safeTitle + '*' }, { quoted: m })")
p(" }")
p(" } catch (e) {")
p(" return m.reply('⚠️ Gagal unduh/kirim: ' + e.message + '\\n\\n🔗 Link manual:\\n' + media.bestVideo)")
p(" }")
p(" return")
p(" }")
p("")
p(" // LIST")
p(" const items = await parseList(CFG.sourceUrl)")
p(" if (!items.length) return m.reply('⚠️ Tidak ada list / website memblokir bot.')")
p(" let out = '📥 *' + CFG.host + ' — Terbaru*\\n\\n'")
p(" items.slice(0, 10).forEach((it, i) => { out += (i + 1) + '. ' + it.text + '\\n🔗 ' + it.link + '\\n\\n' })")
p(" out += '> .' + CFG.name + 'srch <q> untuk cari\\n> .' + CFG.name + 'dl <url> untuk download'")
p(" return m.reply(out.trim())")
p(" } catch (e) {")
p(" return m.reply('❌ Error: ' + e.message)")
p(" }")
p("}")
p("")
p("module.exports = { config: pluginConfig, handler }")
return L.join('\n')
}
async function handler(m, { sock }) {
const [rawName, rawUrl] = splitPipe(argText(m))
if (!rawName || !rawUrl) return m.reply('Format: `.buatscrape nama | url`')
const name = rawName.toLowerCase().replace(/[^a-z0-9]/g, '')
let url
try { url = validateUrl(rawUrl) } catch (e) { return m.reply(`❌ ${e.message}`) }
await m.reply('🔎 Membedah website & menyiapkan multi-engine scraper...')
const analysis = await analyzeTarget(url)
const code = buildPluginCode({ name, url, analysis })
const res = codegen.writePlugin({ folder: 'downloader', fileName: name, code, hotReload: hotReloadPlugin })
if (!res.ok) return m.reply(`❌ Gagal menulis plugin:\n> ${res.error}`)
const lines = []
if (analysis.isFallback) {
lines.push(`⚠️ *Fallback mode* (${analysis.error})`)
} else {
lines.push(`✅ Analisis OK`)
lines.push(`• Host: \`${analysis.host}\``)
lines.push(`• Search: ${analysis.searchUrl ? `\`${analysis.searchParam}\` di \`${analysis.searchUrl}\`` : '❌ tidak ada'}`)
lines.push(`• Selector: \`${analysis.listSelector}\``)
lines.push(`• Video tag: ${analysis.hasVideo ? '✅' : '❌'} | Iframe: ${analysis.hasIframe ? '✅' : '❌'}`)
if (analysis.frameworks.length) lines.push(`• Framework: ${analysis.frameworks.join(', ')}`)
if (analysis.cloudflare) lines.push(`• ⚠️ Cloudflare detected`)
}
const apiStatus = (BASE_URL && API_KEY)
? `✅ API engine aktif (\`${BASE_URL}\`)`
: `⚪ API engine nonaktif (BASE_URL/API_KEY kosong)`
const footer = [
'',
'┌─ CREDITS ────────────────────',
'│ Nakano Itsuki',
'│ AlwaysLennz',
'├─ ENGINES ────────────────────',
'│ 1. yt-dlp',
'│ 2. API Downloader',
'│ 3. Playwright (headless)',
'└──────────────────────────────',
'',
'⚠️ *Jangan hapus credits — hargai developer.*',
].join('\n')
return ui.sendPanel(sock, m.chat, {
title: '🚀 Multi-Engine Scraper Ready',
body: [
lines.join('\n'),
'',
`*${apiStatus}*`,
'',
'*Perintah Tersedia:*',
`1. \`.${name}\` — List terbaru`,
`2. \`.${name}srch <judul>\` — Cari konten`,
`3. \`.${name}dl <url>\` — Download video`,
footer,
`*Reload:* ${res.reload?.success ? '✅' : '⚠ Gagal'}`,
].join('\n'),
buttons: [
{ type: 'reply', text: `▶ Coba List`, id: `.${name}` },
{ type: 'reply', text: `📁 Kirim File`, id: `.kirimplugin ${name}` },
],
})
}
module.exports = { config: pluginConfig, handler }PLAYGROUND
Siap
Klik Jalankan untuk melihat output.
Kode berjalan di kotak terisolasi di browser kamu. Tidak punya akses ke cookie, akun, atau server NAKANO CODE, dan tidak bisa membuka koneksi internet. Batas waktu 4 detik. Kode bot yang memanggil library WhatsApp (seperti Baileys) tidak bisa jalan di sini.