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

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.

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 | TypeError: Cannot read property 'position' of undefined

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.

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)

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

Resources