首页 > 解决方案 > TypeError:无法读取未定义 Discord.js 的属性“day”

问题描述

我正在编写一个生日不和谐机器人。我已经编写了一个将 bdays 保存在 JSON 文件中的命令。但是当我想阅读它时,会弹出这个错误:TypeError: Cannot read property 'day' of undefined。

如果你有什么想法请告诉我,谢谢:D

我在 youtube 上关注了一个家伙,但他在 main.js 中做这一切

主.js:


const client = new Discord.Client();

const prefix = '?';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);

    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('Bot is online!');
});

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'jsidement') {
        client.commands.get('ping').execute(message, args);
    } else if (command === 'help') {
        client.commands.get('help').execute(message, args, Discord);
    } else if (command === 'mute') {
        client.commands.get('mute').execute(message, args);
    } else if (command === 'unmute') {
        client.commands.get('unmute').execute(message, args);
    }else if(command === 'setbday'){
        client.commands.get('setbday').execute(message, args);
    }else if(command === 'bday'){
        client.commands.get('bday').execute(message, args);
    }
})

client.login('Token');

bday.js:

const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
module.exports = {
    name: 'bday',
    description: 'this is a bday command!',
    execute(message, args){
        client.bdays = require('./bdays.json');

        const target = message.mentions.users.first();
        let _bday = client.bdays[target.id].day;
        message.channel.send ('bday is :' +_bday);
    }
}

这就是 bdays.json 的样子:

{
    "453556418352513025": {
        "day": "16",
        "month": "1",
        "year": "2006",
        "id": "BookOfMonsterman04"
    }
}

标签: javascriptnode.jsdiscord.js

解决方案


您正在尝试将 的内容bdays.json用作数组,而事实并非如此。{}用方括号替换外部


推荐阅读