i getting error Cannot read property 'channels' of undefined - javascript

I'm getting an error Cannot read property 'channels' of undefined
(node:2632) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'channels' of undefined
at updateMembers (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:5:31)
at module.exports (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:13:5)
at Client. (C:\Users\Asus\Desktop\Episode 50\index.js:48:5)
at Object.onceWrapper (events.js:421:28)
at Client.emit (events.js:315:20)
at WebSocketManager.triggerClientReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard. (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
Here is my code:
module.exports = (client) => {
const membercountchannel = '811119579580465182'
const updateMembers = (guild) => {
const channel = guild.channels.cache.get(membercountchannel)
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('787083837833871400')
updateMembers(guild)
}

If you check the stack trace, you can see that your updateMembers function receives a guild that is undefined (member-count.js:5:31). On the next line you can see that it's coming from the last line (member-count.js:13:5): updateMembers(guild).
As you define guild one line above, it means client.guilds.cache.get('787083837833871400') returns undefined. Make sure the guild ID is correct. If it is correct, you can try to fetch the guild instead.
One more thing, you should never add event handlers inside event handlers. I think you're already in client.on('message'). Every time someone's using your command to update the member count, you create two new event listeners (client.on('guildMemberAdd') and client.on('guildMemberRemove')) and it will cause issues (memory leaks). You need to handle these somewhere else, outside of your commands.
module.exports = async (client) => {
const updateMembers = (guild) => {
const memberCountChannel = '811119579580465182';
const channel = guild.channels.cache.get(memberCountChannel);
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`);
};
try {
const guild = await client.guilds.fetch('787083837833871400');
updateMembers(guild);
} catch (error) {
console.log(error);
}
};

Related

events `messageUpdate` and `messageDelete` doesn't "work" after bot restart

Well, events messageUpdate and messageDelete doesn't "work" after restarting the bot
I mean, they don't respond to messages that were sent before the restart
I added MESSAGE to partials
Now the events works, but there is a problem with the if (newMessage.author.bot) return and if (message.author.bot) return and generally with message|newMessage.author|member etc.
Here are the error:
TypeError: Cannot read properties of null (reading 'bot')
at module.exports.run (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\events\messageDelete.js:14:28)
at Slodziak.<anonymous> (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\aslodziak.js:40:43)
at Slodziak.emit (node:events:527:28)
at Slodziak.emit (node:domain:475:12)
at MessageDeleteAction.handle (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\actions\MessageDelete.js:24:16)
at Object.module.exports [as MESSAGE_DELETE] (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_DELETE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketManager.js:346:31) at WebSocketShard.onPacket (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:478:22)
at WebSocketShard.onMessage (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:317:10)
at WebSocket.onMessage (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\ws\lib\event-target.js:199:18)
Can someone help? I need these partials MESSAGE to messageUpdate because the bot did not respond to messages that were sent after restart. More specifically, to the automod, i.e. that it deletes invitations if someone has edited the message and has no permissions
messageUpdate
module.exports = class {
constructor(client) {
this.client = client;
}
async run(oldMessage, newMessage) {
const data = {};
const client = this.client;
data.config = client.config;
if (newMessage.author.bot) return;
if (!newMessage.editedAt) return;
code that deleted invites if member has not permissions
}
};
messageDelete
module.exports = class {
constructor(client) {
this.client = client;
}
async run(message) {
const data = {};
const client = this.client;
data.config = client.config;
if (message.author.bot) return;
Code that snipes deleted message
}
}
The error means that newMessage.author is null. You already knew that you would need to use the MESSAGE partials.
The problem is that you don't check if the received message is a partial only.
A partial message will not contain all of the original Message parameters. The id, the channelId, and the guildId will be present, but others, like author, can be null.
To solve this, you'll need to check if your message is partial only, and if it is, you can fetch it and use it as usual:
module.exports = class {
constructor(client) {
this.client = client;
}
async run(oldMessage, newMessage) {
const data = {};
const client = this.client;
data.config = client.config;
if (oldMessage.partial) oldMessage = await oldMessage.fetch();
if (newMessage.partial) newMessage = await newMessage.fetch();
if (newMessage.author.bot) return;
if (!newMessage.editedAt) return;
// code that deleted invites if the member has no permissions
}
};

I get this error: TypeError: Cannot read properties of undefined (reading 'members') whenever I execute command

const levels = require('discord-xp')
const { MessageEmbed } = require('discord.js')
const client = require('../../index')
module.exports = {
name: "edit",
description: "Edits a users level or xp",
usage: ".edit <user> [xp / level] [add / set / remove] <number>",
developersOnly: true,
run: async (message, args, client) => {
const usage = ".edit <user> [xp / level] [add / set / remove] <number>"
if (!args[0]) return message.channel.send(`> You need to state more arguments \`${usage}\``)
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
if (!['xp', 'level'].includes(args[1])) return message.channel.send(`> You did not specify if you are changing level or xp: \`${usage}\``)
if (args[1] === "xp") {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s xp to \`${value}\``)
} catch (err) {
console.log(err)
}
}
} else if (args[1] === 'level') {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s level to \`${value}\``)
} catch (err) {
console.log(err)
}
}
}
}
}
This is supposed to be a level and xp edit command for my bots leveling system
i tested it on my self first but it didnt seem to work and i dont think theres any errors in my code. It send this super long error:
TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10) Promise {
<rejected> TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10)
}
so like can someone help me?
(if you need any more info about code say it in comment ill reply with the info there)
Whenever you see this error, check the line 'reading members'(in your case). That simply means you are doing a key access where keyname is 'members' and object inside which this key 'members' is present is undefined. For example X.members where X is undefined.So check in your code why this 'X'(imaginary name given for the sake of answer could be any name that you only know) is undefined or what could make that 'X' undefined. And after finding that you should put a check before doing the access i.e something like below to avoid these run time errors:
if(X) then X.members
OR
X?.members
Looking at your code the error is coming from here :
const mentionedMember = message.mentions.members.first()
Keep this line in correct place i.e all your access to mentionedMember should occur after this line and then change above line to :
const mentionedMember = message.mentions?.members.first() provided members has first() method. If you are not sure then you can do like this also const mentionedMember = message.?mentions?.members?.first()
There is one more way which is not cleaner but it's fine:
let mentionedMember;
if(message && message.mentions && message.mentions.members) {
mentionedMember = message.mentions.members.first()
}
In this line code:
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
Try to arrange this like:
const mentionedMember = message.mentions.members.first()
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
In line:
if (!mentionedMember) return message.channel.send('> Mention a valid user / member.'); you already calling the mentionedMember which is its not readable.
Let me know if the error still there after you rearrange your code

