Cannot read property 'members' of undefined error - discord.js

I try to check something and I get an error:
TypeError: Cannot read property 'members' of undefined
The code:
module.exports= {
name: 'roles',
description: "roles",
execute(client, message, args){
let roleID = "754739387295858828";
let membersWithRole = message.guild.roles.cache.get('754739387295858828').members;
console.log('sda');
}
}

Make sure the guild has a role with the provided id before getting the member property.
module.exports = {
name: 'roles',
description: "roles",
execute(client, message, args){
let roleID = "754739387295858828";
let role = message.guild.roles.cache.get(roleID);
if (role) console.log(`${role.members} member has the role ${role.name}`);
else console.log(`There's no role with the id ${roleID}`);
}
}

Related

DISCORD BOT : `TypeError: Cannot read properties of undefined (reading 'permission')`

Its been a while since I programmed the Permissions Handler which all the perms will be handled each command. So I'm using Discord.Js v14 and it seems that this Permission handling is "deprecated"??? I really don't know so the error is TypeError: Cannot read properties of undefined (reading 'permission')
and here is my code
const ValidPerms = [
p.AddReactions,
p.Administrator,
p.AttachFiles,
p.BanMembers,
p.ChangeNickname,
p.Connect,
p.CreateInstantInvite,
p.CreatePrivateThreads,
p.CreatePublicThreads,
p.DeafenMembers,
p.EmbedLinks,
p.KickMembers,
p.ManageChannels,
p.ManageEmojisAndStickers,
p.ManageEvents,
p.ManageGuild,
p.ManageMessages,
p.ManageNicknames,
p.ManageRoles,
p.ManageThreads,
p.ManageWebhooks,
p.MentionEveryone,
p.ModerateMembers,
p.MoveMembers,
p.MuteMembers,
p.PrioritySpeaker,
p.ReadMessageHistory,
p.RequestToSpeak,
p.SendMessages,
p.SendMessagesInThreads,
p.SendTTSMessages,
p.Speak,
p.Stream,
p.UseApplicationCommands,
p.UseEmbeddedActivities,
p.UseExternalEmojis,
p.UseExternalStickers,
p.UseVAD,
p.ViewAuditLog,
p.ViewChannel,
p.ViewGuildInsights,
]
if (command.permissions) {
let invalidPerms = []
for (const permission of command.permissions) {
if (!ValidPerms.includes(permission)) {
console.log(`Invalid Perms`)
}
if (!message.members.permission.has(permission)) {
invalidPerms.push(permission)
}
}
if (invalidPerms.length) {
const noPermsEmbed = new ME()
.setColor(config.colors.no)
.setTitle("Aww~~~ You dont have have permss~")
.addField('Aweee~~~ you don\'t have permissions to run command:', `\`${command.name}\``)
.addField('Permission Required', `\`${invalidPerms}\``)
.setFooter({ text : client.user.username, iconURL : client.user.displayAvatarURL() })
.setTimestamp()
return message.channel.send(noPermsEmbed);
}
}
I tried using the "ADMINISTRATOR" like putting something like this in one like in the code and still the same error where did I go wrong?
Nvm I fixed it I have so many errors on creating the perms I didn't read the docs of so I fixed it by changing the p.[perms] to p.Flags.[perms] and I forgot to create a new function called :
`const ValidPerms = new PermissionsBitField(perms)`
and I fixed this function as well :
if (command.permissions) {
let invalidPerms = []
for (const permission1 of command.permissions) {
if (!ValidPerms.has(permission1)) {
console.log(`Invalid Perms`)
}
const member = message.member
if (!member.permissions.has(permission1)) {
invalidPerms.push(permission1)
}
}
if (invalidPerms.length) {
const noPermsEmbed = new ME()
.setColor('Random')
.setTitle("Aww~~~ You dont have have permss~")
.addFields(
{
name: 'Aweee~~~ you don\'t have permissions to run command:',
value: `\`${command.name}\``
}
)
.addFields(
{
name: 'Permission Required',
value: `\`${invalidPerms}\``
}
)
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
.setTimestamp()
return message.channel.send({embeds : [noPermsEmbed]});
}
}
and on the command as well On Module.Exports :
permissions: ['BanMembers'],
I hope this answer will help you as well
reference here : https://discordjs.guide/popular-topics/permissions.html#converting-permission-numbers

I am creating an event to identify the Member Status

