使用ytdl下载后,我在发送文件时遇到麻烦。我注意到这很奇怪,只要我手动为其命名(标题除外),它将成功将文件发送到服务器...否则,它仅将0字节文件发送到我的服务器。我尝试在标题方案上运行各种字符串方法,以为可能是错误的,但这是行不通的。我有一种预感,可能与以下方面有关:
https://github.com/hydrabolt/discord.js/issues/1907

但是,我不知道我一无是处。任何帮助将不胜感激。以下是我的消息来源。发送文件时出现问题的功能是命令==='ytm'

const Discord = require('discord.js');  //need discord.js library of course.
const config = require("./config.json"); //load up the token and prefix from our object configuration file.
const bot = new Discord.Client();  //establishing the bot as the client. "bot" means "client" when looking at the documentation!


bot.on('ready', () => {
  console.log('I am ready!');
});

bot.on('message', message => {

  if(message.author.bot) return; //prevents the bot from reacting to itself.
  if(message.content.indexOf(config.prefix) !== 0) return; //reads out the first character of the message, and if its not our prefix we don't do break away

  const args = message.content.slice(config.prefix.length).trim().split(/ +/g); //setting up to split things into arguments for handling commands, and usage of the prefix
  const command = args.shift().toLowerCase();

  if (command === 'ping') {
    message.channel.send('pong');
    //console.log(args);
    //console.log(command);
  }


  if (command === 'ytm') {
     const fs = require('fs');
     const ytdl = require('ytdl-core');
     url = args[0];
     //console.log(ytdl.getURLVideoID(url));
     //tried to actually work with the "title" information outside of the callback. apparently impossible?
     ytdl.getInfo(url,function(err, info){
         var title = info['title'];
         var length = title.length;
         title = title.substring(0, (length / 3));
         title = title.trim();
         title = './' + title + '.mp3'
         console.log(title);
         //console.log(info['size']);
         ytdl(url, {filter:'audioonly', format:'mp3'}).pipe(fs.createWriteStream(title.toString()));
         message.channel.send("Here's your mp3, boi.", {files:[(title)]});
         //message.channel.sendFile(('./' + title), title, 'Heres your mp3, boi,'); //deprecated?
         })

  }





});

bot.login(config.token);

最佳答案

问题是您试图通过执行title = './' + title + '.mp3'将title变量作为文件明确发送为文件,并将其发送为文件。您的问题是您正在尝试发送视频流而不是视频文件。 ytdl-core是显式用于流式传输视频而不是下载视频的模块。要获取和发送MP3文件,您必须改用youtube-dl(ytdl-core的基础)。文件下载完成后,它将发出一个事件,您可以通过Discord.js发送该事件。

关于javascript - Discord.js();如何发送文件(总是发送一个0字节的文件?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47424406/

10-11 23:15
查看更多