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

时间:2019-10-13 23:07:57

标签: discord.js

我遇到了这个问题:TypeError:添加别名后,无法在我的Discord机器人上读取未定义的属性“ forEach”。在向其添加别名之前,此方法已奏效,因此我假设问题就在附近。我似乎找不到问题的根源,因此不胜感激!

代码:

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

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);
        props.help.aliases.forEach(alias => {
            bot.aliases.set(alias, props.help.name);
        });
    });
});



bot.on("ready", async () => {
    console.log(`${bot.user.username} is online`);
    bot.user.setActivity("$ Made by xkillerx15");
});

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)) || bot.commands.get(cmd.slice(prefix.length));
    if(commandfile) commandfile.run(bot,message,args);

    if(!profile[message.author.id]){
        profile[message.author.id] = {
            coins: 0
        };
    }

    let coinAmt = Math.floor(Math.random() * 15) + 1;
    let baseAmt = Math.floor(Math.random() * 15) + 1;
    if(coinAmt === baseAmt){
        profile[message.author.id] = {
            coins: profile[message.author.id].coins + coinAmt
        };
        fs.writeFile("./profiles.json", JSON.stringify(profile), (err) => {
            if(err) console.log(err)
        });
    }
});

bot.login(botconfig.token);

确切错误:

TypeError: Cannot read property 'forEach' of undefined
    at jsfile.forEach (C:\Users\Jordy\Desktop\jbot\index.js:23:28)
    at Array.forEach (<anonymous>)
    at fs.readdir (C:\Users\Jordy\Desktop\jbot\index.js:19:12)
    at FSReqWrap.args [as oncomplete] (fs.js:140:20)

1 个答案:

答案 0 :(得分:0)

您的问题是aliasesundefined,这意味着它不是对象,因此您不能使用forEach

有一种可能性:

  1. 命令文件应在aliases对象中包含help。 所以应该是这样

    exports.help = {
    aliases:[...props]
    }