@saidanyx

Почему возникает ошибка в музыкальном боте?

У меня есть музыкальный бот, написанный на Discord.js. Когда я ввожу поисковый запрос, поначалу всё работает, музыка находится, начинает играть. Но в среднем через 6-10 минут бот крашится с ошибкой, которую я укажу ниже. Я уже гуглил, задавал вопросы gpt, но безрезультатно.

Ошибка:
Ошибка плеера: AudioPlayerError: write ECONNABORTED
    at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:95:16)
    at handleWriteReq (node:internal/stream_base_commons:59:21)
    at writeGeneric (node:internal/stream_base_commons:150:15)
    at Socket._writeGeneric (node:net:953:11)
    at Socket._write (node:net:965:8)
    at doWrite (node:internal/streams/writable:590:12)
    at clearBuffer (node:internal/streams/writable:774:7)
    at Writable.uncork (node:internal/streams/writable:523:7)
    at ClientRequest._flushOutput (node:_http_outgoing:1177:10)
    at ClientRequest._flush (node:_http_outgoing:1146:22) {
  resource: AudioResource {
    playStream: OggDemuxer {
      _events: [Object],
      _readableState: [ReadableState],
      _writableState: [WritableState],
      allowHalfOpen: true,
      _maxListeners: undefined,
      _eventsCount: 5,
      _remainder: null,
      _head: null,
      _bitstream: null,
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: [Function: bound onwrite]
    },
    edges: [ [Object], [Object] ],
    metadata: null,
    volume: undefined,
    encoder: undefined,
    audioPlayer: AudioPlayer {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _state: [Object],
      subscribers: [Array],
      behaviors: [Object],
      debug: [Function (anonymous)],
      [Symbol(shapeMode)]: false,
      [Symbol(kCapture)]: false
    },
    playbackDuration: 586740,
    started: true,
    silencePaddingFrames: 5,
    silenceRemaining: -1
  }
}

Код:
const {
    Client,
    GatewayIntentBits,
    SlashCommandBuilder,
    REST,
    Routes
} = require('discord.js');
const {
    joinVoiceChannel,
    createAudioPlayer,
    createAudioResource,
    AudioPlayerStatus,
    VoiceConnectionStatus,
    getVoiceConnection
} = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const YouTube = require('simple-youtube-api');
const {
    generateDependencyReport
} = require('@discordjs/voice');
const OpusScript = require('opusscript');
console.log(generateDependencyReport());
const sodium = require('libsodium-wrappers');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildVoiceStates
    ]
});

const youtube = new YouTube('');

const commands = [
    new SlashCommandBuilder()
    .setName('play')
    .setDescription('Проигрывает музыкальный трек из YouTube')
    .addStringOption(option =>
        option.setName('query')
        .setDescription('Поисковый запрос')
        .setRequired(true))
].map(command => command.toJSON());

const rest = new REST({
    version: '9'
}).setToken('');

(async () => {
    try {
        console.log('Начинаю обновление (/) команд.');

        await rest.put(
            Routes.applicationCommands(''), {
                body: commands
            },
        );

        console.log('Успешно зарегистрировал (/)-команды.');
    } catch (error) {
        console.error('Ошибка при регистрации команд:', error);
    }
})();

client.on('ready', () => {
    console.log(`Вошёл в систему как ${client.user.tag}!`);
});

async function searchYouTube(query) {
    const searchResults = await youtube.searchVideos(query, 1).catch(console.error);
    if (searchResults.length === 0) {
        return [];
    }

    return [{
        title: searchResults[0].title,
        url: `https://www.youtube.com/watch?v=${searchResults[0].id}`
    }];
}

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;

    const {
        commandName
    } = interaction;

    if (commandName === 'play') {
        try {
            await interaction.deferReply();

            const voiceChannel = interaction.member.voice.channel;
            if (!voiceChannel) {
                await interaction.editReply('Пожалуйста, присоединитесь к голосовому каналу, чтобы использовать эту команду.');
                return;
            }

            const searchQuery = interaction.options.getString('query');
            console.log(`Поисковый запрос: ${searchQuery}`);

            const videos = await searchYouTube(searchQuery);
            if (videos.length === 0) {
                await interaction.editReply('Не удалось найти видео по вашему запросу.');
                return;
            }

            console.log(`Найденное видео: ${videos[0].title}, URL: ${videos[0].url}`);

            const connection = joinVoiceChannel({
                channelId: voiceChannel.id,
                guildId: voiceChannel.guild.id,
                adapterCreator: voiceChannel.guild.voiceAdapterCreator,
            });

            connection.on(VoiceConnectionStatus.Ready, () => {
                console.log('Бот присоединился к голосовому каналу.');
            });

            connection.on(VoiceConnectionStatus.Disconnected, () => {
                console.log('Соединение разорвано и уничтожено.');
                connection.destroy();
            });

            function play(resource, player, connection) {
                player.play(resource);
                connection.subscribe(player);

                player.on('error', async error => {
                    console.error('Ошибка плеера:', error);
                    if (!interaction.replied) {
                        await interaction.editReply('Произошла ошибка при воспроизведении музыки. Повторная попытка.');
                    }

                    const newStream = ytdl(videos[0].url, {
                        filter: 'audioonly'
                    });
                    const newResource = createAudioResource(newStream);
                    play(newResource, player, connection);
                });

                player.on(AudioPlayerStatus.Idle, async () => {
                    if (!interaction.replied) {
                        await interaction.editReply('Воспроизведение музыки завершено.');
                    }
                    connection.disconnect();
                    connection.destroy();
                });

                player.on(AudioPlayerStatus.Playing, () => {
                    console.log('Музыка играет.');
                });
            }

            const stream = ytdl(videos[0].url, {
                filter: 'audioonly'
            });
            const resource = createAudioResource(stream);
            const player = createAudioPlayer();

            await interaction.editReply(`Воспроизведение: ${videos[0].title}`);

            play(resource, player, connection);

        } catch (error) {
            console.error('Ошибка при обработке команды:', error);
            await interaction.editReply('Произошла ошибка')
        }

    }
})

client.login("");
  • Вопрос задан
  • 56 просмотров
Пригласить эксперта
Ваш ответ на вопрос

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

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