This discord bot that greets people when they join my server won't work?

I am trying to make a welcoming message to whoever joins my discord server with this bot, but nothing happens when someone joins. I am getting an error:
ReferenceError: channelname is not defined
at C:\Users\Vir\Desktop\DiscBot\index.js:13:71
at Map.find (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\util\Collection.js:506:11)
at Client. (C:\Users\Vir\Desktop\DiscBot\index.js:13:43)
at Client.emit (events.js:223:5)
at Guild._addMember (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\structures\Guild.js:1298:19)
at GuildMemberAddHandler.handle (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\client\websocket\packets\handlers\GuildMemberAdd.js:12:13)
at WebSocketPacketManager.handle (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
at WebSocketConnection.onPacket (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\Vir\Desktop\DiscBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\Vir\Desktop\DiscBot\node_modules\ws\lib\event-target.js:120:16)
PS C:\Users\Vir\Desktop\DiscBot>
But I have no clue what that means. I've tried searching it up and found nothing.
The code is
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = "NzEzMTcwNjc4NjYwMjAyNTA2.XscOxQ.0YxwpbBEITN0DIwGFwYIdRxCOu0";
const PREFIX = ";";
bot.on('ready', () =>{
console.log('This bot is online!');
})
bot.on('guildMemberAdd', member =>{
const channel = member.guild.channels.find(channel => channelname === "welcome");
if(!channel) return;
channel.send('Welcome, ${member}, make sure to read the rules and verfiy.')
});
bot.on('message', message=>{
let args = message.content.substring(PREFIX.length).split(" ")
switch(args[0]){
case 'Version':
message.reply('Version 1.0.0');
break;
case 'Commands':
message.reply(';Version ;Commands');
break;
}
})
bot.login(token);
This is the code that i use for this
client.on("guildMemberAdd", (member) => {
const channel = member.guild.channels.cache.get('CHANNEL_ID');
channel.send(`**Hey ${member.user}, welcome to the server!\nMake sure to read the rules in <#CHANNEL_ID>**`);
});
They have changed it, so you'll need to use cache now. So in this case:
bot.on('guildMemberAdd', member =>{
const channel = member.guild.channels.cache.find(channel => channel.name === "welcome");
if(!channel) return;
channel.send('Welcome, ${member}, make sure to read the rules and verfiy.')
});
Hope this helps!
The error suggests that channelname is not defined. I believe you should be using channel.name instead, just a simple typo.
Following OP's comment, I checked the docs and you must access the cache property to get a list of channels, like so:
bot.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(channel => channel.name === "welcome");
if(!channel) {
return;
}
channel.send(`Welcome, ${member}, make sure to read the rules and verfiy.`)
});

