|
| 1 | +import { Message, MessageMedia } from "whatsapp-web.js"; |
| 2 | +import fs from "fs"; |
| 3 | +import path from "path"; |
| 4 | +import innertube from "../components/innertube"; |
| 5 | +import ytdl from "ytdl-core"; |
| 6 | +import { client } from "../components/client"; |
| 7 | + |
| 8 | +export const command = "play"; |
| 9 | +export const role = "admin"; |
| 10 | + |
| 11 | +// Type guard |
| 12 | +function isVideoNode(node: any): node is { |
| 13 | + type: string; |
| 14 | + video_id: string; |
| 15 | + title: { toString(): string }; |
| 16 | + length_text?: { toString(): string }; |
| 17 | +} { |
| 18 | + return node?.type === "Video" && typeof node.video_id === "string"; |
| 19 | +} |
| 20 | + |
| 21 | +export default async function play(msg: Message) { |
| 22 | + const query = msg.body.replace(/^play\b\s*/i, "").trim(); |
| 23 | + if (!query) { |
| 24 | + await msg.reply("Please provide a search query."); |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + const yt = await innertube(); |
| 29 | + const search = await yt.search(query, { type: "video" }); |
| 30 | + |
| 31 | + const video = search.results.find((node) => isVideoNode(node)); |
| 32 | + if (!video) { |
| 33 | + await msg.reply("Unable to find resources for the given query."); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + const videoId = video.video_id; |
| 38 | + const videoUrl = `https://www.youtube.com/watch?v=${videoId}`; |
| 39 | + const title = video.title.toString(); |
| 40 | + const duration = video.length_text?.toString() || "unknown"; |
| 41 | + |
| 42 | + await msg.reply(`🎵 Downloading audio for *${title}* (${duration})`); |
| 43 | + |
| 44 | + const filePath = path.resolve(__dirname, `../../.temp/audio-${videoId}.webm`); |
| 45 | + const audioStream = ytdl(videoUrl, { |
| 46 | + filter: "audioonly", |
| 47 | + quality: "highestaudio", |
| 48 | + }); |
| 49 | + const writeStream = fs.createWriteStream(filePath); |
| 50 | + audioStream.pipe(writeStream); |
| 51 | + |
| 52 | + await new Promise<void>((resolve, reject) => { |
| 53 | + writeStream.on("finish", resolve); |
| 54 | + writeStream.on("error", reject); |
| 55 | + }); |
| 56 | + |
| 57 | + const audioBuffer = fs.readFileSync(filePath); |
| 58 | + const media = new MessageMedia( |
| 59 | + "audio/webm", |
| 60 | + audioBuffer.toString("base64"), |
| 61 | + `audio-${videoId}.webm` |
| 62 | + ); |
| 63 | + await client.sendMessage(msg.from, media, { |
| 64 | + caption: `🎶 *${title}*`, |
| 65 | + }); |
| 66 | + |
| 67 | + fs.unlinkSync(filePath); |
| 68 | +} |
0 commit comments