Discord.js Music Bot in a command handler

2019-08-19 09:30发布

问题:

I want to make a music bot in my command handler, but I ran into some problems. This is the command handler I use:

delete require.cache[require.resolve(`./commands/${command}.js`)];

let commandFile = require(`./commands/${command}.js`);
commandFile.run(client, message, args);

And in my play.js file I have a queue:

var servers = {};

I don't know how to make it so that I can skip a song (using the skip command - skip.js) in the queue. Code for skipping:

if (server.dispatcher) server.dispatcher.end();

I tried looking at tutorials but they all do it in one file wich makes it easier because you can just put the "var servers = {};" on the top and its going to work. I couldn't find any tutorials where they shown how to make it so that you can use a command handler like mine.

Here are all the files:

play.js - https://hastebin.com/dijavugufu.js

skip.js - https://hastebin.com/kupecayotu.js

It would also be nice if someone told me how to modify some other music bot commands to work with a command handler.

回答1:

Hey man not sure if you're still looking for an answer but I'm also working on a bot with a command handler. The way I got around this was to export the skip function directly from the play file and use that function in the skip file. Here's kinda what I did.

/*In play.js*/
var dispatcher;
async function Play(connection, message){
    dispatcher = await connection.playStream("your url and options here");
}
module.exports.Skip = function(){
    if(dispatcher) dispatcher.end();
}

/*In skip.js*/
const playModule = require("your_path_to/play.js");
module.exports.run = async (client, message, args) => {
    var skip = playModule.Skip();
}

Sorry, I'm still pretty new to Node.js and creating a Discord bot and this may not be the most elegant solution. But the main point is that I got around it by writing the function in play.js and exporting that function to skip.js and calling it there.