0
votes

I'm trying to get my song bot for discord to let us view a list of queued songs but I am struggling to get a for or a forEach loop working. I am mainly trying to get the loop to work for now and I'll add the right things to get the title and duration to display but if I can get some assistance to get this to work from this error that would be great.

Here is the error

(node:42564) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined at songQueue (C:\Users\Purev\Desktop\Discord Bot\index.js:163:23) at Client. (C:\Users\Purev\Desktop\Discord Bot\index.js:46:5) at Client.emit (events.js:311:20) at MessageCreateAction.handle (C:\Users\Purev\Desktop\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Purev\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (C:\Users\Purev\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31) at WebSocketShard.onPacket (C:\Users\Purev\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:435:22) at WebSocketShard.onMessage (C:\Users\Purev\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10) at WebSocket.onMessage (C:\Users\Purev\Desktop\Discord Bot\node_modules\ws\lib\event-target.js:120:16) at WebSocket.emit (events.js:311:20)

Here is all the code:

    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("VeloBot is running...");
    });

    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 if (message.content.startsWith(`${prefix}pause`)) {
        pause(message, serverQueue)
        return;
      } else if (message.content.startsWith(`${prefix}resume`)) {
        resume(message, serverQueue)
        return;
      } else if (message.content.startsWith(`${prefix}nowplaying`)) {
        nowPlaying(message, serverQueue)
        return;
      } else if (message.content.startsWith(`${prefix}queue`)) {
        songQueue(message, serverQueue)
        return;
      } else if (message.content.startsWith(`${prefix}restart`)) {
        restart(message, serverQueue)
        return;
      }
        else {
        message.channel.send("Hey stupid not a valid command!");
      }
    });

    async function execute(message, serverQueue) {
      const args = message.content.split(" ");

      const voiceChannel = message.member.voice.channel;
      if (!voiceChannel)
        return message.channel.send(
          "Hop in a channel to play music!"
        );
      const permissions = voiceChannel.permissionsFor(message.client.user);
      if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
        return message.channel.send(
          "Yo dawg I need permissions 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: 1,
          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);
        return message.channel.send(`${song.title} has been added to the queue!`);
      }
    }

    function skip(message, serverQueue) {
      if (!message.member.voice.channel)
        return message.channel.send(
          "You have to be in a voice channel to skip the song!"
        );
      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.voice.channel)
        return message.channel.send(
          "You have to be in a voice channel to stop the music!"
        );
      serverQueue.songs = [];
      serverQueue.connection.dispatcher.end();
    }
    function pause(message, serverQueue) {
        if(!message.member.voice.channel)
        return message.channel.send(
            "You have to be in a voice channel to pause the song!"
        );
        if(!serverQueue)
        return message.channel.send("There is no song to pause!"
        );
        serverQueue.connection.dispatcher.pause();
    }
    function resume(message, serverQueue) {
        if(!message.member.voice.channel)
        return message.channel.send(
            "You have to be in a voice channel to resume the song!"
        );
        if(!serverQueue)
        return message.channel.send("There is no song to resumme!"
        );
        serverQueue.connection.dispatcher.resume();
    }
    function nowPlaying(message, serverQueue) {
        if(!serverQueue)
        return message.channel.send("There is no song that is playing!"
        );
        return message.channel.send(`Now playing: ${serverQueue.songs[0].title}`);

    }
    function songQueue(message, serverQueue) {
        if(!message.member.voice.channel)
        return message.channel.send(
            "You have to be in a channel to view the Queue!"
        );
        if(!serverQueue)
        return message.channel.send("There is no song playing!"
        );
        var queueOutput;
        var count = 1;
        serverQueue.array.forEach(entry =>{
          queueOutput = queueOutput + count + "." + entry + "\n";
          count++;
        });
        message.channel.send(queueOutput);
    }

    function restart(message, serverQueue) {
          message.channel.send("VeloBot restarting..."
          );
           serverQueue.voiceChannel.leave();
           process.exit();
    }

    function play(guild, song) {
      const serverQueue = queue.get(guild.id);
      if (!song) {
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
      }

      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);
      serverQueue.textChannel.send(`Started playing: **${song.title}**`);
     }

    client.login(token);
    ```


1
Cannot read property 'forEach' of undefined. You have a forEach function made with an array equals anything. See your forEach function in index.js at line 163.Corentin de Maupeou
Please provide a minimal, complete and verifiable example stackoverflow.com/help/mcve - currently your code is too long. Have you tried debugging your code? Given you have an undefined error, it seems likely that a variable is not being assigned correctly.Philip Eagles
does .array in serverQueue.array exist? did you try serverQueue.forEach() instead?Syntle
@Syntle I tried serverQueue.forEach() and it tells me serverQueue.forEach is not a function.MisterVelo
Console log serverQueue and post the results on hastebin or pastebinSyntle

1 Answers

0
votes

Change songQueue.array.forEach(...) to songQueue.songs.forEach(...). You've defined it as songQueue.songs, yet you've been trying to use songQueue.array!