so I've been trying to make a bot for Discord, and my kick and ban function work, but the permissions don't work. Tried to repair it somehow, but it got worse and it was going into an infinite loop.
bot.on('message', message => {
if (message.member.hasPermission("ADMINISTRATOR")) {
if (!message.guild) return;
if (message.content.startsWith('+kick')) {
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!");
}
}
}
});
This is my code. I want to make it go to further messages only if you have kick members permission. There are many codes on the internet but they seem to break my code somehow.
Related
I made my bot etc but I would like to make it so that the bot sends a dm when it ban a person I do not find it has been 3 hours that I search but without success
exports.run = (client, message, args) => {
if (message.member.hasPermission('BAN_MEMBERS')) {
const user = message.mentions.users.first();
let reason = args.slice(1).join(' ');
if (!reason) reason = "No reason provided";
if (user) {
const member = message.guild.member(user);
user.send("You we're banned from **__" + message.guild.name + "__** for **__" + reason + "__**")
.catch(() => message.reply("Unable to send message to user"))
.then(() => member.ban({
reason: "BANNED!"
}))
.catch(err => {
message.reply('I was unable to ban the member');
console.error(err);
});
if (member) {
member
.ban({})
.then(() => {
message.reply(`Successfully banned **__${user.tag}__** for **__${reason}__**`);
})
.catch(err => {
message.reply('I was unable to ban 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 ban!");
}
} else {
message.reply('you don\'t have permission to ban members!')
}
}
There's a few flaws here.
Firstly, message.guild.member() is not a method. You should instead use message.mentions.members.first(); instead of message.mentions.users.first(), then access the User object via GuildMember.user (in your case, user.user, unless you rename the variable) if you need to. You could use guild.members.fetch() but this is much easier.
Secondly, you try to message, if you can't you don't bother banning. Which means if a user blocks your bot, they can prevent getting banned by it. So to fix this, with your current code, just do
user.send("message")
.catch(err => {
message.reply("User could not be messaged");
});
user.ban( {reason: "BANNED!"} )
.catch(err => {
message.reply("User could not be banned");
});
If it continues to error after this, please respond with the error your receive.
So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
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');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.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');
// Log the error
console.error(err);
});
}
}
The line in particular is line 19. As soon as I add .then It wants me to add a bunch of stuff that breaks the code entirely. VSC also lists it as dead code as soon as I add .then.
name: 'ban',
description: 'Ban a user',
execute(message, args) {
if (message.member.hasPermission("BAN_MEMBERS")) {
// Ignore messages that aren't from a guild
if (!message.guild) return;
//DM's user that they have been banned
async function banBefore(message, args) {
let member = message.guild.members.cache.get("id") || message.guild.members.cache.get(args[0])
// to send a message to the user
if (member !== undefined) {
await member.user.send("You have been banned from", message.guild.name)
}
await member.ban()
}
//Right Below Here.
.then(() => {
//Ban's User
const user = message.mentions.users.first();
message.guild.members.ban(user);
})
.then(() => {
//Notifies that user was banned
message.reply("Banned Mentioned User. User has been notified");
})
} else {
message.reply("You don't have permission to ban members!")
}
}
}```
Thanks in advance.
You should use:
name: 'ban',
description: 'Ban a user',
execute(message, args) {
if (message.member.hasPermission("BAN_MEMBERS")) {
// Ignore messages that aren't from a guild
if (!message.guild) return;
let member = message.guild.members.cache.get("id") || message.guild.members.cache.get(args[0])
// to send a message to the user
if (member !== undefined) {
await member.user.send("You have been banned from", message.guild.name)
}
member.ban().then(() => {
//Notifies that user was banned
message.reply("Banned Mentioned User. User has been notified");
})
} else {
message.reply("You don't have permission to ban members!")
}
}
}
I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and message.channel.send("now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.
I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.
I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});
I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".