K
K
Kirill2020-12-13 21:29:56
Node.js
Kirill, 2020-12-13 21:29:56

Why is the array reset when the command is called again?

The code
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);
                }
        },
};

When I call the command again, my serverQueue is set to undefined . How can this be corrected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-12-14
@KIRIK12

What behavior did you expect from this?

const queue = new Map();
let serverQueue = queue.get(message.guild.id);
You have created an empty map and immediately try to read from it.
PS It's better to change the YouTube key and stop firing again

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question