I want to check if someone has permission to be kicked, but the answer is wrong - discord

I use msg.member.hasPermission('KICK_MEMBERS'), but even if the author of the message doesn't have this permission, the answer is true instead of false.
const Discord = require("discord.js");
const client = new Discord.Client();
channel = '858963360909099068';
module.exports ={
name: 'kick',
description: 'kick people',
execute(msg, args) {
let impostor = msg.mentions.members.first();
const mod = msg.author;
let botResponse;
if(msg.member.hasPermission('KICK_MEMBERS')){
console.log('true');
if(!impostor){
botResponse = 'You need to tag the person that you want to kick !';
impostor = 'Not specified';
}
else{
botResponse = `${impostor} was kicked !`;
impostor.kick();
}
}
else{
console.log('false');
botResponse = 'You are not able to kick people !';
}
let embed = new Discord.MessageEmbed()
.setColor('#f9ae0e')
.setTitle('Kick')
.setDescription(botResponse)
.addFields(
{ name: "Impostor", value: impostor},
{ name: "Member", value: mod}
);
msg.channel.send(embed);
}
}
This is the error:
TypeError: msg.member.hasPermission is not a function
I can't see what's wrong here, can you help me solve it?

You should change msg.member.hasPermission('PERM') to msg.member.permissions.has('PERM')

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

How To Make Queue System - Discord.js

I am working on a music and I would like to know how to add a queue system to the command; I have been looking around for hours and not been able to find anything on it,
If anyone can help that would be great and I don't need a queue command but I do need to add a queue system so it would really help I will be checking back in an hour to see if anyone has given me or an idea or the answer to my problem
This is my code so far:
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const YoutubeSearcher = new QuickYtSearch({
YtApiKey: '',
});
module.exports={
name: 'play',
category: 'music',
description: 'Joins and plays the song',
aliases: ['p'],
usage: '.play <song name or URL>',
run: async(client, message, args)=>{
try{
if (message.member.voice.channel) {
let args = message.content.split(' ').slice(1).join(' ');
if (!args) {
const error = new Discord.MessageEmbed()
.setTitle(`🔴 Looks like there is an Issue!`)
.setColor(0x2f3136)
.setDescription(`You have to provide me at least, the name or the url.\n\nExample :
\`\`\`fix
.play <url>
OR
.play <name>\`\`\``)
return message.channel.send(error);
};
message.member.voice.channel.join()
.then(connection => {
if (YoutubeSearcher.isVideoUrl(args) === false) {
YoutubeSearcher.getVideo(args).then(video => {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(video.url, { filter: 'audioonly' }, volume));
const play1 = new Discord.MessageEmbed()
.setTitle('Song info')
.setURL(video.url)
.setDescription(`Name: ${video.title}, By: ${video.channelTitle}`)
.setThumbnail(video.highThumbnail)
message.channel.send(play1);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.');
message.member.guild.me.voice.channel.leave();
});
});
} else {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(args, { filter: 'audioonly' }, volume));
message.reply('Now playing ' + args);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.')
message.member.guild.me.voice.channel.leave();
});
};
});
} else {
message.reply('You need to join a voice channel.');
};
}catch(err) {
console.log(err)
return message.channel.send(`Error: ${err.message}`)
}
}
}
In theory you could use the queue data structure (the last element is taken out and when a new one is added it is added to the start) and in the queue hold the music that is requested to be played. This is how it might roughly look like:
client.on("message", (msg) => {
var arrOfMusic = [];
if(msg.content.startsWith("!queue")){
msg.channel.send(arrOfMusic.join(" , ")
}
if(msg.content.startsWith("!play")){
arrOfMusic.push(msg.content.slice(6))
// you don't need to play the music
}
// your code to play the end of the array all you do is play the last element you also //need to check once it is over and use pop to remove last element
if(msg.content.startsWith("clear")){
arrOfMusic = []
}
})

i am having trouble with the kick command in my bot, can anyone help me?

edit
So i tried to make a kick and ban command but then i got this error in my kick file idk how to fix it
const memberTarget = message.guild.member.cache.get(member.id);
^
ReferenceError: message is not defined
this is the code:
module.exports = {
name: 'kick',
description: "this command kicks people",
execute(messages, args){
const member = messages.mentions.users.first();
if(member){
const memberTarget = message.guild.member.cache.get(member.id);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldent kick that person');
}
}
}
edit: now i got this error
const memberTarget = message.guild.member.cache.get(member.id);
^
TypeError: Cannot read property 'get' of undefined
This should fix your error:
module.exports = {
name: 'kick',
description: "this command kicks people",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.member(member);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldent kick that person');
}
}
}

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.

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)

Resources