send error message or without permission on the channel - discord

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
}

Related

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

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

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

Discord warn command + time

Greetings I want to do something to my warn command
I want to add a time to it like: ,warn Noob 5m Cause a noob
warn [name | nickname | mention | ID] [time] [Reason]
I have no idea how to do it can someone help?
const { MessageEmbed } = require("discord.js");
const { redlight } = require('../../JSON/colours.json')
const db = require('quick.db');
module.exports = {
config: {
name: "warn",
aliases: ['report'],
category: "moderation",
description: "reports a user of the guild",
usage: "[name | nickname | mention | ID] <reason> (optional)",
accessableby: "Administrator",
},
run: async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have The Permissions To Report Someone! - [MANAGE_GUILD]**");
if (!args[0]) return message.channel.send("**Please Enter A User!**")
let target = 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 (!target) return message.channel.send("**Please Enter A User!**")
if (target.id === message.member.id) return message.channel.send("**Cannot Warn Yourself!**")
let reason = args.slice(1).join(" ")
if (target.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Warn This User!**')
if (target.hasPermission("MANAGE_GUILD") || target.user.bot) return message.channel.send("**Cannot Warn This User!**")
try {
const sembed2 = new MessageEmbed()
.setColor("RED")
.setDescription(`**Hello, You Have Been Warned In ${message.guild.name} for - ${reason || "No Reason!"}**`)
.setFooter(message.guild.name, message.guild.iconURL())
target.send(sembed2)
} catch {
}
if (reason) {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned for ${reason}!**`)
message.channel.send(embed)
} else {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned!**`)
message.channel.send(embed)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
const sembed = new MessageEmbed()
.setColor(redlight)
.setTimestamp()
.setThumbnail(target.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "report")
.addField("**User Reported**", `${target}`)
.addField("**User ID**", `${target.user.id}`)
.addField("**Reported By**", `${message.member}`)
.addField("**Reported in**", `${message.channel}`)
.addField("**Reason**", `**${reason || "No Reason"}**`)
.addField("**Date**", message.createdAt.toLocaleString());
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(sembed)
}
}
Thanks in advance!
(Telling me to add more details but idk what I can say more so ignore this lol)
Basically, Your code is hard to get, atleast for me. But you can add timeout fuction like this:-
setTimeout(function(){
//thing you wanna do
}, 1000); //time in milliseconds
Also before you proceed ahead, I don't think you want to make timed warns, which clear after particular time, Maybe. it's on you.

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.

How can I prohibit the use of the command on certain roles

I want to write code that will check if the roles are in the list. If yes, then they can be issued, and if not, then no. I'm new in discord js.
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply();
let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!rMember) return message.reply("I can't find player.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("specify rang!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("I can't find this rang!.");
if(rMember.roles.has(gRole.id)) return message.reply("I can't do it.");
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
await(rMember.removeRoles(['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']));
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Your rang was changed to ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
It works without check code, but if I add it, all times, when I will try to change role of user, it gives out "nope".
You could check whether the given role is in the list of allowed roles using Array.includes().
const allowed = ['id', 'anotherID', 'andAnother'];
if (!allowed.includes(gRole.id)) return;
// Returns if the role is *not* in the 'allowed' array.

Resources