Cannot read properties of null (reading 'hasPermission') discord.js - discord

I have coded a discord bot but i have a problem, when i execute my command it shows me a error.
Error:
if (!message.member.hasPermission("ADMINISTRATOR"))
TypeError: Cannot read properties of null (reading 'hasPermission')
Code where the error comes up:
if (command === "add") {
if (!message.member.hasPermission("ADMINISTRATOR"))
return message.reply("Desoler, vous ne pouvez pas effectuer cette commande car vous n'ette pas administrateur");
var fs = require("fs");
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var account = args[0]
var service = args[1]
const filePath = __dirname + "/" + args[1] + ".txt";
fs.appendFile(filePath, os.EOL + args[0], function (err) {
if (err) return console.log(err);
message.channel.send("Terminer !")
});
I already tried to replace hasPermission with permissions.has but it still does not work.

Define your client like that
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
Also make sure intents are enabled in the developer portal and use GuildMember#permissions.has

Related

How do i add a commands where it unban an user id from all the servers the bot is in

So i have tried this but it says "ReferenceError: member is not defined", can you guys help me fixing it please, i already have a command to ban someone from all the servers the bot is in but i don't know how to do for unban-all, so here is my code so you can guys take a look, i'm pretty new in discord.js so sorry if my code looks bad
const { MessageEmbed } = require('discord.js');
/**
*
* #param {import('discord.js').Client} client
* #param {import('discord.js').Message} message
* #param {string} args
*
*/
exports.run = async (client, message, args) => {
const targetID = args[0];
const reason = args.slice(0).join(' ')
const dm_messagev2 = new MessageEmbed()
.setColor("#02fa49")
.setTitle(":no_entry: BAN :no_entry:")
.addField("**Message :**", `${member.user.tag} Vous avez été déban-all de Storm-Community.`)
.addField("**Raison : **", `${reason || 'Aucune raison définie.'}`)
.addField("**Autheur : **", `${message.author.username}.`)
.setFooter("Bot by Roka | 1.1")
member.send({ embeds: [dm_messagev2]})
setTimeout(function(){
client.guilds.cache.forEach(a => a.members.unban(targetID)).then(() => {
const embedv3 = new MessageEmbed()
.setColor("#02fa49")
.setTitle(":white_check_mark: Succès")
.addField("**Message :**", `${member.user.tag} as été déban-all de la communauté.`)
.addField("**Raison : **", `${reason || 'Aucune raison définie.'}`)
.addField("**Auteur : **", `${message.author.username}.`)
.setFooter("Bot by Roka | 1.1")
message.channel.send({ embeds: [embedv3]});
});
}, 2000);
/* const dmembed = new MessageEmbed()
.setTitle("You have been banned from all the servers i am in")
.setDescription('Your Crime was `${reason}`. If you want to apeal, You may join [Appeal Server by Clicking here](https://discord.gg/ZWWYy37atN)')
.setColor("#FF0000")
message.targetID.send(embed)*/
};
exports.info = {
name: 'unbanall', // Command name
description: 'Clears a specific amount of messages in a channel', // Command description
category: 'mod',
icon: '🧹',
usage: '<count>' // Command usage
};
exports.config = {
args: true, // Whether this command should require one or more arguments
guildOnly: true, // Whether the command should be used in a guild or not
permissions: {
user: ['MANAGE_MESSAGES'], // Required guild permissions for the user to use this command (must be a valid permission flag)
bot: ['MANAGE_MESSAGES'], // Required guild permissions for the bot to run this command (must be a valid permission flag)
},
aliases: ['uball', 'unban-all', 'débanall', 'déban-all', 'deban-all', 'debanall'], // Aliases
disabled: false, // Whether this command is disabled or not
};```
It looks as if your Reference Error is coming from
member.send({ embeds: [dm_messagev2]})
I'm not quite sure why you need this for an unban as it seems to be a notice of a ban. Assuming its just leftover code...
As for unbanning all your banned members, you can access these bans through this method!
guild.bans.fetch();

ReferenceError: Cannot access ' ' before initialization

My code;
const mentionMember = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(banEmbederrormessage);
banEmbederrormessage
let banEmbederrormessage = new discord.MessageEmbed()
.setColor(0xdb2727)
.setDescription(`
Bir hata oluştu.
**[KULLANIM]** +ban #mention sebep
`);
Terminal error;
(node:3248) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'banEmbederrormessage' before initialization
at Object.run (C:\Users\gtaplus bot\commands\ban.js:13:50)
I am developing ban command. Terminal returns this error after using the ban command.
You need to place the definition first.
let banEmbederrormessage = new discord.MessageEmbed()
.setColor(0xdb2727)
.setDescription(`
Bir hata oluştu.
**[KULLANIM]** +ban #mention sebep
`);
const mentionMember = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(banEmbederrormessage);

Unban is not defined

const Discord = require('discord.js');
module.exports = {
name: 'unban',
aliases: ['uban', 'unban'],
category: 'misc',
permissions: ['BAN_MEMBERS'],
description:
'Use this command to permanately or temporary ban a server member from Sekai.',
/**
* #param {Discord.Message} message
* #param {Array} args
*/
async execute(message, args) {
if (message.mentions.users.size === 0)
return message.reply('Please mention a user to unban ❌');
const targetid = message.mentions.users.first().id;
if (targetid === message.client.user.id)
return message.reply(
"Me? Really? That's not very nice, I guess you failed 🤡"
);
const targed = await message.guild.members.cache.get(targetid);
let reason = [];
if (args.length >= 2) {
args.shift();
reason = args.join(' ');
} else reason = 'No Reason provided';
try {
let extra = '';
try {
const embed = new Discord.MessageEmbed()
.setTitle('Moderation message regarding on your **BAN**')
.setAuthor("Joony's Den")
.setDescription(
`you have been banned from **${message.guild.name} ✅ **\nReason for ban: **${reason}\n${extra}**`
)
.addField('Contact','If you believe that your ban was unjustified, please feel free to contact any of these staff members. **JOONY#9513** or any of administrators online.')
.setColor('#2243e6')
.addField('Appeal Accepted?','if your appeal was accepted, please join using this link. your link will expire after 1 use. **https://discord.gg/4yuCzUC7aw**')
.addField(
'Appeal',
'Because you have been banned from the server, you will have one chance to appeal 🔨. Your appeal will be processed to the administrators or appeal managers ✅ **[CLICK HERE TO APPEAL](https://forms.gle/atc75ZftpdfJhfH56)**'
);
targed.send(embed);
} catch (error) {
extra = 'Messaging the user has failed! ❌';
}
setTimeout(() => {
targed.unban(targed, [reason])
const embed = new Discord.MessageEmbed()
.setTitle('User unbanned')
.setDescription(
`${
targed.tag || targed.user.username
} has been sucessfully unbanned from **${
message.guild.name
} ✅ **\nReason for unban: **${reason}\n${extra}**`
)
.setColor('#FA2657');
message.channel.send(embed);
}, 2000);
} catch (error) {
message.channel.send(
`I could not unban the given member, make sure that my role is above member! ❌`
);
}
},
};
Hello! how do I unban the user using this format, it has an error saying "guild.unban is undefined"
it has an error saying
targed.unban([reason])
^
TypeError: targed.unban is not a function
at Timeout._onTimeout (C:\Users\Joon\Documents\GitHub\Discord-Bot\commands\misc\unban.js:49:16)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
You cannot unban a GuildMember (a banned user is not a member of a Guild). You should call unban on GuildMemberManager. See https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban

send error message or without permission on the channel

My bot is having some problems with some servers, the problem is Missing Permissions, it happens when the bot tries to do a function that it does not have permission on the server, and to alert the users of the bot that it does not have permission to execute the command on the server, I put 2 functions so that it warns the member that it does not have enough permission, but it is not advancing because the bot does not send the message on the channel saying that it does not have permission
The first function where he tells the member that he is not allowed to create the invitation is
in if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('I am not allowed to create invitations.');}
And the second is
in } catch (e) { console.log(e) return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
const ms = require('parse-ms')
const { DiscordAPIError, MessageEmbed } = require("discord.js");
const { invalid } = require("moment");
module.exports = {
name: "jogar",
description: "Set the prefix of the guild!",
category: "economia",
run: async (bot, message, args) => {
if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('Eu não\ tenho permissão para fazer isso!');
}
const { chunk } = require('../../functionsss');
let guild = bot.guilds.cache.get("759003907858104350");
let emoji = guild.emojis.cache.find(emoji => emoji.name === 'loading');
let emoji2 = guild.emojis.cache.find(emoji => emoji.name === 'check');
if(!message.member.voice.channel) return message.reply(`Você precisa está conectado ao um canal de voz para procurar partida!`)
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;
const vo = message.member.voice.channel.members.size
for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;
let membro = message.author;
let newInfo = args.join(' ');
if (!newInfo) return message.reply('Insira o codigo da sala do among! **a!jogar BCETYJ**');
if (newInfo.length > 6) return message.channel.send(`**Max \`6\` Caracteres permitidos!**`);
let newsInfo = chunk(newInfo, 42).join('\n');
let embed = new Discord.MessageEmbed();
try {
let channel = message.member.voice.channel;
channel.createInvite({
maxAge: 3600, // 0 = infinite expiration
maxUses: 10 // 0 = infinite uses
})
.then(invite=>{
embed
.setTitle(`${emoji} Procurando partida..`)
.setColor('RANDOM')
.setTimestamp()
.setDescription(`Pessoal <#${membro.id}> está procurando mais gente para jogar!
\n<:info:775212992895254548> **Informações:**
**・Canal:** ${channel}
**・Codigo:** ${newsInfo}
**・Jogadores:** ${vo}
\n[Entrar na partida](https://discord.gg/${invite.code})`)
.setThumbnail('https://attackofthefanboy.com/wp-content/uploads/2020/09/Among-Us-3.jpg')
message.channel.send(embed)
message.react("✅");
})
} catch (e) {
console.log(e)
return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
}}}```
I've had this problem before and I spent hours troubleshooting. I eventually figured out that it was the way that I was looking for permissions. Discord.js v12 has added many changes to this type of function. I suggest changing
(!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE'))
to
(!message.guild.me.hasPermission("Create_Instant_Invite"){
//rest of your code
}

Why this bot is failing at 'user.hasPermission()'?

I developed a bot. This is my code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('ready', () => {
console.log(`Bot ready!`)
})
const filterNum = (str) => {
const numericalChar = new Set(["|","&","!","?",":","<","=",">","(",")","/","*","-","+",".","0","1","2","3","4","5","6","7","8","9"])
str = str.split("").filter(char => numericalChar.has(char)).join("");
return str;
}
client.on('message',(msg)=>{
user = msg.author
msg1 = msg.content
msg1 = msg1.toLowerCase()
msg1 = msg1.replace(new RegExp(/[àáâãäå]/g),"a")
msg1 = msg1.replace(new RegExp(/[èéêë]/g),"e")
msg1 = msg1.replace(new RegExp(/[ìíîï]/g),"i")
msg1 = msg1.replace(new RegExp(/[òóôõö]/g),"o")
msg1 = msg1.replace(new RegExp(/[ùúûü]/g),"u")
msg1 = msg1.replace(new RegExp(/[ýÿ]/g),"y")
try{
if(msg.content.startsWith("/kick")){
if(user.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])){
member = msg.mentions.members.first()
if(member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])){
msg.channel.send("No se puede kickear a un staff.")
}else{
member.kick().then((member) => {
msg.channel.send("Kickeado exitosamente.")
}).catch(() => {
msg.channel.send("Acceso denegado.")
})
}
}else{
msg.channel.send("/kick "+user)
}
}
}catch(e){
msg.channel.send(e.message)
}
if(msg.content.startsWith("/calc")){
try{
operation=msg.content.split("/calc")[1]
operation=filterNum(operation)
result=eval(operation)
msg.channel.send("```"+operation+"≡"+result+"```")
}catch(e){
msg.channel.send(e.message)
}
}
if(!msg.content.startsWith("/calc")&&!msg.content.startsWith("/kick")&&msg.content.startsWith("/")){
msg.reply(`
Comando desconocido. Aquí tienes la lista de comandos:
/kick miembro: Expulsa a un miembro de la sala.
/calc operación: Calcula una operación matemática.
`)
}
})
client.login('token')
And this is the error:
user.hasPermission is not a function
I tried to change it to another command and it didn't worked. I tried to show msg.author, and it's undefined, but strangely, msg.author.bot is defined as a boolean. It's weird. Looks like a problem with discord.js API. I cant show the token because someone can utilize my bot into his purposes, but, anywhere.
What can I do? Thanks for helping.
The hasPermission() function can only be used on a member object. So you need to change user = msg.author to user = msg.member.

Resources