gohellp
@gohellp
Громкое "Ы" из темноты

Почему бот не воспроизводит аудио после подключения и выдаёт ошибку?

При запуске бота всё нормально, но стоит заказать песню, как он выдаёт ошибку
The "file" argument must be of type string. Received an instance of Object
и завершает свою работу. FFMPEG переустанавливал, качал стандарт, бинариес - ничего не помогло. В коде уверен, да и пробовал преобразование типа переменной в ctring - тот же результат. На стаке, гитхабе и тд смотрел ветки - ничего дельного не нашёл. Так же пробовал заведомо рабочий код из обучалок по созданию муз ботов.

const Discord = require('discord.js');
const {
    prefix,
    token,
} = require('./config.json');
const ytdl = require('ytdl-core');
const client = new Discord.Client();
const queue = new Map();

client.once('ready', () => {
    console.log('Ready!');
});
client.once('reconnecting', () => {
    console.log('Reconnecting!');
});
client.once('disconnect', () => {
    console.log('Disconnect!');
});
client.on('message', async message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;
    const serverQueue = queue.get(message.guild.id);
    if (message.content.startsWith(`${prefix}play`)) {
        execute(message, serverQueue);
        return;
    } else if (message.content.startsWith(`${prefix}skip`)) {
        skip(message, serverQueue);
        return;
    } else if (message.content.startsWith(`${prefix}stop`)) {
        stop(message, serverQueue);
        return;
    } else {
        message.channel.send('You need to enter a valid command!')
    }
});
async function execute(message, serverQueue) {
    const args = message.content.split(' ');
    const voiceChannel = message.member.voiceChannel;
    if (!voiceChannel) return message.channel.send('You need to be in a voice channel to play music!');
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
        return message.channel.send('I need the permissions to join and speak in your voice channel!');
    }
    const songInfo = await ytdl.getInfo(args[1]);
    const song = {
        title: songInfo.title,
        url: songInfo.video_url,
    };
    if (!serverQueue) {
        const queueContruct = {
            textChannel: message.channel,
            voiceChannel: voiceChannel,
            connection: null,
            songs: [],
            volume: 5,
            playing: true,
        };
        queue.set(message.guild.id, queueContruct);
        queueContruct.songs.push(song);
        try {
            var connection = await voiceChannel.join();
            queueContruct.connection = connection;
            play(message.guild, queueContruct.songs[0]);
        } catch (err) {
            console.log(err);
            queue.delete(message.guild.id);
            return message.channel.send(err);
        }
    } else {
        serverQueue.songs.push(song);
        console.log(serverQueue.songs);
        return message.channel.send(`${song.title} has been added to the queue!`);
    }
}
function skip(message, serverQueue) {
    if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
    if (!serverQueue) return message.channel.send('There is no song that I could skip!');
    serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
    if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
    serverQueue.songs = [];
    serverQueue.connection.dispatcher.end();
}
function play(guild, song) {
    const serverQueue = queue.get(guild.id);
    if (!song) {
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
    }
    const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
        .on('end', () => {
            console.log('Music ended!');
            serverQueue.songs.shift();
            play(guild, serverQueue.songs[0]);
        })
        .on('error', error => {
            console.error(error);
        });
    dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}
client.login(token);
  • Вопрос задан
  • 1605 просмотров
Решения вопроса 1
Alexandre888
@Alexandre888 Куратор тега discord.js
Javascript-разработчик
с первого взгляда сложно сказать, в чём именно проблема.
вы копировали код отсюда, верно?
насколько я понял, этот код для старой версии discord.js, и я не советую вам его использовать.
в нём много запутанных моментов, в целом он написан достаточно плохо.
попробуйте сделать простое подключение и проигрывание мелодии, и, если всё пройдёт гладко - проблема была в том коде (в противном случае, дело в FFMPEG'e).
bot.on("message", async message => {
const dispatcher = connection.play('audio.mp3');

dispatcher.on('start', () => {
	message.channel.send('audio.mp3 проигрывается!');
});

dispatcher.on('finish', () => {
	message.channel.send('audio.mp3 остановлено!');
});

dispatcher.on('error', console.error);
})
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы