I'm kinda new to coding discord bots and I have a problem. I want to have a ban command that would ban the mentioned user in the command or the user that has an ID that was provided in the command. For example:
&ban #User#0001 would ban User#0001
but
if the command looks like this:
&ban 123456789123456789 (let's say that's the ID of User#0001)
it would still ban User#0001 (as it is the user's ID).
I have this code, it works if I mention the user, but it doesn't work if I enter the ID.
const Discord = require('discord.js');
module.exports = {
name: 'testban',
description: "Executer will ban the mentioned user",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Can't ban that one, he also can ban")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban({reason: banReason})
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
The error I get when entering the ID is this:
message.guild.members.get is not a function
How could I make it ban the person even if I only provide the ID?
If you're using the newer versions of discord.js you need to use the cache, you just need to change it to this:
message.guild.members.cache.get(args[0])
Related
I recently made a discord command called -dm that basically DMs the user mentioned in the message. Something like: -dm #Omega Hello! and it would send "Hello!" to the user mentioned.
But some people find it annoying when they get pinged multiple times, so I want to know if there is a way I could use the USER ID instead of mentioning the user. That would make life a lot more easier. For whom it may concern, my code is given below.
const Discord = require('discord.js')
module.exports = {
name: 'dm',
description: 'DMs the person with the User ID mentioned',
execute(client, msg, args) {
if(!msg.member.permissions.has("ADMINISTRATOR")) return msg.channel.send("You cannot do that!")
//if(msg.author.id !== 'CENSORED') return msg.channel.send("You cannot do that!")
const user = msg.mentions.users.first()
if(!user) return msg.channel.send("That user ID doesn't exist OR that person isn't in the same server as me!")
const str = args.slice(1).join(" ")
user.send(str)
msg.channel.send("Message sent to the user!")
var dmLogger = new Discord.MessageEmbed()
.setTitle("DM Sent")
.setColor("RANDOM")
.addField("MESSAGE SENT BY", msg.author.tag)
.addField("MESSAGE SENT TO", user)
.addField("MESSAGE CONTENT", str)
.setTimestamp()
client.channels.cache.get('CENSORED_2.0').send(dmLogger)
}
}
You could add await message.guild.members.fetch(args[0]) but if you still want to keep the mentions thing you can just add that to your user variable.
const user = msg.mentions.users.first() || await msg.guild.members.fetch(args[0])
If you want only with user ID, remove the mentions part.
Revoking A Ban Using Code
So, I am making a moderation discord bot using VS Code and I have already set up a ban command. I want to make a unban command (revoking a ban) too so that the user can easily unban a user and not have to go into Server Settings to do it.
I know you can do it because I have been using another bot, GAwesomeBot, that is able to do it.
Link to GAwesomeBot: https://gawesomebot.com
I am a little new to Stack Overflow and this is my first question so pardon me if I am doing anything wrong.
Consider using GuildMemberManager#unban
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban
let guildMemberManager, toUnbanSnowflake;
guildMemberManager.unban(toUnbanSnowflake); // Takes UserResolveable as argument
First you want to define the user that you are unbanning.
Because the user is already banned you will have to mention the user by their ID and then unbanning them.
let args = message.content.split(/ +/g); //Split the message by every space
let user = message.guild.members.cache.get(args[1]); //getting the user
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }); //Unbanning the user
The full example:
//Define your variables
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = 'your-prefix-here';
//Add a message event listener
client.on('message', () => {
let args = message.content.split(/ +/g); //Split the message by every space
if (message.content.toLowerCase() === prefix + 'unban') {
let user = message.guild.members.cache.get(args[1]); //getting the user
if (!user) return message.channel.send('Please specify a user ID');
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }).then(() => message.channel.send('Success');
}
});
the remove role error
my code:
bot.on('message', message => {
let prefix = "t?";
let args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {
case 'mute':
let person = message.mentions.users.first(); message.guild.members.fetch(args[1])
if(!person) return message.reply("couldnt find member");
let mainrole = message.guild.fetch(role => role.name === "member");
let muterole = message.guild.fetch(role => role.name === "muted");
if(!muterole) return message.reply("couldn't find mute role");
let time = (args[2]);
if(!time) {
return message.reply("how long? <:Thonk:582005026470363137>");
}
person.removeRole(mainrole.id);
person.addRole(muterole.id);
channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`);
setTimeout(function(){
person.addRole(mainrole.id);
person.removeRole(muterole.id);
message.channel.send(`#${person.user.tag} has been unmuted.`);
}, ms(time));
break;
}
});
and it pops up and error that says remove Role is not a function
do anyone know how to solve these kinds of problem in discord
You are confusing GuildMember with User.
A user is a person on Discord, a GuildMemebr is a person on discord as pertaining to a specific guild. For example, you can DM a user or a guild member because direct messages don't have anything to do with guilds, but you can't remove a role from a user because a user isn't associated with a guild, there are no roles to remove.
So, you need to get message.mentions.members not message.mentions.users
The documentation for this is here in MessageMentions
I can't get the bot to make a invite on another guild the bot is in.
I've tried giving my bot the adminstrator role to make sure it has permissions.
if(msg.content.startsWith('-createinvite')) {
const args = msg.content.split(' ').slice(1)
if(!args[0])
var invitechannels = guild.channels.filter(c => c.members.get(bot.user.id).hasPermission("CREATE_INSTANT_INVITE")).first();
var guild = client.guilds.get(args[0]);
if (!guild) return msg.reply("The bot isn't in the guild with this ID.");
if(!invitechannels) return msg.channel.send('No Channels found with permissions to create Invite in!')
console.log(invitechannels)
invitechannels.random().createInvite().then(invite=> msg.channel.send('Found Invite:\n' + invite.code))
}
I've tried different kind of codes but I can't seem to get this to work.
if(msg.content.startsWith('-createinvite')) {
const args = msg.content.split(' ').slice(1)
let guild = client.guilds.get(args[0]);
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
let invitechannels = guild.channels.filter(c=> c.permissionsFor(guild.me).has('CREATE_INSTANT_INVITE'))
if(!invitechannels) return message.channel.send('No Channels found with permissions to create Invite in!')
invitechannels.random().createInvite()
.then(invite=> message.channel.send('Found Invite:\n' + invite.code))
}
You were verifying if the bot has permissions for a guild before getting the guild.
And this is not a thing c.members.get(bot.user.id).hasPermission("CREATE_INSTANT_INVITE")).first()
The command requires a reason to work, however, it still does not ban even if I mention someone and give a reason. It's like the command isn't recognized!
bot.on('message', async message => {
if (message.content == prefix + "ban") {
if (!message.member.roles.some(r => ["Administrator", "Co-owner"].includes(r.name)))
return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member)
return message.reply("Please mention a valid member of this server");
if (!member.bannable)
return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
var reason = args.slice(1).join(' ');
if (!reason) reason = "No reason provided";
await member.ban(reason);
}
});
Finally got it to work! This was my code at the end:
bot.on('message', message => {
let member = message.mentions.members.first();
if (message.content.startsWith(prefix + "ban")) {
if (!message.member.hasPermission('BAN_MEMBERS'))
return message.reply("Sorry, you don't have permissions to use this!");
if (!member)
return message.reply("Please mention a valid member of this server");
if (!member.bannable)
return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
// V This line has been changed V
var reason = message.content.split(' ').slice(2).join(' ');
if (!reason) return message.reply("Please specify a reason!");
member.ban(reason);
}
});
It was all because of the reason! Thanks to everyone who helped me, this opened doors for a lot more commands for me.
For the kick command, you have to put an argument as a reason. Like this:
var reason = args.slice(1).join(' ');
member.kick(reason);
This is just like the ban command in the second image.
If you need more help or clarification, ask me.
If this doesn't work, make sure your bot has a high enough role in the role hierarchy.