使用discord bot下载

问题描述 投票:0回答:1

我正在制作一个音乐不和谐机器人,可以播放本地目录中的歌曲。我的问题是,我正在尝试创建一个命令,从 youtube 下载歌曲并保存在这个目录中,但是当我使用该命令开始下载时,歌曲文件出现在目录中,但它有 0 字节,而且永远不会结束了。

require('dotenv').config();
const { Client, GatewayIntentBits, Events } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus, getVoiceConnection } = require('@discordjs/voice');
const path = require('path');
const fs = require('fs');
const ytdl = require('ytdl-core');

// Criar cliente do Discord
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildVoiceStates,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
});

// Quando o bot estiver pronto
client.once(Events.ClientReady, () => {
    console.log(`${client.user.tag} está online!`);
});

client.on(Events.MessageCreate, async (message) => {
    if (!message.guild || message.author.bot) return;

    const args = message.content.split(' ');
    const command = args.shift().toLowerCase();

if (message.content.startsWith('!baixarmusica')) {
        const args = message.content.split(' ');
        const url = args[1];

        if (!ytdl.validateURL(url)) {
            return message.channel.send('Por favor, envie um link válido do YouTube.');
        }

        const info = await ytdl.getInfo(url);
        const title = info.videoDetails.title.replace(/[^\w\s]/gi, ''); // Nome do arquivo sem caracteres especiais

        const outputPath = path.resolve(__dirname, 'music', `${title}.mp3`);
        
        message.channel.send(`Baixando: **${title}**...`);

        try {
            // Stream de download e conversão para MP3 usando ffmpeg
            const stream = ytdl(url, { filter: 'audioonly' });

            // Salvando o áudio como arquivo .mp3 na pasta "music"
            const audioFile = fs.createWriteStream(outputPath);

            stream.pipe(audioFile);

            audioFile.on('finish', () => {
                message.channel.send(`Música **${title}** foi baixada e salva na pasta **music**.`);
            });

            audioFile.on('error', (err) => {
                console.error('Erro ao salvar o arquivo:', err);
                message.channel.send('Ocorreu um erro ao baixar a música.');
            });

        } catch (error) {
            console.error('Erro ao baixar a música:', error);
            message.channel.send('Houve um erro ao processar o link do YouTube.');
        }
    }
});

我不知道该尝试什么

discord bots ytdl
1个回答
0
投票

尝试使用 NodeJS 的 youTube-mp3-downloader 模块。您必须有本地 FFmpeg 安装。

var YoutubeMp3Downloader = require("youtube-mp3-downloader");

//Configure YoutubeMp3Downloader with your settings
var YD = new YoutubeMp3Downloader({
    "ffmpegPath": "/path/to/ffmpeg",
    "outputPath": "/path/to/mp3/folder",
    "youtubeVideoQuality": "highestaudio",  // Desired video quality (default: highestaudio)
    "queueParallelism": 2,                  // Download parallelism (default: 1)
    "progressTimeout": 2000,                // Interval in ms for the progress reports (default: 1000)
    "allowWebm": false                      // Enable download from WebM sources (default: false)
});

//Download video and save as MP3 file
YD.download("Video-Id-Here");

YD.on("finished", function(err, data) {
    console.log(JSON.stringify(data));
});

YD.on("error", function(error) {
    console.log(error);
});

YD.on("progress", function(progress) {
    console.log(JSON.stringify(progress));
});

将上述设置替换为您想要的值,并确保将“Video-Id-Here”更改为您想要下载为 MP3 的视频 ID(从 YouTube)。使用此功能时,请确保为用户提供 YouTube 视频的链接,以避免受到版权警告。

© www.soinside.com 2019 - 2024. All rights reserved.