I have this small problem where I get the Cannot read properties of undefined error, but I don't know where the issue is. Can someone help me with this one?
Here is the code:
const { Client } = require("discord.js");
const DB = require("../Structures/Schemas/LockDown");
/**
* @param {Client} client
*/
module.exports = async(client) => {
DB.find().then(async (documentsArray) => {
documentsArray.forEach(async (d) => {
const Channel = client.guilds.cache
.get(d.GuildId)
.channels.cache.get(d.ChannelID);
if(!Channel) return;
const TimeNow = Date.now();
if(d.Time < TimeNow){
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
return await DB.deleteOne({ ChannelID: Channel.id });
}
const ExpireDate = d.time - Date.now();
setTimeout(async () => {
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
await DB.deleteOne({ ChannelID: Channel.id });
}, ExpireDate);
});
});
};
and here is the error I get:
TypeError: Cannot read properties of undefined (reading 'channels')
There is a chance that not all channels and guilds are added to the cache. Try fetching them first and then see. For example, something like this should work:
const { Client } = require('discord.js');
const DB = require('../Structures/Schemas/LockDown');
/**
* @param {Client} client
*/
module.exports = async(client) => {
DB.find().then(async(documentsArray) => {
documentsArray.forEach(async(d) => {
const GuildChannel = await client.guilds.fetch(d.GuildId);
const Channel = await GuildChannel.channels.fetch(d.ChannelID);
if (!Channel) return;
const TimeNow = Date.now();
if (d.Time < TimeNow) {
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
return await DB.deleteOne({
ChannelID: Channel.id
});
}
const ExpireDate = d.time - Date.now();
setTimeout(async() => {
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
await DB.deleteOne({
ChannelID: Channel.id
});
}, ExpireDate);
});
});
};
Instead of fetching the guild and then the channel, directly fetch the channel from the client like so:
const { Client } = require('discord.js');
const DB = require('../Structures/Schemas/LockDown');
/**
* @param {Client} client
*/
module.exports = async(client) => {
DB.find().then(async(documentsArray) => {
documentsArray.forEach(async(d) => {
const Channel = await client.channels.fetch(d.ChannelID);
if (!Channel) return;
const TimeNow = Date.now();
if (d.Time < TimeNow) {
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
return await DB.deleteOne({
ChannelID: Channel.id
});
}
const ExpireDate = d.time - Date.now();
setTimeout(async() => {
Channel.permissionOverwrites.edit(d.GuildID, {
SEND_MESSAGES: null,
});
await DB.deleteOne({
ChannelID: Channel.id
});
}, ExpireDate);
});
});
};
Or, as @Malik Lahlou said, it could be a typo.
Hoped this helped!