discord.js TypeError:无法读取未定义的属性“name”

时间:2018-03-31 16:01:39

标签: javascript discord discord.js

const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();

fs.readdir("./commands/", (err, files) => {

  if(err) console.log(err);

  let jsfile = files.filter(f => f.split(".").pop() === "js")
  if(jsfile.length <= 0){
    console.log("Couldn't find commands.");
    return;
  }

  jsfile.forEach((f, i) =>{
    let props = require(`./commands/${f}`);
    console.log(`${f} loaded!`);
    bot.commands.set(props.help.name, props);
  });

});


bot.on("ready", async () => {
  console.log(`${bot.user.username} is online on ${bot.guilds.size} servers!`);

  bot.user.setActivity("!help | website.xyz", {type: "WATCHING"});

  //bot.user.setGame("on SourceCade!");
});

bot.on("message", async message => {
  if(message.author.bot) return;
  if(message.channel.type === "dm") return;

  let prefix = botconfig.prefix;
  let messageArray = message.content.split(" ");
  let cmd = messageArray[0];
  let args = messageArray.slice(1);

  let commandfile = bot.commands.get(cmd.slice(prefix.length));
  if(commandfile) commandfile.run(bot,message,args);

});

bot.login(tokenfile.token);

这是我的索引文件夹,当我尝试运行bot时出现此错误。我已经尝试了所有的东西,但我不是最好的,因为我还在学习,所以任何帮助都将不胜感激!谢谢

C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:21
    bot.commands.set(props.help.name, props);
                                ^

TypeError: Cannot read property 'name' of undefined
    at jsfile.forEach (C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:21:33)
    at Array.forEach (<anonymous>)
    at fs.readdir (C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:18:10)
    at FSReqWrap.oncomplete (fs.js:135:15)
[nodemon] app crashed - waiting for file changes before starting...

3 个答案:

答案 0 :(得分:1)

您的命令处理程序没有

exports.conf = {
  aliases: ['Stuff', 'AlsoStuff']
  };
  exports.help = {
  name: "More Stuff", description: "SillyStuff.", usage: ".SeriousStuff"
  }

这就是您返回名称未找到错误的原因。因为在它看起来的代码中,它并不存在。

答案 1 :(得分:0)

props.help存在问题,因为它返回undefined(关键字&#34;帮助&#34;在道具中不存在),因为错误状态。您可能应该确切地检查您分配给道具的内容。

答案 2 :(得分:0)

当您访问某个属性的属性时,您应该添加第一个属性的检查。

您的props.helpundefinedundefined不是Javascript对象,未定义的name属性查找将失败。

如果您尝试查找undefined的属性,您将获得TypeEror

Object.getOwnPropertyNames(undefined)
// prints 'Uncaught TypeError: Cannot convert undefined or null to object'

特别是因为您正在读取多个文件并访问这些文件中的字段,所以应该注意文件格式不正确,文件读取不正确等情况。

&#13;
&#13;
jsfile.forEach((f, i) =>{
  let props = require(`./commands/${f}`);
  console.log(`${f} loaded!`);
  if (props.help && props.help.name) {
    bot.commands.set(props.help.name, props);
  } else {
    console.error(`file ${f} does not have .help or .help.name property!`);
});
&#13;
&#13;
&#13;