V
V
VELAND2020-06-12 15:03:40
JavaScript
VELAND, 2020-06-12 15:03:40

Why does Undefined occur when accessing a JSON file?

An error occurs

C:\Users\V3land\Desktop\999\index.js:42
      "name": `[UNMUTE] ${member.user.tag}`,
                                 ^

TypeError: Cannot read property 'user' of undefined
    at Timeout._onTimeout (C:\Users\V3land\Desktop\999\index.js:42:34)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

The error occurs when the function is initialized via Interval in the index file, which in turn consists of the following code:
const fs = require('fs');

const Discord = require('discord.js');
const bot = new Discord.Client({ disableEveryone: true });

const credentials = require("./credentials");
const prefix = credentials.prefix;

bot.commands = new Discord.Collection();

bot.muted = require('./muted.json');
try{
fs.readdir('./cmds/', (err, files) => {
    if (err) console.error(err);
    const jsFiles = files.filter(f => f.split('.').pop() === 'js');
    if (jsFiles.length <= 0) return console.log('No command files found!');
    jsFiles.forEach((f, i) => {
        const props = require(`./cmds/${f}`);
        console.log(`${i + 1}: ${f} loaded!`);
        bot.commands.set(props.help.name, props);
    });
})

bot.on('ready', async () => {
    console.log(`${bot.user.username} is ready!`);

    // Проверка истечения срока мутов каждые 60 секунд
    bot.setInterval(() => {
        for (const i in bot.muted) {
            const time = bot.muted[i].time;
            const guildId = bot.muted[i].guild;
            const guild = bot.guilds.get(guildId);
            const member = guild.members.get(i);
            const mutedRole = guild.roles.find(mR => mR.name === 'Muted');
            if (!mutedRole) continue;

            if (Date.now() > time) {
                 // Логирование  
 const embed = {
    "color": 13450239,
    "author": {
      "name": `[UNMUTE] ${member.user.tag}`,
      "icon_url": `${member.user.displayAvatarURL}`
    },
    "fields": [
      {
        "name": "Пользователь",
        "value": `${member.user}`,
        "inline": true
      },
      {
        "name": "Модератор",
        "value": `${bot.user}`,
        "inline": true
      },
      {
        "name": "Причина",
        "value": `Окончание срока мута`
      }
    ]
  }
  bot.channels.get('656496416847560724').send({embed});
                member.removeRole(mutedRole);
                delete bot.muted[i];
                fs.writeFile('./muted.json', JSON.stringify(bot.muted), err => {
                    if(err) throw err;
                });
            }
        }
    }, 60000);
});

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

    const messageArray = message.content.split(' ');
    const command = messageArray[0];
    const args = messageArray.slice(1);

    if (!command.startsWith(prefix)) return;

    const cmd = bot.commands.get(command.slice(prefix.length));
    if (cmd){
    message.delete();
    cmd.run(bot, message, args); }
});
} catch(err){
  console.log(err);
}
// Проверка заполнености токена в Credentials
if(credentials.token === '') return console.log('Token is empty!');
bot.login(credentials.token);


JSON file has the following structure:
{

    "501044794920009728": {
        "guild": "608610149569134619",
        "time": 1591920815930
    },
    "678601812831371285": {
        "guild": "608610149569134619",
        "time": 1591920881556
    },
    "259415136584859649": {
        "guild": "608610149569134619",
        "time": 1591971348807
    },
    "474096751335178240": {
        "guild": "608610149569134619",
        "time": 1591942561971
    },
    "428579239051264012": {
        "guild": "608610149569134619",
        "time": 1591942616913
    },
    "307486316931579905": {
        "guild": "608610149569134619",
        "time": 1591942640520
    },
    "437315666182275074": {
        "guild": "608610149569134619",
        "time": 1591921107918
    },
    "310775392640434176": {
        "guild": "608610149569134619",
        "time": 1591921114628
    },
    "644491828569178124": {
        "guild": "608610149569134619",
        "time": 1591921132484
    },
    "278054122299719680": {
        "guild": "608610149569134619",
        "time": 1591921158443
    },
    "284522016780845056": {
        "guild": "608610149569134619",
        "time": 1591921178490
    },
    "338391991870029826": {
        "guild": "608610149569134619",
        "time": 1591931994238
    },
    "278935951823339521": {
        "guild": "608610149569134619",
        "time": 1591921214019
    },
    "697349792468303892": {
        "guild": "608610149569134619",
        "time": 1591921218703
    },
    "289058087942488064": {
        "guild": "608610149569134619",
        "time": 1591924844518
    },
    "417718243046981660": {
        "guild": "608610149569134619",
        "time": 1591921309845
    },
    "564199174946553886": {
        "guild": "608610149569134619",
        "time": 1591921327227
    },
    "369516454610993152": {
        "guild": "608610149569134619",
        "time": 1591942967350
    },
    "268097873885790208": {
        "guild": "608610149569134619",
        "time": 1591921379255
    },
    "242405386479468544": {
        "guild": "608610149569134619",
        "time": 1591921385532
    },
    "644841947726348301": {
        "guild": "608610149569134619",
        "time": 1591921510593
    },
    "541119064290885632": {
        "guild": "608610149569134619",
        "time": 1591921528960
    },
    "314067762408456202": {
        "guild": "608610149569134619",
        "time": 1591928768192
    },
    "556468808978530306": {
        "guild": "608610149569134619",
        "time": 1591921569402
    }
}

At the same time, the error does not occur immediately, but after the number of lines in the JSON file starts to exceed ~ 1.000 lines, before that everything works more than normally.
Once all Muted.json elements have been cleared, work is back to normal.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-12
@VELAND

It is obvious that for some element the line
const member = guild.members.get(i);
returns undefined
Put a breakpoint with a condition in this place and look at which element. It is obvious that somewhere guild.members has fewer elements than in the bot.muted array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question