This JavaScript code constitutes a functionality used in a bot...

August 24, 2025 at 01:29 PM

case 'otak': { const axios = require('axios'); const cheerio = require('cheerio'); /** * Fetch dengan retry otomatis */ async function fetchWithRetry(url, options = {}, retries = 3) { for (let i = 0; i < retries; i++) { try { return await axios.get(url, options); } catch (err) { if (i === retries - 1) throw err; console.warn(`⚠️ Retry ${i + 1}/${retries} gagal: ${err.message}`); } } } /** * Scraper safelink → ambil direct Pixeldrain */ async function scrapePixeldrainLink(safelinkUrl) { try { // 1. Request halaman safelink const response = await fetchWithRetry( safelinkUrl, { maxRedirects: 5, headers: { "User-Agent": "Mozilla/5.0" }, }, 3 ); // 2. Ambil URL final (fallback ke input kalau ga ada) const finalUrl = response.request?.res?.responseUrl || safelinkUrl; // 3. Ambil isi halaman final const { data: html } = await fetchWithRetry( finalUrl, { headers: { "User-Agent": "Mozilla/5.0" }, }, 3 ); // 4. Load cheerio const $ = cheerio.load(html); // 5. Cari link Pixeldrain (utama: meta, fallback: <a>) let pixeldrainUrl = $('meta[property="og:url"]').attr("content"); if (!pixeldrainUrl) { pixeldrainUrl = $('a[href*="pixeldrain"]').attr("href"); } return pixeldrainUrl || null; } catch (err) { console.error("❌ Error scraping:", err.message); return null; } } // === Eksekusi utama === const input = text?.trim(); if (!input) return m.reply( `Contoh:\n${prefix + command} https://otakudesu.cloud/episode/jsn2025-episode-2-sub-indo/` ); const url = input; const encodedUrl = encodeURIComponent(url); try { const { data } = await axios.get( `https://api.siputzx.my.id/api/anime/otakudesu/download?url=${encodedUrl}`, { timeout: 30000, headers: { 'User-Agent': 'Mozilla/5.0' } } ); if (!data?.status || !data.data?.downloads) return m.reply('❌ Gagal mengambil data episode.'); const preferredQualities = ['360p', '480p', '720p', '1080p']; const pxdlLinks = []; for (const q of preferredQualities) { const found = data.data.downloads.find(dl => dl.quality.toLowerCase().includes(q) ); if (found) { let finalLink = null; if (found.host.toLowerCase() === 'pdrain') { finalLink = found.link; } else if (found.host.toLowerCase().includes('desustream')) { finalLink = await scrapePixeldrainLink(found.link); } if (finalLink && finalLink.includes("pixeldrain")) { pxdlLinks.push({ title: q, description: `Pixeldrain - Direct Link`, id: `.otakudesu ${finalLink}` }); } } } if (!pxdlLinks.length) { return m.reply('❌ Ga ada pixeldrain bang, only pixeldrain.'); } return await conn.sendMessage( m.chat, { text: '📺 Pilih resolusi video yang ingin kamu unduh:', buttons: [ { buttonId: 'resolusi', buttonText: { displayText: '🎞️ Pilih Resolusi Video' }, type: 4, nativeFlowInfo: { name: 'single_select', paramsJson: JSON.stringify({ title: 'Pilih Resolusi Video', sections: [ { title: 'Pixeldrain Available', highlight_label: `Direkomendasikan: ${pxdlLinks[0].title}`, rows: pxdlLinks } ] }) } } ], footer: '© 2025 KrongBotz - Otakudesu', headerType: 1, viewOnce: true, contextInfo: { mentionedJid: [m.sender] } }, { quoted: m } ); } catch (e) { console.error(e); return m.reply(`❌ Terjadi error: ${e.message || 'Gagal fetch data.'}`); } } break

This JavaScript code constitutes a functionality used in a bot (likely for an automated messaging/chat application). Its purpose is to obtain and provide video download links (preferably from Pixeldrain) for episodes of anime hosted on the website Otakudesu. Here’s a detailed step-by-step explanation of what the code does:

1. Define supporting functions:

  • fetchWithRetry(url, options, retries):

    • A helper function that attempts to fetch data from a URL using axios.
    • Implements retry logic, trying up to 3 times (or a specified number of retries) in case of errors.
    • Outputs a warning message to the console if a request fails but retries.
  • scrapePixeldrainLink(safelinkUrl):

    • This function is used to extract Pixeldrain direct download links from a safelink or intermediary page.
    • Steps:
      1. Fetch the safelink page using fetchWithRetry.
      2. Handle any URL redirects to the final page using response.request?.res?.responseUrl.
      3. Parse the HTML content using Cheerio to extract links using specific selectors (e.g., <meta> tags or <a> elements with a Pixeldrain URL).
      4. Return the extracted Pixeldrain link if found, or null otherwise.

2. Main logic:

  • Input validation:

    • The user provides a text input containing a URL (e.g., an episode page from Otakudesu), and the code validates it.
    • If no valid input is provided, a message is sent to guide the user on how to use the command.
  • Fetch download links for the episode:

    • The provided Otakudesu episode URL is sent to a backend API (https://api.siputzx.my.id/api/anime/otakudesu/download), which returns information about available download links.
    • Checks if the API response contains valid and useful data (e.g., for video quality and download links).
  • Filter and prioritize links:

    • The code has a preferred quality order360p, 480p, 720p, and 1080p.
    • For each quality, it iterates through the links provided by the API, looking for preferred hosts:
      • If the host is Pixeldrain (pdrain), the link is directly used.
      • If the host is Desustream (or similar), the scrapePixeldrainLink function is called to attempt to extract Pixeldrain direct links from the intermediary page.
  • Handle Pixeldrain links:

    • Extracted valid Pixeldrain links are added to the pxdlLinks array, which stores information about download quality, a description, and a clickable message.

3. Respond to the user:

  • If no Pixeldrain links are available for the episode, inform the user that only Pixeldrain links are supported.

  • If Pixeldrain links exist, send a message (e.g., via the bot) with buttons allowing the user to select a download resolution:

    • The user receives dynamic buttons corresponding to the available resolutions (360p, 480p, etc.).
    • Clicking a button provides the direct Pixeldrain link for the chosen resolution.
  • Any errors (e.g., with API calls or scraping) are logged to the console, and an appropriate error message is sent to the user.


4. In summary:

The code is a scraping and API-interfacing mechanism:

  • It retrieves download links for anime episodes from Otakudesu pages.
  • It prioritizes fetching Pixeldrain direct links for ease of downloading.
  • It provides the results to the user in an interactive format, allowing them to choose the desired resolution of the episode to download.

This code is likely part of a bot implementation in a messaging platform (e.g., WhatsApp, Telegram, etc.), where the workflow revolves around responding to user commands.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node