2017-10-08 8 views
0

그래서 Discord.JS 라이브러리를 사용하여 Discord 봇에서 작업 중이며 문제가 발생했습니다. 확실히 문제는 Javascript 대 Discord.JS와 더 관련이 있습니다. 그래서 여기에서 물어보고 도움이되기를 바랍니다.불화 봇 | 불일치 | Javascript

모든 기본 명령 기능을 보유하고있는 commandManager.js라는 파일이 있습니다. 그 중 하나는/commands/폴더에서 명령을 자동로드하고 범주를 기반으로 어레이에 지정합니다 (내보내기를 통해 명령에 지정됨). 내가 명령 예를 들어, "핑"는 회신해야한다고 그래서

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!`); 
    } 
} 

을 :

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)"); 
    }); 
} 

다음이 후 나는 다음과 같은 한 메시지 비트의 실제 로봇에 명령을 사용할 수 있습니다 msg.reply ("사용자") 대신에 그것이 존재하지 않는다고 말합니다. 나는 당신이 호기심이 많았을 때 이것을 세계에 알렸다.

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와 초보자 인 것처럼 알려주십시오. 다음

+0

왜'userCommands [cleanCommand]'?? 카테고리는 무엇에 좋은가? –

+1

글쎄, 카테고리는 나중에 명령 목록을 작성해야한다면 그들을 구분하기위한 아이디어입니다. 그리고 왜 당신에게 정직하지 않을지 확신하지 못합니다. 그런 다음 카테고리에 대한 더 나은 아이디어 또는 내가 대신 동일한 결과를 얻으려면 무엇을 할 수 있습니까? –

답변

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(" ") 
) 
); 

당신은 여전히 ​​카테고리 핸들러 등 당과 그 확장 할 수