Error with discord bot

Hello.
I was coding my bot when this appeard:


Here’s the NitroClient.js code:

global.Promise = require("bluebird");

// Modules
const os = require("os");
const EventEmitter = require("events");

// Framework
const Discord = require("discord.js");
const CommandLoader = require("./CommandLoader");
const ConsistentTimer = require("./ConsistentTimer");
const Database = require("./Database");
const MusicPlayer = require("./MusicPlayer");
const Image = require("./Image");
const Enum = require("./Enum");
const Logger = require("./Logger");
const config = require("../config");

// Load all extensions
const Ex = require("../Extensions");
Ex.ShardClientUtil.extend(Discord.ShardClientUtil);
Ex.MessageEmbed.extend(Discord.MessageEmbed);
Ex.GuildChannel.extend(Discord.GuildChannel);

class NitroClient extends Discord.Client {

    constructor(...args) {
        super(...args);

        this.db = new Database();
        this.modlog = new EventEmitter();
        this.CommandLoader = new CommandLoader();
        this.Embed = Discord.MessageEmbed;
        this.conTimers = new ConsistentTimer(this);
        this.isBeta = config.BETA;

        this.SimpleStorage = {
            guild: {},
            channel: {},
            user: {},
            system: {}
        };

        this.initTime = Date.now();
        this._unhandledRejection();
        this.once("ready", () => {
            this.conTimers.restartTimers();
            // MUSIC IS DISABLED FOR NOW (lavalink not needed as such)
            if (!config.DIS_MUSIC) this.player = new MusicPlayer(this);
            logger.info("Bot online.")
            this.updateStats();
            this.user.setActivity("n!help");
        })

    }

    updateStats() {
        this.stats = this.botStats();
        setInterval(() => this.stats = this.botStats(), 10000);
    }

    botStats() {
        return {
            guildCount: this.guilds.size,
            channelCount: this.channels.size,
            userCount: this.users.size,
            cpuUsage: os.loadavg()[1],
            memUsage: process.memoryUsage().rss / 1024 / 1024,
        };
    }

    async init() {
        await this.db.formatDb();
        await Image.loadFiles();
        this.commands = this.CommandLoader.load()
        this.login(config.TOKEN);
    }

    _unhandledRejection() {
        //Log all uncaught exceptions
        process.on("unhandledRejection", (e) => logger.err(e))
    }

    get embed() {
        return new Discord.MessageEmbed()
    }
}

module.exports = NitroClient;

What’s happening?


MOD EDIT: formatting

1 Like

I think you might be using fancy quotes,
Can you try using this instead!

global.Promise = require("bluebird");
// Modules
const os = require("os");
const EventEmitter = require("events");
// Framework
const Discord = require("discord.js");
const CommandLoader = require("./CommandLoader");
const ConsistentTimer = require("./ConsistentTimer");
const Database = require("./Database");
const MusicPlayer = require("./MusicPlayer");
const Image = require("./Image");
const Enum = require("./Enum");
const Logger = require("./Logger");
const config = require("…/config");
// Load all extensions
const Ex = require("…/Extensions");
Ex.ShardClientUtil.extend(Discord.ShardClientUtil);
Ex.MessageEmbed.extend(Discord.MessageEmbed);
Ex.GuildChannel.extend(Discord.GuildChannel);
class NitroClient extends Discord.Client {
constructor(args) {
super(args);
  this.db = new Database();
   this.modlog = new EventEmitter();
   this.CommandLoader = new CommandLoader();
   this.Embed = Discord.MessageEmbed;
   this.conTimers = new ConsistentTimer(this);
   this.isBeta = config.BETA;

   this.SimpleStorage = {
       guild: {},
       channel: {},
       user: {},
       system: {}
   };

  this.initTime = Date.now();
   this._unhandledRejection();
   this.once("ready", () => {
       this.conTimers.restartTimers();
       // MUSIC IS DISABLED FOR NOW (lavalink not needed as such)
       if (!config.DIS_MUSIC) this.player = new MusicPlayer(this);
       Logger.info("Bot online.")
       this.updateStats();
       this.user.setActivity("n!help");
   })

}
updateStats() {
this.stats = this.botStats();
setInterval(() => this.stats = this.botStats(), 10000);
}
botStats() {
return {
guildCount: this.guilds.size,
channelCount: this.channels.size,
userCount: this.users.size,
cpuUsage: os.loadavg()[1],
memUsage: process.memoryUsage().rss / 1024 / 1024,
};
}
async init() {
await this.db.formatDb();
await Image.loadFiles();
this.commands = this.CommandLoader.load()
this.login(config.TOKEN);
}
_unhandledRejection() {
//Log all uncaught exceptions
process.on("unhandledRejection", (e) => Logger.err(e))
}
get embed() { return new Discord.MessageEmbed() }
}
module.exports = NitroClient;


Still not working… :confused:

1 Like

