Discord Bot | DiscordJS |使用Javascript

时间:2017-10-08 21:41:44

标签: javascript discord

所以我一直在使用Discord.JS库制作Discord bot,但我遇到了一个问题。很确定问题与Javascript和Discord.JS有关,所以我会问这里并希望得到一些帮助。

我有一个名为commandManager.js的文件,它包含我所有的基本命令功能。其中一个是自动加载来自/ commands /文件夹的命令,并根据它们的类别(通过导出在命令中指定)将它们分配给一个数组。

global.userCommands = {};
global.modCommands = {};
global.adminCommands = {};
global.ownerCommands = {};

exports.init = function(bot)
{
    fs.readdir("./commands/", (error, files) =>
    {
        if (error)
        {
            logger.error(error);
        }

        files.forEach(file =>
        {
            let commandFile = require(`../commands/${file}`);
            let commandName = file.split(".")[0];
            if (commandFile.info.category == "User")
            {
                userCommands[commandName] = commandFile;
            }
            else if (commandFile.info.category == "Mod")
            {
                modCommands[commandName] = commandFile;
            }
            else if (commandFile.info.category == "Admin")
            {
                adminCommands[commandName] = commandFile;
            }
            else if (commandFile.info.category == "Owner")
            {
                ownerCommands[commandName] = commandFile;
            }
            else
            {
                logger.warn("Could not add the command " + commandName + " to any of the categories");
            }
        });

        logger.info("Loaded " + files.length + " command(s)");
    });
}

然后在此之后我可以在实际的机器人on on message bit中使用命令,我按照以下方式执行:

exports.run = function(bot, msg)
{   
    const args = msg.content.slice(config.prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
    const cleanCommand = command.slice(config.prefix.length);

    if (msg.author.bot)
    {
        return;
    }   
    else if (msg.content.indexOf(config.prefix) !== 0) 
    {
        return;
    }   
    else if (has.call(userCommands, cleanCommand))
    {
        msg.reply("user");
    }
    else if (has.call(modCommands, cleanCommand))
    {

    }
    else if (has.call(adminCommands, cleanCommand))
    {

    }
    else if (has.call(ownerCommands, cleanCommand))
    {

    }
    else
    {
        msg.reply(`that command does not even exist! You can say ${config.prefix}help for a list of commands!`);
    }
}

所以当我说命令例如“ping”时,它应该回复msg.reply(“user”),但它说它不存在任何东西。我宣称像这样的全球化,你很好奇。

global.has = Object.prototype.hasOwnProperty;

如果你想看到命令,如下:

exports.info =
{
    name: "Ping",
    permission: 10,
    category: "User",
    about: "Makes the bot respond with pong, useful to see if the bot is working."
};

exports.run = function(msg)
{
    msg.channel.send("Pong!");
}

任何提示,参考,示例或只是普通的勺子喂食是100%欢迎。另外,如果您想分享一些更好的技巧来做我正在做的事情,请告诉我,因为我只是JS的初学者。

1 个答案:

答案 0 :(得分:0)

以下是完全基于意见的......

我打赌你也想要使用嵌套命令,例如播放音乐播放视频,所以在我看来,命令树就是这里的方式。因此,也无需解析文件夹中的命令,而是可以拥有更独立的结构。起始文件如下所示:

module.exports = (sub, exit) => ({ 
  //a global handler applied to all commands:
  [sub]:(user)=>"Hi there!",
  //a main exit point ( if a command cannot be found)
  [exit]:{
    run:(user,command)=>"Sorry ${command} doesnt exist"
  },
  //commands
  play: {
    //the following is applied to "play whatever"
    [exit]:{
      desc:"a random command",
      run:(user, ...args) => args.join(" "),
      category:"random"
    },
    //the following is applied to all subcommands
    [sub]:(user)=> user.admin?"start playing":new Error("you must be an admin"),

    //the subcommands
    video:{
      //sub sub commands maybe
      [exit]: {
        info: "to play videos",
        run(user, videoname)=> videoname+".mp4"
      }
   },
   //one can also use require here
   whatever: require("./whatever.js")(sub,exit)
 });

使用此模式可以将代码应用于一大堆命令(通过[sub]),并且可以使用子命令等(通过[exit])运行命令。现在让我们实现路由:

const exit = Symbol("exit"), sub = Symbol("sub");
//requiring the above tree
const routes = require("./commands.js")(exit,sub);
//implementing the router:
function route(tree, user, params ){
  var res;
  //the [sub] implementation
  if( tree[sub] ){
    res = tree[sub]( user, ...params);
    if( res instanceof Error ){
       //if an error applied exit now
       return "An error occured:"+res;
    }
  }

  if( tree[ params[0] ] ){
    return res + "\n" + route( tree[ params[0] , user, params.slice(1) );
  } else {
    return res + " \n" + tree[exit].run(user, params);
  }
}

所以要让它运行:

msg.reply(
  route(
   routes,
   {admin:true, /*...*/ },
   msg.content.split(" ")
 )
);

您仍然可以使用每个类别处理程序等扩展它。