TypeError: value.split is not a function

I'm creating a discord.js bot v12 and I get this error on line 2 when I use the purge command in discord and I'm assuming value.split is not a function and wondering if I should be doing something else since I'm using v12 of discord.js:
Uncaught Promise Error:
TypeError: args.split is not a function or its return value is not iterable
at Object.module.exports.run (c:\Users\Kazzu\Desktop\src\commands\prune.js:2:34)
at module.exports (c:\Users\Kazzu\Desktop\src\events\message.js:33:9)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Kazzu\Desktop\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
This is my code:
module.exports.run = async (client, message, args) => {
let [ userId, limit ] = args.split(/\s+/);
if(!userId && !limit) {
let deletedMessages = await message.channel.bulkDelete();
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
if(!userId || !limit) return message.channel.send('Please provide the correct arguments.');
let r = new RegExp(/^\d+$/);
if(!r.test(userId)) return message.channel.send('Please provide a valid user id.');
if(isNaN(limit)) return message.channel.send('Please provide a numeric value for limit');
if(limit > 100) return message.channel.send('Limit must be less than or equal to 100.');
try {
let fetchedMessages = await message.channel.messages.fetch({ limit });
let filteredMessages = fetchedMessages.filter(message => message.author.id === userId);
let deletedMessages = await message.channel.bulkDelete(filteredMessages);
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
catch(err) {
console.log(err);
}
}
module.exports.help = {
name: "purge",
description: "Deletes a number of messages from a user in a channel."
}
module.exports.requirements = {
userPerms: [],
clientPerms: [],
ownerOnly: false
}
It seems that args is not type of string. When you call .split() for something other than a string, JavaScript runtime cannot find the .split() method for that type. So, make sure you are passing a string to your function or try something like that:
if (typeof string === args) {
var str = args.toString();
}
Turns out I needed to replace value.split to value.slice

When checking invites is the following

If I create a new express invitation to the server when the bot is turned on, an error occurs. In other cases, it works
const invites = {};
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
wait(1000);
g.fetchInvites().then(guildInvites => {
invites[g.id] = guildInvites;
});
});
});
client.on('guildMemberAdd', member => {
member.guild.fetchInvites().then(guildInvites => {
const ei = invites[member.guild.id];
invites[member.guild.id] = guildInvites;
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
const inviter = client.users.get(invite.inviter.id);
const logChannel = member.guild.channels.find(channel => channel.name === "join-logs");
logChannel.send(`${member.user.tag} joined using invite code ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
});
});
Errors:
2019-07-07T09:49:20.363359+00:00 app[worker.1]: Unhandled Rejection:
2019-07-07T09:49:20.363377+00:00 app[worker.1]: TypeError: Cannot read property 'uses' of undefined
2019-07-07T09:49:20.363378+00:00 app[worker.1]: at guildInvites.find.i (./bot.js:398:57)
2019-07-07T09:49:20.363380+00:00 app[worker.1]: at Map.find (./node_modules/discord.js/src/util/Collection.js:160:13)
2019-07-07T09:49:20.363381+00:00 app[worker.1]: at member.guild.fetchInvites.then.guildInvites (./bot.js:398:33)
2019-07-07T09:49:20.363382+00:00 app[worker.1]: at process._tickCallback (internal/process/next_tick.js:68:7)
398 deadline
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
The invite used is new, and isn't yet in the cache. However, ei.get(i.code).uses assumes it is, and tries to use a property of it when it doesn't exist.
This revised predicate function will return the invite that isn't cached, or the invite that increased in uses.
const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);

Categories

Resources