Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { Module } = require("../main");
- const config = require("../config");
- const { setVar } = require("./manage");
- const { downloadGram } = require("./utils");
- const {
- getVideoInfo,
- downloadVideo,
- downloadAudio,
- convertM4aToMp3,
- } = require("./utils/yt");
- const fs = require("fs");
- const fromMe = false;
- // temp yt quality store
- const YT_SELECTIONS = {};
- const HANDLER_PREFIX =
- config.HANDLERS === "false"
- ? ""
- : (config.HANDLERS || ".").charAt(0);
- const URL_PATTERNS = {
- instagram:
- /^https?:\/\/(?:www\.)?instagram\.com\/(?:p\/[A-Za-z0-9_-]+\/?|reel\/[A-Za-z0-9_-]+\/?|tv\/[A-Za-z0-9_-]+\/?|stories\/[A-Za-z0-9_.-]+\/\d+\/?)(?:\?.*)?$/i,
- youtube:
- /^https?:\/\/(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/[A-Za-z0-9_-]+\/?)|youtu\.be\/)([A-Za-z0-9_-]{11})?(?:[\?&].*)?$/i,
- };
- function getAllUrls(text) {
- if (!text) return [];
- const urlMatches = text.match(/https?:\/\/\S+/gi);
- if (!urlMatches) return [];
- return urlMatches.map((url) =>
- url.replace(/[)\]\.,!?>]*$/, "")
- );
- }
- function detectPlatform(url) {
- for (const [platform, re] of Object.entries(URL_PATTERNS)) {
- if (re.test(url)) return platform;
- }
- return null;
- }
- function isAlreadyCommand(text) {
- text = text?.toLowerCase()?.trim();
- if (!text) return false;
- return /(insta\s|ytv\s|yta\s|play\s|instagram\s|youtube\s)/i.test(
- text
- );
- }
- function formatBytes(bytes) {
- if (bytes === 0) return "0 B";
- const k = 1024;
- const sizes = ["B", "KB", "MB", "GB"];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return (
- Math.round((bytes / Math.pow(k, i)) * 100) / 100 +
- " " +
- sizes[i]
- );
- }
- // ========================================
- // NUMBER REPLY HANDLER
- // ========================================
- Module({ on: "text", fromMe }, async (message) => {
- try {
- const text = message.text?.trim();
- if (!/^\d+$/.test(text)) return;
- if (!message.reply_message) return;
- const repliedText =
- message.reply_message?.text ||
- message.reply_message?.message ||
- "";
- if (!repliedText.includes("Select Video Quality")) return;
- const selection = parseInt(text);
- const data = YT_SELECTIONS[message.jid];
- if (!data) {
- return await message.sendReply(
- "_Session expired. Send YouTube link again._"
- );
- }
- const { url, info, qualities } = data;
- // audio
- if (selection === qualities.length + 1) {
- let audioPath;
- const msg = await message.sendReply(
- "_Downloading audio..._"
- );
- try {
- const result = await downloadAudio(url);
- audioPath = result.path;
- const mp3Path = await convertM4aToMp3(audioPath, {
- title: result?.title,
- artist: result?.info?.channel?.name,
- thumbnail: result?.info?.thumbnail,
- });
- audioPath = mp3Path;
- const stream = fs.createReadStream(audioPath);
- await message.sendMessage(
- { stream },
- "audio",
- {
- mimetype: "audio/mpeg",
- fileName: `${result.title}.mp3`,
- }
- );
- stream.destroy();
- await message.edit(
- "_Download complete!_",
- message.jid,
- msg.key
- );
- if (fs.existsSync(audioPath)) {
- fs.unlinkSync(audioPath);
- }
- } catch (err) {
- console.log(err);
- await message.edit(
- "_Download failed!_",
- message.jid,
- msg.key
- );
- if (audioPath && fs.existsSync(audioPath)) {
- fs.unlinkSync(audioPath);
- }
- }
- return;
- }
- const quality = qualities[selection - 1];
- if (!quality) {
- return await message.sendReply("_Invalid selection!_");
- }
- const msg = await message.sendReply(
- `_Downloading ${quality} video..._`
- );
- try {
- const result = await downloadVideo(url, quality);
- await message.sendMessage(
- { url: result.path || result.url },
- "video",
- {
- caption: `_*${info.title}*_`,
- }
- );
- await message.edit(
- "_Download complete!_",
- message.jid,
- msg.key
- );
- if (result.path && fs.existsSync(result.path)) {
- fs.unlinkSync(result.path);
- }
- } catch (err) {
- console.log(err);
- await message.edit(
- "_Download failed!_",
- message.jid,
- msg.key
- );
- }
- } catch (err) {
- console.log(err);
- }
- });
- // ========================================
- // MAIN AUTODL
- // ========================================
- Module({ on: "text", fromMe }, async (message) => {
- try {
- if (message.fromBot) return;
- const chatJid = message.jid;
- const isGroup = chatJid.includes("@g.us");
- const autodlEnabledForChat = (() => {
- try {
- const enabledList = config.AUTODL || "";
- const enabled = enabledList
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean);
- if (enabled.includes(chatJid)) return true;
- if (isGroup && config.AUTODL_ALL_GROUPS === "true")
- return true;
- if (!isGroup && config.AUTODL_ALL_DMS === "true")
- return true;
- return false;
- } catch (e) {
- return false;
- }
- })();
- if (!autodlEnabledForChat) return;
- let text = message.text || "";
- if (isAlreadyCommand(text)) return;
- const urls = getAllUrls(text);
- if (!urls.length) return;
- const platformGroups = {};
- for (const url of urls) {
- const platform = detectPlatform(url);
- if (!platform) continue;
- if (!platformGroups[platform]) {
- platformGroups[platform] = [];
- }
- platformGroups[platform].push(url);
- }
- if (!Object.keys(platformGroups).length) return;
- await message.react("⬇️");
- // ========================================
- // YOUTUBE
- // ========================================
- if (platformGroups["youtube"]) {
- let url = platformGroups["youtube"][0];
- try {
- if (url.includes("youtube.com/shorts/")) {
- const shortId = url.match(
- /youtube\.com\/shorts\/([A-Za-z0-9_-]+)/
- )?.[1];
- if (shortId) {
- url = `https://www.youtube.com/watch?v=${shortId}`;
- }
- }
- const info = await getVideoInfo(url);
- const videoFormats = info.formats
- .filter((f) => f.type === "video" && f.quality)
- .sort((a, b) => {
- const getRes = (q) => {
- const match = q.match(/(\d+)/);
- return match ? parseInt(match[1]) : 0;
- };
- return getRes(b.quality) - getRes(a.quality);
- });
- const uniqueQualities = [
- ...new Set(videoFormats.map((f) => f.quality)),
- ];
- if (!uniqueQualities.length) {
- await message.react("❌");
- return;
- }
- // store selections
- YT_SELECTIONS[message.jid] = {
- url,
- info,
- qualities: uniqueQualities,
- };
- let qualityText = `_*${info.title}*_\n\n`;
- qualityText += "_Select Video Quality:_\n\n";
- uniqueQualities.forEach((quality, index) => {
- const format = videoFormats.find(
- (f) => f.quality === quality
- );
- let sizeInfo = "";
- if (format?.size) {
- const match = format.size.match(
- /([\d.]+)\s*(KB|MB|GB)/i
- );
- if (match) {
- const value = parseFloat(match[1]);
- const unit = match[2].toUpperCase();
- let bytes = value;
- if (unit === "KB") bytes *= 1024;
- if (unit === "MB") bytes *= 1024 * 1024;
- if (unit === "GB") bytes *= 1024 * 1024 * 1024;
- sizeInfo = ` ~ _${formatBytes(bytes)}_`;
- }
- }
- qualityText += `*${index + 1}.* _${quality}_${sizeInfo}\n`;
- });
- qualityText += `*${
- uniqueQualities.length + 1
- }.* _Audio MP3_\n`;
- qualityText += "\n_Reply with number to download_";
- await message.sendReply(qualityText);
- } catch (err) {
- console.log(err);
- await message.react("❌");
- }
- return;
- }
- // ========================================
- // INSTAGRAM
- // ========================================
- if (platformGroups["instagram"]) {
- try {
- const allMediaUrls = [];
- const quotedMessage = message.reply_message
- ? message.quoted
- : message.data;
- for (const url of platformGroups["instagram"]) {
- try {
- const result = await downloadGram(url);
- if (result && result.length) {
- allMediaUrls.push(...result);
- }
- } catch (err) {
- console.log(err);
- }
- }
- if (!allMediaUrls.length) {
- await message.react("❌");
- return;
- }
- if (allMediaUrls.length === 1) {
- const media = allMediaUrls[0];
- await message.sendMessage(
- { url: media },
- /\.(jpg|jpeg|png|webp|heic)(\?|$)/i.test(media)
- ? "image"
- : "video",
- {
- quoted: quotedMessage,
- }
- );
- return;
- }
- const albumObject = allMediaUrls.map((mediaUrl) => {
- return /\.(jpg|jpeg|png|webp|heic)(\?|$)/i.test(
- mediaUrl
- )
- ? { image: mediaUrl }
- : { video: mediaUrl };
- });
- await message.client.albumMessage(
- message.jid,
- albumObject,
- message.data
- );
- } catch (err) {
- console.log(err);
- await message.react("❌");
- }
- return;
- }
- } catch (err) {
- console.log(err);
- }
- });
- // ========================================
- // AUTODL SETTINGS
- // ========================================
- Module(
- {
- pattern: "autold ?(.*)",
- fromMe: false,
- desc: "Auto-download manager",
- },
- async (message, match) => {
- const input = match[1]?.trim();
- const chatJid = message.jid;
- const readList = () => {
- try {
- const list = config.AUTODL || "";
- return list
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean);
- } catch (e) {
- return [];
- }
- };
- if (!input) {
- return await message.sendReply(
- `*_⬇️ AutoDownload Manager_*\n\n` +
- `- \`${HANDLER_PREFIX}autodl on\`\n` +
- `- \`${HANDLER_PREFIX}autodl off\`\n` +
- `- \`${HANDLER_PREFIX}autodl status\``
- );
- }
- const parts = input.split(" ");
- const cmd = parts[0]?.toLowerCase();
- const target = parts[1]?.toLowerCase();
- if (cmd === "on") {
- if (target === "groups") {
- await setVar("AUTODL_ALL_GROUPS", "true");
- return await message.sendReply(
- "_AutoDL enabled for all groups ✅_"
- );
- }
- if (target === "dms") {
- await setVar("AUTODL_ALL_DMS", "true");
- return await message.sendReply(
- "_AutoDL enabled for all DMs ✅_"
- );
- }
- const enabledList = readList();
- if (!enabledList.includes(chatJid)) {
- enabledList.push(chatJid);
- }
- await setVar("AUTODL", enabledList.join(","));
- return await message.sendReply(
- "_AutoDL enabled in this chat ✅_"
- );
- }
- if (cmd === "off") {
- if (target === "groups") {
- await setVar("AUTODL_ALL_GROUPS", "false");
- return await message.sendReply(
- "_AutoDL disabled for all groups ❌_"
- );
- }
- if (target === "dms") {
- await setVar("AUTODL_ALL_DMS", "false");
- return await message.sendReply(
- "_AutoDL disabled for all DMs ❌_"
- );
- }
- const enabledList = readList().filter(
- (x) => x !== chatJid
- );
- await setVar("AUTODL", enabledList.join(","));
- return await message.sendReply(
- "_AutoDL disabled in this chat ❌_"
- );
- }
- if (cmd === "status") {
- const enabledList = readList();
- return await message.sendReply(
- `*_AutoDL Status_*\n\n` +
- `• _Enabled chats:_ ${
- enabledList.length
- ? enabledList.join(", ")
- : "None"
- }`
- );
- }
- return await message.sendReply(
- `Unknown option: ${cmd}`
- );
- }
- );
Add Comment
Please, Sign In to add comment