Discord.js | TypeError: Cannot read property 'position' of undefined - discord.js

I'm working on a discord.js bot and its giving me a TypeError, but I'm not sure why.
Code:
module.exports = {
name: 'kick',
description: 'Tag a member and kick them',
execute(message) {
if(!message.member.hasPermission('KICK_MEMBERS')) {
message.channel.send("You're not an admin lmaooo")
return;
};
let mentionMember = message.mentions.members.first();
if(!mentionMember){
message.channel.send("Who do you want me to kick :smiling_imp:")
return;
}
let authorHighestRole = message.member.highestRole.position;
let mentionHighestRole = mentionMember.highestRole.position;
if(mentionHighestRole >= authorHighesrRole) {
message.channel.send("I can't kick him hes to op :tired_fac:")
return;
};
if(!mentionMember.kickable){
message.channel.send("I have no perms cant kick him lol")
};
mentionMember.kick()
.then(() => console.log(`Kicked ${member.displayName}`))
.catch(console.error);
},
};
Error: TypeError: Cannot read property 'position' of undefined

You need to specify what you're trying to code.
Node.js usually provides the line where the error has occurred.
Check if (mentionHighestRole >= authorHighesrRole) {
It probably should be authorHighestRole.
If that doesn't solve the issue, then it's probably the if statement itself, because that statement doesn't make sense to me.
EDIT: your authorHighestRole should also be let authorHighestRole = message.author.highestRole.position.

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

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

can someone explain the change to bulkDelete (discord.js)

Here is the code I have right now
module.exports ={
name:'purge',
description:'Clears the number of messages you set in a seccond ARG.',
aliases:['clear','nuke'],
execute(msg, args)
{
if(!msg.member.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("You do not have permission to run this command").then(msg => msg.delete(5000));
}
if (!isNaN(args[0]) || parseInt(args[0]) <= 0) {
return msg.reply("That is not a number").then(msg => msg.delete(5000));
}
if(!msg.guild.me.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("Sorry I can't messages please make sure i have the correct permissions").then(msg => msg.delete());
}
let deleteAmount;
if(parseInt(args[0]) > 100) {
deleteAmount = 100;
} else {
deleteAmount = parseInt(args[0]);
}
msg.channel.bulkDelete(deleteAmount, true);
}
}
Error:
(node:25048) UnhandledPromiseRejectionWarning: TypeError [MESSAGE_BULK_DELETE_TYPE]: The messages must be an Array, Collection, or number.
at TextChannel.bulkDelete (C:\StrangeOccBot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:364:11)
at Object.execute (C:\StrangeOccBot\commands\purge.js:27:21)
at Client.<anonymous> (C:\StrangeOccBot\index.js:46:39)
at Client.emit (events.js:315:20)
at WebSocketShard.onPacket (C:\StrangeOccBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\StrangeOccBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\StrangeOccBot\node_modules\ws\lib\event-target.js:120:16)
So I'm not sure if an int is still the way to do it with bulkDelete()
but as far as I know, you can fetch messages in a channel and pass those to the method!
msg.channel.messages.fetch({ limit: deleteAmount }).then(messages => {
msg.channel.bulkDelete(messages).then(deleted => {
msg.channel.send(`${deleted.size} messages pruged!`).then(msg => msg.delete(5000));
})
})
This is the way how I have done it for the last few times I created functions like what you try to archive.
Also you can add .catch() methods to the .then() methods so you can check if something went wrong or not!
Edit: I changed your code a little bit especially at the end so you have an idea how I would have done it to archive what you wanna archive
module.exports ={
name:'purge',
description:'Clears the number of messages you set in a seccond ARG.',
aliases:['clear','nuke'],
execute(msg, args) {
if (!msg.member.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("You do not have permission to run this command").then(msg => msg.delete(5000));
}
if (!msg.guild.me.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("Sorry I can't messages please make sure i have the correct permissions").then(msg => msg.delete());
}
if (!isNaN(args[0]) || parseInt(args[0]) <= 0) {
return msg.reply("That is not a number").then(msg => msg.delete(5000));
}
// I changed this slightly to how I would do it!
let deleteAmount = 100;
if (parseInt(args[0]) < 100) {
deleteAmount = parseInt(args[0])
}
// If I'm not mistaken, the bulkDelete() method also works with fetched messages in an variable.
// To archive this, you can use `msg.channel.messages.fetch()` as I will show below!
// Ofcourse I did not use the .catch() method, so if something isn't correctly done it can cause issues!
msg.channel.messages.fetch({ limit: deleteAmount }).then(messages => {
msg.channel.bulkDelete(messages).then(deleted => {
msg.reply(`${deleted.size} messages pruged!`).then(msg => msg.delete(5000));
})
})
}
}

How do I check if the bot has permmsion to manage webhooks?

My problem is that I'm getting an error whenever I use the following code:
else if (cmd === "sayw") {
const embed2 = new Discord.RichEmbed()
.setDescription("❌ You can't make me say nothing! \nWait, you just did-")
.setFooter(`Requsted by ${message.author.tag}.`, message.author.avatarURL)
if(!args[0]) return message.channel.send(embed2)
const guild = message.guild
const embed = new Discord.RichEmbed()
.setAuthor("Say Webhook", bot.user.avatarURL)
.setDescription("❌ I need the `MANAGE_WEBHOOKS` permision first!" )
.setImage(`https://i.gyazo.com/d1d5dc57aa1dd20d38a22b2f0d4bd2f6.png`)
const member = guild.members.get(bot.id)
if (member.hasPermission("MANAGE_WEBHOOKS")) {
message.channel.createWebhook(message.author.username, message.author.avatarURL)
.then(webhook => webhook.edit(message.author.username, message.author.avatarURL))
.then(wb => {wb.send(args.join(" "))
setTimeout(() => {
bot.fetchWebhook(wb.id, wb.token)
.then(webhook => {
console.log("deleted!")
webhook.delete("Deleted!")
}, 5000)})})
} else {
message.channel.send(embed)
}}
I want the bot to tell the user if it can't create the webhook, but instead, I get this error when trying to use this command:
(node:10044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined
How do I make this code work?
If you're using Discord.js v12 (the latest verison), guild.members.get(bot.id) won't work as guild.memebrs is now a GuildMemberManager.
Use
const member = guild.members.cache.get(bot.id)
or you could even use this as a shortcut:
const member = guild.me

TypeError: Cannot read property 'id' of undefined [discord.js]

Im getting this error for writing this "unban" codes to unban.js
Re-installed discord.js library, re-writed the code but did'nt worked.
module.exports.run = async (client, message, args) => {
if (!message.member.roles.find(role => role.name === "🚫| Ban Hammer")) {
return message.channel.send(
"**Kanka `🚫| Ban Hammer` yetkisine sahip değilsin.**"
);
}
let bannedMember = await client.fetchUser(args[0]);
if (!bannedMember) {
return message.channel.send(`**Bir id yazmalısın.**`);
}
let reason = args.slice(1).join(" ");
if (!reason) {
reason = "Bir sebep belirtilmedi.";
}
try {
message.guild.unban(bannedMember, { reason: reason });
message.react(emoji);
} catch (e) {
console.log(e.message);
}
};
module.exports.conf = {
name: "unban"
};
[ Sorry guys, my english is bad. ]
It seems that your code does not reference id in that particular file.
When looking for debugging help, please attach the full, or at least main error message, like Cursed said. my only suggestion would be that id might be misused in a different file, or incorrectly referenced elsewhere.

Resources