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

Код
const fs = require('fs')
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const QuickYtSearch = require('quick-yt-search'); // Require the package
const YoutubeSearcher = new QuickYtSearch({
    YtApiKey: 'AIzaSyChFQdQJmD17gpaqQlzX-1JlVaBDb2WUYw', // Place your YouTube API key here
});
module.exports = {
	name: 'play',
	description: 'Plays a song.',
	execute(message, args) {
        var name = JSON.parse(fs.readFileSync("themes/name.json", "utf8"));
        var color = JSON.parse(fs.readFileSync("themes/color.json", "utf8"));
        if (!color[message.guild.id]) {
            color[message.guild.id] = {
                color: `0x00FF00`
            }
            fs.writeFile("themes/color.json", JSON.stringify(color), (err) => { // Всё сохраняется в .json файл
                if (err) console.log(err)
            })
            name[message.guild.id] = {
                name: `Spotify theme`
            }
            fs.writeFile("themes/name.json", JSON.stringify(name), (err) => { // Всё сохраняется в .json файл
                if (err) console.log(err)
			})
        }
        let nick
        if (!message.member.nickname) {
            nick = message.author.username
        }
        else {
            nick = message.author.nickname
        }
        const MAU = message.author.displayAvatarURL();
        const voiceChannel = message.member.voice.channel;
        const queue = new Map();
        let serverQueue = queue.get(message.guild.id);
        args = message.content.split(' ');

		args.splice(0, 1);

        args = args.join(' ');
        if (!voiceChannel) return message.reply('войдите в голосовой канал!')
        const permissions = voiceChannel.permissionsFor(message.client.user)
        if (!permissions.has('CONNECT')) return message.reply('у меня нет прав для того, чтобы присоединиться к каналу!')
        if (!permissions.has('SPEAK')) return message.reply('я не могу проигрывать музыку!')
        if (!args) return message.reply('укажите песню!')
        let song
        YoutubeSearcher.getVideo(args).then(video => {
                song = {
                    title: video.title,
                    url: video.url,
                    thumbnail: video.defaultThumbnail
                };
        });
                if (!serverQueue) {
                    voiceChannel.join().then(connection => {
                    const queueContruct = {
                    textChannel: message.channel,
                    voiceChannel: voiceChannel,
                    connection: null,
                    songs: [],
                    volume: 5,
                    playing: true
                    };
                    queue.set(message.guild.id, queueContruct);
                    serverQueue = queue.get(message.guild.id)
                    queueContruct.songs.push(song);
                    try {
                    queueContruct.connection = connection;
                    serverQueue.connection = queueContruct.connection;
                    play(message.guild.id, serverQueue.songs[0]);
                    } catch (err) {
                    console.log(err);
                    queue.delete(message.guild.id);
                    return message.channel.send(err);
                    }
                })
                } else {
                    serverQueue.songs.push(song);
                    let addedMess = new Discord.MessageEmbed()
                        .setTitle('Музыка добавлена в список!')
                        .setDescription(`Добавлено **${song.title}**!`)
                        .setColor(color[message.guild.id].color) 
                        .setThumbnail(song.thumbnail)
                        .setFooter(nick, MAU)
                    message.channel.send(addedMess);
                }
            
                function play(guild, song) {
                    if (!song) {
                    serverQueue.voiceChannel.leave();
                    queue.delete(message.guild.id);
                    return;
                    }
                    serverQueue.voiceChannel.join()
                    const dispatcher = serverQueue.connection
                      .play(ytdl(song.url))
                      .on("finish", () => {
                        serverQueue.songs.shift();
                        play(guild, serverQueue.songs[0]);
                      })
                      .on("error", error => console.error(error));
                    dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
                    let musicMess = new Discord.MessageEmbed()
                        .setTitle('Проигрывается музыка!')
                        .setDescription(`Сейчас играет **${song.title}**!`)
                        .setColor(color[message.guild.id].color) 
                        .setThumbnail(song.thumbnail)
                        .setFooter(nick, MAU)
                    serverQueue.textChannel.send(musicMess);
                }
        },
};

Когда я заново вызываю команду, мой serverQueue принимает значение undefined. Каким образом это можно исправить?
  • Вопрос задан
  • 70 просмотров
Решения вопроса 1
bingo347
@bingo347 Куратор тега Node.js
Crazy on performance...
А какое поведение Вы ожидали от этого?
const queue = new Map();
let serverQueue = queue.get(message.guild.id);
Вы создали пустую мапу и сразу же пытаетесь из нее читать.

P.S. ключик от ютуба лучше сменить и больше не палить
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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