Cannot read properties of undefined (reading 'roles') - javascript

i want to make ban command with button
and always getting error
if(guild.members.me.roles.highest.position <= members.roles.highest.position)
code:
run: async (interaction, client, user) => {
await interaction.deferReply({ ephemeral: false })
const { options, guild } = interaction
const member = interaction.options.getMember("target")
const reason = interaction.options.getString("reason") || "No reason provided"
const members = guild.members.cache.get(user.id)
if(member.id === user.id) return interaction.editReply(`You Can Banned Yourself`)
if(guild.ownerId === member.id) return interaction.editReply(`Cant Ban Owner`)
if(guild.members.me.roles.highest.position <= members.roles.highest.position) return interaction.editReply('can ban this member because your roles are same or higher')
if(interaction.member.roles.highest.position <= members.roles.highest.position) return interaction.editReply(`blabla`)
and i get an error:
Cannot read properties of undefined (reading 'roles')
how to solve it?
I always get an error like that
please anyone help me

Related

Does fetching embeds through messages from msg.reference.messageID not work?

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn't a thing. Is there anything wrong with my code?
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.
The error reads TypeError: Cannot read properties of undefined (reading '0'), and when I remove the [0], it's undefined. This whole thing is in a module.exports.run, if that helps.
module.exports.run = async (client, msg, args) => {
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
if (args.length === 5) {
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(await msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
//do things with fetchedMsg
You can get the MessageEmbed() same as normal Message using:
const messages = args[0]
if(!messages) return message.reply("Provide an ID for message.")
if(isNaN(messages)) return message.reply("Message ID should be
number, not a letter")
message.channel.messages.fetch(`${messages}`)
.then(msg => {
console.log(msg.content) || console.log(msg.embeds)
})
You can find more here about fetching a message

Cannot read properties of undefined (reading 'fetchBans')

Im trying to make a command with in my Discord bot to make unban a person. When I finnished the code I got an error. The error is Cannot read properties of undefined (reading 'fetchBans'). The code I use to make it is
message.guild.cache.fetchBans().then(async bans => {
if (bans.size === 0) return message.channel.send("No one is banned on the server!")
let bannedUser = bans.find(ban => ban.user.id == userID)
if (!bannedUser) return message.channel.send("This user isn't banned!")
await message.guild.members.unban(bannedUser.user, reason).catch(err => {
return message.channel.send("Something went wrong!")
}).then(() => {
let embed = new MessageEmbed()
.setColor("GREEN")
.setTitle(`Member unbanned!`)
.setDescription("")
.setTimestamp()
.setFooter(this.client.user.username)
embed.addField(`member = ${target.username}`, `reason = ${reason}`, false)
message.channel.send({embeds: [embed]});
if (row[0].logs_channel != null) this.client.channels.cache.get(row[0].logs_channel).send({embeds: [embed]})
message.delete()
})
The line where it goes wrong is this line:
message.guild.cache.fetchBans().then(async bans => {
When I run this command it will give the error. I also tried to do something else. The code i tried else for that line is:
message.guild.fetchBans().then(async bans => {
This line also gave an error that says: TypeError: message.guild.fetchBans is not a function.
I don't know what i can do about this. I hope somebody can help me.
Node.js version: 16.9.1
discord.js version: 13.1.0
According to the documentation there is no fetchBans on Guild. Maybe you're looking for message.guild.bans.fetch().
It's also worth noting that message.guild is nullable - if the message was a direct message (not sent in a guild) it will be null.

I want to disable discord bot commands in dms but I keep getting an error

This is my discord reject code:
client.on('message', msg => {
if (msg.channel instanceof Discord.DMChannel && msg.author.id !== "828093594098204702") {
const Reject = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle('Error')
.setDescription('This command can only be used in the server.')
msg.author.send(Reject);
}
})
This is the error I'm getting:
const member = msg.guild.members.cache.get(msg.author.id);
^
TypeError: Cannot read property 'members' of null
at Client.<anonymous>
How can I fix this?
(v13)
I know, that you are using messages, but if you will you'll change your mind and will start using slash commands, use if (!interaction.guild) return;, this will disable slash commands in DMS. Also you can add interaction.followUp to return a message.
client.on("message", message => {
if(message.author.bot
|| message.channel.type === "dm") return;
// your code here
}
this is what I use to filter out bots and dms.

"Cannot read property 'roles' of undefined" when no argument is provided

I have this code to add/remove the streaming role when a user types ?stream <user>
It works fine when this happens the whole command is entered, but when only ?stream
if (!member.roles.cache.some(role => role.name === 'streaming')) {
^
TypeError: Cannot read property 'roles' of undefined
and i have no idea why?
this is the code:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
const member = message.mentions.members.first();
if (command === 'stream') {
if(message.member.permissions.has("MANAGE_ROLES")){
if (!member.roles.cache.some(role => role.name === 'streaming')) {
member.roles.add('744292301874135122')
message.channel.send('`Added streaming role.`')
} else
member.roles.remove('744292301874135122') && message.channel.send('`Removed streaming role.`')
} else message.channel.send('`You dont have permission.`')
}
});
Discord.js can't get the member you defined in this method:
const member = message.mentions.members.first();
Because there is no mention when you just type ?stream. So discord.js can't get the roles of the member because the member is not defined.

discord.js UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined

Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...

Categories

Resources