Hey @TheBigerGamer the only thing I see that might be problematic in the code is the trailing , at the end of the botStats() method, but in fact I wouldn’t expect that to cause a problem. It might be more helpful if we can look at your code within the project, if you’re willing to share your project name.

1 Like

Of course. The project name is: warlock-gaming-bot.

1 Like

Your project is set to private, meaning no-one can see your code to help you.

I looked at your error for a bit, it looks like the error might be originating from MusicPlayer.js. I’m assuming you copied and pasted the code. If so, just check that you didn’t add an extra ; by accident. Please send the code from MusicPlayer.js or feel free to DM me an invite link.

1 Like

Here is the code of MusicPlayer.js:

const {
    LAVALINK_NODES,
    LAVALINK
} = require("../config");
const {
    PlayerManager,
    Player
} = require("discord.js-lavalink");
const {
    shuffleArray,
    pullProps
} = require("./util");
const Paginator = require("./Paginator");
const snekfetch = require("snekfetch");
const Duration = require("duration-js");

class MusicPlayer {


    async get(channel) {
        const {
            guild,
            id
        } = channel;
        let player = this.guilds[guild.id];
        if (player) return player;

        player = new GuildPlayer(await this.createPlayer(channel), channel)
        return this.guilds[guild.id] = player;
    }

    check(channel) {
        let player = this.guilds[channel.guild.id];
        if (player) return player;
        else return false;
    }

    kill(guild) {
        const player = this.guilds[guild.id];
        if (!player) return;
        this.manager.leave(guild.id);
        this.guilds[guild.id] = undefined;
    }

    async createPlayer(channel) {
        return this.manager.join({
            channel: channel.id,
            guild: channel.guild.id,
            host: "localhost"
        }, {
            selfmute: true
        });
    }

    constructor(bot) {
        this.bot = bot;
        this.manager = new PlayerManager(bot, LAVALINK_NODES, {
            user: bot.user.id,
            shards: 1
        })
    }
}

class GuildPlayer {
    player;
    guild; // The guild this player is attached to.
    channel;
    client;
    _broadcastChannel;

    playlist = [];

    isPlaying = false;
    currentTrack;
    loopPlaylist = false;

    dj;
    // Commands

    async playLink(query) {
        let tracks = await loadTracks(query);
        for (let i = 0; i < tracks.length; i++) {
            tracks[i] = this.formatTrack(tracks[i]);
            this.queueTrack(tracks[i]);
        }
        return tracks;
    }

    async playSearch(query) {
        let track = await loadTracks(query, true);
        track = this.formatTrack(track);
        this.queueTrack(track);
        return track;
    }

    async search(query) {
        const tracks = await loadTracks(query);
        for (let i = 0; i < tracks.length; i++) {
            tracks[i] = this.formatTrack(tracks[i]);
        }
        return tracks;
    }

    skip() {
        if (!this.isPlaying) return;
        this.playNext();
    }

    skipto(to) {
        if (!this.isPlaying) return;
        for (let i = 0; i < to - 1; i++) {
            let sk = this.playlist.shift();
            if (!sk) return this.kill();
            if (this.loopPlaylist) this.playlist.push(sk);
        }
        this.playNext();
    }

    pause() {
        if (!this.isPlaying) return;
        this.player.pause();
    }

    unpause() {
        if (!this.isPlaying) return;
        this.player.pause(false);
    }

    seek(to) {
        if (!this.isPlaying) return;
        if (this.playlist[0].seekable) return;
        this.player.seek(to);
    }

    volume(vol) {
        if (!this.isPlaying) return;
        this.player.volume(vol);
    }

    loop() {
        this.loopPlaylist = !this.loadPlaylist;
    }

    // Track playing

    playNext() {
        const next = this.playlist.shift();
        if (!next) return this.kill();

        if (this.loopPlaylist) this.playlist.push(next);

        this.isPlaying = true;
        this.currentTrack = next;
        this.player.play(next.code);

        const {
            author,
            title
        } = next;
        this.broadcast(`Now playing ${title} uploaded by ${author}`);
    }

    queueTrack(track) {
        if (this.playlist.length < 600)
            this.playlist.push(track);

        if (!this.isPlaying) this.playNext();
    }

    formatTrack(track) {
        const {
            info
        } = track;
        return {
            code: track.track,
            title: info.title,
            author: info.author,
            length: info.length,
            seekable: info.isSeekable,
            url: info.uri
        }
    }

    onPlayerEnd(data) {
        if (data.reason === "REPLACED") return;
        if (this.playlist.length < 1) {
            this.broadcast("You've run out of tunes, queue up some more!");
            this.kill();
        }
        this.playNext();
    }

    onPlayerError(error) {
        this.kill();
        console.log(error);
    }

    setBroadcast(channel) {
        this._broadcastChannel = channel;
    }

    broadcast(msg) {
        if (!this._broadcastChannel) return;
        this._broadcastChannel.send(`**:musical_note: | ${msg}**`);
    }