client.on('raw', async dados => {
if(dados.t == 'PRESENCE_UPDATE' && this.client.guilds.cache.get("948835296089342012").members.cache.get(dados.d.user.id)){
let membro = this.client.guilds.cache.get("948835296089342012").members.cache.get(dados.d.user.id)
if(dados.d.activites.state == null) return membro.roles.remove("653651520361070612")
if(dados.d.activities.state == undefined) return membro.roles.remove("653651520361070612")
let valor = dados.d.activities.state.toLowerCase()
let n = valor.search(`discord.gg/server`)
if(n>=0) membro.roles.add("653651520361070612")
if(n<0 && membro.roles.cache.has("653651520361070612")) membro.roles.remove("653651520361070612")
}
log=
user: { id: '932194344859996180' },
status: 'online',
guild_id: '947899731303096320',
client_status: { web: 'online' },
activities: [
{
type: 4,
state: 'aa536a43',
name: 'Custom Status',
id: 'custom',
created_at: 1647655901662
}
]
}
I'm creating an event to identify the member's Status, for example: if the member has the url in the discord.gg/3 status the member will receive a position and when he removes the status the bot will remove the selected position
The presence is only available on GuildMember not an user. Get the member who used the command from message.member (make sure that the command is used in a guild)
Now read the member's presence through message.member.presence. Seems like you are trying to get member's custom status. It's one of presence.activities array and has the type Activity. Find in that array which has the type is CUSTOM, that is what you need. Note that presence can be null so you need to check if it exists.
This is the code I have tested and it works. Hope it works for you too:
const member = message.member; // Get member from message
const custom = member.presence?.activities?.find(x => x?.type === 'CUSTOM'); // Get the custom status from member's presence
if (custom?.includes('cat') console.log('This user has `cat` in his/her custom status');
else { console.log('This user doesn\'t have `cat` in his/her custom status'); }
const Command = require("../../structures/Command");
module.exports = class teste extends Command {
constructor(client) {
super(client);
this.client = client;
this.name = "teste";
this.category = "Fun";
this.description = ".";
this.usage = "";
this.aliases = [];
this.enabled = true;
this.guildOnly = true;
}
async run({ message, args}, t) {
const user =
this.client.users.cache.get(args[0]) ||
message.mentions.members.first() ||
message.author
console.log(user.presence.activities.state)
}
}
I also tried to use this without being on the basis of the Event but on the command, it always returns undefined
log=
[
Activity {
id: 'custom',
type: 'CUSTOM',
url: null,
details: null,
state: 'aa536a43',
applicationId: null,
syncId: null,
platform: null,
party: null,
assets: null,
flags: ActivityFlags { bitfield: 0 },
emoji: null,
sessionId: null,
buttons: [],
createdTimestamp: 1647656752595
}
]

if (fn(val, key, this)) error (Discord.js)

This program should add role to a server member
Here is an error:
Users\Администратор.ADMIN-5IU14HIGH\Desktop\DSBot\node_modules#discordjs\collection\dist\index.js:235
if (fn(val, key, this))
^ TypeError: fn is not a function
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
module.exports = {
name: 'role',
description: 'role',
execute(message, args) {
const member = message.mentions.members.first();
let myRole = message.guild.roles.cache.some(791413811529515008);
member.roles.add(role);
},
};
.some takes in a function and returns true if some value in the collection matches the function. You pass in a value, so you get the error. You want to actually get the value at the key, so use the get function:
let myRole = message.guild.roles.cache.get(791413811529515008);

Ban Command in Discord.js won't Compile

I have a command which bans a user. I have tried changing the last part to several different variations yet if I try modChannel.message.send, it throws the error "modChannel already defined." I'm not sure what else to do.
module.exports = {
name: "ban",
description: "Ban the troublesome users!",
execute(message, args) {
let member = message.mentions.user.first();
if(!message.member.roles.some(r=>["Administrator"].includes(r.name))) {
return message.channel.send("You don't have the permissions to use this command!");
}
if(!member.bannable) {
return message.channel.send("I can\'t ban this person. Please try again. Make sure I have ban permissions.");
}
let reason = args.slice(7).join(" ");
if(!reason) {
reason = "No reason was provided.";
}
let modChannel = client.guilds.find(ch => ch.name === "mod-log");
const banEmbed = {
color: 225,
title: "User Banned",
description: `**User**: ${member.username}#${member.discriminator} (${member.id})
**Reason**: ${reason}
**Banned By**: ${message.author.username}#${message.author.discriminator}`,
},
modChannel.send({embed: banEmbed });
},
};
Try:
let modChannel = message.guild.channels.find(c => c.name === "logs)

How do I make a channel? (discord.js)

I have a problem with creating a channel. Here is my code:
let id = message.author.id.toString().substr(0, 4) + message.author.discriminator;
var name = `order-${message.author}-${id}`
message.createChannel(name);
This is the error I am getting:
TypeError: message.createChannel is not a function
I hope someone could help me! :-)
message.createChannel() is not a thing. You need to use guild.channels.create().
For a full list of permissions, click here.
const category = message.guild.channels.cache.get(CATEGORY_ID)
message.guild.channels.create(name, {
parent: category,
permissionOverwrites: [
{
id: message.author.id, // Takes either user ID or role ID
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES'], // Denies permission(s)
allow: ['ATTACH_FILES'] // Allows permission(s)
},
{
id: message.guild.id, // guild.id doubles as the role id for the default role `#everyone`
deny: ['VIEW_CHANNEL']
}
]
})

Resources