i am having a few difficulties getting my kick command to only allow people with the permission node KICK_MEMBERS to kick people. currently i have the bot in a state where anyone and everyone is allowed to kick the following is my code.
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
};
module.exports.help = {
name: "kick"
}
GuildMember#hasPermission returns a boolean of whether a user has a specified permission or not. We can use it to declare if the user has the KICK_MEMBERS permission.
Final Code
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('KICK_MEMBERS', { checkAdmin: true, checkOwner: true })) return message.reply('You cannot use this command!')
// I like to have it so people with the administrator permission can use it regardless.
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
};
module.exports.help = {
name: "kick"
}
Related
I'm trying to make a ban all command for my bot and am having issues. When I try to use it, I get an error:
DiscordAPTError: Missing Permissions
This is my code:
const { Client, Discord } = require("discord.js")
module.exports.run = async (bot, message, args) => {
try {
message.guild.members.cache.each(m => {
m.ban();
});
} catch(e) {
console.log(e.stack);
}
}
module.exports.help = {
name: "banall",
desc: "Bans everyone",
}
Use this:
let members = await message.guild.members.fetch();
members.forEach(member => {
if (member.bannable) {
member.ban().catch((err) => { console.log(err); });
}
});
Also make sure your bot has the correct intents (configured in your js file) and permissions on the server (role perms)
I want to make a command that tags a user when there name got mentoined. But now the bot only tags the username and not a nickname the person has in the server
client.on("message", message => {
if(message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
})
client.on("message", message => {
const list = message.guild;
list.members.cache.each(member => {
pinging = member.user.id
console.log(member.user.username)
if(message.content.includes(member.user.username)){
message.channel.send(`<#${pinging}>`)
}
})
})
can anyone help?
First thing, you only want to have one listener for the message event, so try this code:
client.on("message", message => {
if (message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
// insert choices from below here
})
If you want it to listen for a member being tagged
const mentionedMember = message.mentions.members.first()
if (mentionedMember){
message.channel.send(`${mentionedMember}`)
}
Now if you want it to listen for username instead of #username
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.user.username.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})
To listen for displayName
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.displayName.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})
I am trying to create a command that kicks people, unfortunately, it doesn't work and no errors in the console, when I type -kick without mentioning anyone, the expected message comes, but when I mention someone it doesn't kick them.
Here is my code in my command handler:
module.exports = {
name: 'kick',
decription: 'Kick command',
execute(message, args) {
if (!message.guild) return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick()
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
};
}
}
EDIT: here is my main file code:
const Discord = require("discord.js");
const keepAlive = require("./server");
const client = new Discord.Client();
const prefix = ('-');
const fs = require('fs');
client.on("ready", () => {
console.log(`logged in as ${client.user.tag}`);
});
client.commands = new Discord.Collection();
const commandFiles = fs
.readdirSync('./commands/')
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('message', (message) => {
if(!message.content.startsWith(prefix) || message.author.bot)
return;
const args = message.content.slice(prefix.length).split("/ +/");
const command = args.shift().toLowerCase();
if (command === 'help') {
client.commands.get('help').execute(message, args);
} else if (command === 'clear') {
client.commands.get('clear').help(message,args);
} else if(command === 'ban') {
client.commands.get('ban').execute(message, args);
} else if(command === 'kick') {
client.commands.get('kick').execute(message);
} else if(command === 'mute') {
client.commands.get('mute').execute(message,args);
}
});
keepAlive();
client
.login("TOKEN")
.catch(console.error);
TypeScript has a feature that tells you if you declared an unnecessary variable (you never used the variable). You could remove it, or ignore it. Your code will work either way.
For example, using this code, TypeScript will tell you b is declared but its value is never read
const a = 1
const b = 2
console.log(a)
//b is not used anywhere except for the declaration
Why is your code not working?
You are using Guild.member. This relies on cache and is deprecated. Use message.mentions.members.first() instead to directly retrieve the member
const member = message.mentions.members.first();
args is not defined
This just means that the parameter args to your execute function is unnecessary here and you could remove it.
guild.member() does not exist, use guild.members.resolve(user.id) instead.
Also if you're just accessing a member of a guild, you should use message.mentions.members instead.
So in the end it would look something like this:
module.exports = {
name: 'kick',
decription: 'Kick command',
execute(message) {
if (!message.guild) return;
const member = message.mentions.members.first();
if (member) {
member
.kick()
.then(() => {
message.reply(`Successfully kicked ${member.user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("You didn't mention a member to kick!");
};
}
}
I have solved this problem by editing my code a bit. I also moved the code from my command handler to my main file. Here is the code for anyone who needs it.
else if(message.content.startsWith("-kick")) {
message.content.split("-kick ")[1]
if (!message.guild) return;
const member = message.mentions.members.first();
if (member) {
member
.kick()
.then(() => {
message.reply(`Successfully kicked ${member.user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("You didn't mention a member to kick!");
};
}
I only added the following piece of code:
message.content.split("-kick ")[1]
EDIT: I figured out what was wrong
const args = message.content.slice(prefix.length).split("/ +/");
I needed to remove the quotation marks at the end, so it is basically like this:
const args = message.content.slice(prefix.length).split(/ +/);
I'm working on this mute code:
if (cmd === "mute") {
if (
message.member.permissions.has(
"ADMINISTRATOR",
"KICK_MEMBERS",
"BAN_MEMBERS",
"MANAGE_ROLES"
)
) {
const target = message.mentions.members.first();
if (target) {
let mainRole = message.guild.roles.cache.find(
(role) => role.name === "{🍁}Scouts (VERIFIED)"
);
let muteRole = message.guild.roles.cache.find(
(role) => role.name === "Muted"
);
let memberTarget = message.guild.members.cache.get(target.id);
// timer mute
if (!args[1]) {
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted`);
return;
}
// manually mute
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(
`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`
);
setTimeout(function () {
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
}, ms(args[1]));
} else {
message.channel.send(" I can't mute this member !");
}
} else {
message.channel.send("You can't mute members !");
}
}
I'm trying to make it so that I won't have to keep changing
let mainRole = message.guild.roles.cache.find( (role) => role.name === "{🍁}Scouts (VERIFIED)" )"
instead, I'm trying to make this work on multiple servers/guilds without having to change it. How can I achieve that?
You may check if the role exists in that guild if it doesn't create one!
if(!muteRole) {
const muteRole =
message.guild.roles.create({
data: {
name: "Muted",
},
reason: 'Creating Mute role',
});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.createOverwrite(muteRole, {
SEND_MESSAGES: false,
MANAGE_MESSAGES: false,
READ_MESSAGES: false,
ADD_REACTIONS: false
});
});
memberTarget.roles.set([]); // removed all roles
memberTarget.roles.add(muteRole.id);
return message.channel.send("Mute role not found! Created Muted Role and muted user ");
}
This would allow your bot to create a role if none is present in that guild and the GuildMemberRolesManager#set([]) would remove all the roles from the user so you don't have to remove "specific" roles each time!
So I made this poll command that people without admin could make polls. To prevent spam, there is a verify step for everyone without admin. But when you react to the poll to verify it, it only works for the person making the poll. And not the admin that's supposed to check if it's not spam.
So when the admin reacts nothing happens but when the person that made the poll reacts to it, it verifies the poll and sends it to the main channel.
Code is down below is someone could help! 'Appreciate it!
const {Client, Collection, GuildMember, User, MessageEmbed, Message} = require("discord.js");
const ms = require("ms");
const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
module.exports.run = async(client, message, args, user, reaction) => {
var woord = '!poll'
var question = args.slice(0).join(' ')
var poll = new MessageEmbed()
.setTitle(`${message.author.username} wil een poll maken.`)
.setDescription(question)
.setColor('#eb8dd8')
.setFooter(`Poll gemaakt door: `+ message.author.username)
var success = new MessageEmbed()
.setDescription(question)
.setColor('#eb8dd8')
.setFooter("Poll started door: "+ message.author.username)
if(message.content.includes(woord)) {
message.delete({timeout:0})
}
if(!message.member.roles.cache.some(r => r.name === 'Barman')) {
if(message.channel.name.includes("🙇-poll")) {
if(args[0]) {
message.delete()
message.guild.channels.create(message.author.username, { permissionOverwrites:[
{
deny: 'VIEW_CHANNEL',
id: message.guild.id
},
{
allow: 'VIEW_CHANNEL',
id: message.author.id
},
],
}).then(channel => {
channel.send(poll).then(poll => {
poll.react('✅')
.then(() => poll.react('❌'));
})
})
} else {
message.delete()
}
}
} else {
var pollChannel = client.channels.cache.get('876531134702448701')
pollChannel.send(success).then(success => {
success.react('✅')
.then(() => success.react('❌'))
})
}
client.on('messageReactionAdd', (reaction, user) => {
const deleteChannel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username);
var pollChannel = client.channels.cache.get('876531134702448701')
if(reaction.emoji.name === '✅') {
if(message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username)) {
deleteChannel.delete()
.then(channel => {
pollChannel.send(success).then(success =>{
success.react('✅')
.then(() => success.react('❌'))
})
})
}
} if(reaction.emoji.name === '❌') {
if(message.guild.channels.cache.find(channel => channel.name.toLowerCase() === user.username)) {
deleteChannel.delete()
}
}
})
}
module.exports.help = {
name: "poll"
}
At the start of your function you can do this:
const questions = new Collection();
questions.set("What is the color of healthy grass?", "green");
questions.set("How many vowels are there in these letters: apple", "2");
const chosen = questions.randomKey()
await message.channel.send(`Please answer the question. This is to prevent spam. Make sure your spelling is correct. You have 30 seconds —> ${chosen}`)
try {
await message.channel.awaitMessages((m) => m.author.id === message.author.id && m.content.toLowerCase() === questions.get(chosen), {
time: 30000,
max: 1
})
} catch(err) {
return message.channel.send("You ran out of time to answer correctly!")
}
//code to make poll
Your awaitMessages syntax may be different on v13. You can also replace my questions, and add as many as you want!