    setDJ(id) {
        this.dj = id;
    }

    isDJ(id, channel) {
        if (id === this.dj) return true;
        const perms = channel.permissionsFor(id);
        if (perms.has("MANAGE_MESSAGES") || perms.has("MANAGE_GUILD")) return true;
        return false;
    }

    kill() {
        this.isPlaying = false;
        this.playlist = [];

        this.player.stop();

        this.client.player.kill(this.guild);
    }

    // Playlist handling

    playlistInfo(page = 1) {
        if (!this.isPlaying) return;
        if (!this.currentTrack) return;

        let tracks = [];
        const pages = new Paginator(this.playlist, 20);
        pages.loopPage(page, (item, i) => {
            tracks.push({
                title: item.title,
                author: item.author,
                url: item.url,
                length: new Duration(item.length),
                index: i
            });
        })
        const pageCount = pages.pageCount;
        let totalLength = this.playlist.reduce((a, b) => ({
            length: a.length + b.length
        })).length;
        totalLength = new Duration(totalLength);
        const nowPlaying = pullProps(this.currentTrack, ["title", "author", "length", "url"]);
        nowPlaying.length = new Duration(nowPlaying.length);

        return {
            tracks,
            totalLength,
            nowPlaying,
            pageCount
        };
    }

    shufflePlaylist() {
        if (!this.isPlaying) return;
        this.playlist = shuffleArray(this.playlist);
    }

    async loadPlaylist(urls) {
        let playlist = [];
        for (let i = 0; i < urls.length; i++) {
            let track = await loadTracks(urls[i]);
            track = this.formatTrack(track);
            playlist.push(track);
        }
        this.playlist = playlist;
        this.playNext();
    }

    savePlaylist() {
        let saved = [];
        for (let i = 0; i < this.playlist.length; i++) {
            saved.push(this.playlist[i].url);
        }
        return saved;
    }

    constructor(player, channel, _broadcastChannel) {
        this.guild = channel.guild;
        this.channel = channel;
        this.client = channel.client;
        this.player = player;
        this._broadcastChannel = _broadcastChannel;

        player.on("error", this.onPlayerError.bind(this));
        player.on("end", this.onPlayerEnd.bind(this));
    }
}

async function loadTracks(query, firstResultOnly = false) {
    const res = await snekfetch.get(`http://localhost:2334/loadtracks?identifier=${query}`)
        .set("Authorization", LAVALINK);
    if (!res || !res.body || !res.body.length) throw "No tracks found."
    return firstResultOnly ? res.body[0] : res.body;
}

module.exports = MusicPlayer;

MOD EDIT: formatting

1 Like

Hey @TheBigerGamer I think you might be running into a Node version problem - instance class fields like you have defined in your GuildPlayer class (these things:

    player;
    guild; // The guild this player is attached to.
    channel;
    client;
    _broadcastChannel;

) aren’t supported by default in any of the Node versions available on Glitch at the moment. You can see what node versions Glitch supports here and where instance class fields are supported here. These things will get easier when Node 12 is released (and once it’s added to Glitch)

You can probably get this working with a couple of changes:

  • change your Node version to something > 9.
  "engines": {
    "node": "10.x"
  }

ought to work.

  • call node with the --harmony flag with this change:
"scripts": {
    "start": "node --harmony start.js"
  }

With those two changes I think you’ll be able to get past the Unexpected token errors (although I haven’t actually tested it).

Hope this helps!

1 Like

OK. I’ve done what you said. and now I’m getting this error:

EDIT: OK, now I’m getting this error:

@cori, can you take a look please?

1 Like

Hello @TheBigerGamer,

Can you go to your projects console and type in the following commands in this order!

rm shrinkwrap.yaml
enable-pnpm

and tell me if this helps with your new error!
If this does not help then let me know and I will see what else we can do!

Nope. Still the same error.

1 Like

Can you invite me to your project so I can take a closer look!

Problem has been resolved, you seem to have another error which is unrelated.

I solved the problem by removing all your dependencies, and installed them one by one, until I got the error, the module was “Sharp”, so I lowered the version of sharp to “0.18.1” and then installed your other dependencies and that fixed all your problems except for an unrelated problem with a coding error you have!

1 Like

OK. So I have to install al the other dependecies. And what code error I have?

1 Like

I have installed all your other dependencies!
The only problem you have now is this:

    Structures.extend(struct.name, s => struct);

               ^


TypeError: Cannot read property 'extend' of undefined

OK. But I don’t see them in my project.
I’m installing them right now.

1 Like

It is in your logs.Can you show me what you see there!

1 Like

Yes, that is the error I am talking about.

OK. But there is a problem: I don’t have any idea how to solve what’s causing the error.
Because Structures is defined.

Here is extend.js code:

const { Structures } = require(“discord.js”);

function extend(struct) {
Structures.extend(struct.name, s => struct);
}

module.exports = extend;

@Callum-OKane, can you please help me (again)

1 Like