DISCORD BOT : `TypeError: Cannot read properties of undefined (reading 'permission')` - discord.js

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

Related

MessageEmbed description must be a string

This is my code and im getting this error: RangeError [EMBED_DESCRIPTION]: MessageEmbed description must be a string can can someone help me please? I updated from v12 to v13 and now this error happens, haven't found a solution yet.
const { MessageEmbed } = require('discord.js');
const Command = require('../../Structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
aliases: ['halp'],
description: 'Displays all the commands in the bot',
category: 'Utilities',
usage: '[command]'
});
}
async run(message, [command]) {
const embed = new MessageEmbed()
.setColor('BLUE')
.setAuthor(`${message.guild.name} Help Menu`, message.guild.iconURL({ dynamic: true }))
.setThumbnail(this.client.user.displayAvatarURL())
.setFooter(`Requested by ${message.author.username}`, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
if (command) {
const cmd = this.client.commands.get(command) || this.client.commands.get(this.client.aliases.get(command));
if (!cmd) return message.channel.send(`Invalid Command named. \`${command}\``);
embed.setAuthor(`${this.client.utils.capitalise(cmd.name)} Command Help`, this.client.user.displayAvatarURL());
embed.setDescription([
`**❯ Aliases:** ${cmd.aliases.length ? cmd.aliases.map(alias => `\`${alias}\``).join(' ') : 'No Aliases'}`,
`**❯ Description:** ${cmd.description}`,
`**❯ Category:** ${cmd.category}`,
`**❯ Usage:** ${cmd.usage}`
]);
return message.channel.send(embed);
} else {
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
]);
let categories;
if (!this.client.owners.includes(message.author.id)) {
categories = this.client.utils.removeDuplicates(this.client.commands.filter(cmd => cmd.category !== 'Owner').map(cmd => cmd.category));
} else {
categories = this.client.utils.removeDuplicates(this.client.commands.map(cmd => cmd.category));
}
for (const category of categories) {
embed.addField(`**${this.client.utils.capitalise(category)}**`, this.client.commands.filter(cmd =>
cmd.category === category).map(cmd => `\`${cmd.name}\``).join(' '));
}
return message.channel.send(embed);
}
}
};
Since you updated discord.js to v13, <MessageEmbed>.setDescription no longer accepts arrays, you need to put a string or use <Array>.join like this:
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
].join('\n'));
Discord.js is expecting a string but you give it an array.
I would remove the array brackets [ ] and the commas from the setDescriptions

Im trying to make a giveaway command based in a tutorial i saw and it says TypeError: Cannot read property 'start' of undefined

As i said in the title i am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error. Pls help me i dont know what to do.
error:
"Cannot read property 'start' of undefined"
const ms = require('ms')
const { MessageEmbed } = require('discord.js')
module.exports = {
name : 'giveaway',
execute : async(message, args ,client) => {
if(!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('You dont have manage messages permission.')
const channel = message.mentions.channels.first()
if(!channel) return message.channel.send('Please specify a channel')
const duration = args[1]
if(!duration) return message.channel.send('please enter a valid duration')
const winners = args[2]
if(!winners) return message.channel.send('Please specify an amount of winners')
const prize = args.slice(3).join(" ")
if(!prize) return message.channel.send('Please sepcify a prize to win')
client.giveaways.start(channel, {
time : ms(duration),
prize : prize,
winnerCount: winners,
hostedBy: message.author,
messages: {
giveaway: "Giveaway \#everyone",
giveawayEnd: "Giveaway Ended \#everyone",
timeRemaining: "Time Remaining **{duration}**",
inviteToParticipate: "React with 🎉 to join the giveaway",
winMessage: "Congrats {winners}, you have won the giveaway",
embedFooter: "Giveaway Time!",
noWinner: "Could not determine a winner",
hostedBy: 'Hosted by {user}',
winners: "winners",
endedAt: 'Ends at',
units: {
seconds: "seconds",
minutes: "minutes",
hours: 'hours',
days: 'days',
pluralS: false
}
},
})
message.channel.send(`Giveaway is starting in ${channel}`)
}
}
error line code: client.giveaways.start(channel, {
index.js:
client.giveaways = new GiveawaysManager(client, {
storage : './giveaways.json',
updateCountdownEvery : 5000,
embedColor: '#D03600',
reaction: '🎉'
})
giveaways.json: []
Execute:
try{
command.execute(message,args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
In your command.execute() call, you are passing in client as the fourth parameter. But in your command file, where you export the giveaway command, client is the third parameter.
module.exports = {
name : 'giveaway',
// Add cmd parameter here, so client is passed in correctly as the fourth parameter
execute : async(message, args, cmd, client) => { ... }
}

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)

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