How to ban with Discord.js? - discord.js

I have created a command to ban a user and I want it to prompt the user for a confirmation on whether or not they would like to ban the user, and then once they confirm, execute the ban.
I've tried to log where the problem is, but it gives me a blank error.
My code for the command:
const Discord = require('discord.js')
let target = arguments.shift()
let reason1 = arguments.join(" ");
const reason = reason1 || "Ohne Grund"
const banEmbed = new Discord.MessageEmbed()
.setTitle('🚫Ban')
.setDescription(`Bist du dir sicher, dass ${message.mentions.users.first()} gebannt werden soll?`)
.setColor('RED')
.addFields(
{ name: 'Reason', value: `${reason}`}
)
.setTimestamp()
.setFooter(message.guild.name, message.guild.iconURL())
message.channel.send(banEmbed).then(sentEmbed =>{
sentEmbed.react("βœ…")
sentEmbed.react("❌")
sentEmbed.awaitReactions((reaction, user) => user.id == message.author.id && (reaction.emoji.name == 'βœ…' || reaction.emoji.name == '❌'),
{ max: 1, time: 30000 }).then(collected => {
console.log(collected.first().emoji.name)
if (collected.first().emoji.name == 'βœ…') {
console.log(target)
console.log(reason)
target.ban({ days: 0, reason: reason })
message.reply('Member wird gebannt.');
}
if (collected.first().emoji.name == '❌') {
message.reply('Member wird nicht gebannt.');
}
}).catch(() => {
message.reply('timeout');
console.error();
});
});
and this is the part where it fails, everything else is okay:
sentEmbed.awaitReactions((reaction, user) => user.id == message.author.id && (reaction.emoji.name == 'βœ…' || reaction.emoji.name == '❌'),
{ max: 1, time: 30000 }).then(collected => {
console.log(collected.first().emoji.name)
if (collected.first().emoji.name == 'βœ…') {
console.log(target)
console.log(reason)
target.ban({ reason: reason })
message.reply('Member wird gebannt.');
}
Console Output:
The client is ready!
βœ…
<#!664493064336965634>
test
Please help!

What you are doing here won't work. Why? You are getting the first element of the array which is a string even if you mention someone it will look like <#4242424242424> which doesn't have the method .ban
let target = arguments.shift()
You should find that member in the guild either you can get it by the mentions property
let target = message.mentions.members.first() || message.guild.members.cache.get(arguments.shift());

Related

When i try to create a role it gives me an error (discord.js)

So i am trying to make a command that mute a member. I want my bot to check if there is role name Muted and if there is not, to create a role for Muted members.
This is the code:
module.exports = {
name: 'mute',
description: 'mutes a member',
execute(message, args, Discord, bot) {
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted')
if(!mutedRole) {
Guild.roles.create({
data: {
name: 'Muted',
color: 'BLACK'
}
})
}
}
}
and the error is this:
C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\mute.js:10
Guild.roles.create({
^
TypeError: Cannot read property 'create' of undefined
I don't think you should create a role via code. I think you should create a role in your Discord server (like actually just making one without code). Download the ms package. (npm i ms) Then, paste this code in:
const ms = require('ms');
module.exports = {
name: "mute",
description: "Mutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
if (!args[1]){
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted.`);
return;
}
if (isNaN(args[1]) || !args[1] === ' '){
message.channel.send("Please enter a real number! (If you have a space after the username and you don\'t want to set a time limit, delete the space. YOU HAVE TO.)");
return;
}
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("Can't find that member!");
}
}
}
Thanks to CodeLyon for this code. Hope this works for you! It even includes a time limit.
format 1: !mute #User
format 2: !mute #User 1000 (1000 can be changed, just make sure it's in milliseconds)
module.exports = {
name: "unmute",
description: "Unmutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unmuted.`);
} else {
message.channel.send("Can't find that member!");
}
}
}
format: !unmute #User
Remember, this code only works if you have a role Member and a role Muted. So, in your server, add the role Member to everybody and add a role Muted (not to everybody).
Hope this works! If there's any need for clarification, please tell me in the comments.

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.

SlowMode for one person is possible ? discord.js

I would like to know if it is possible to do some sort of "SlowMode" for a specific person on Discord.
The reason is that I have a "spammer" friend, and I would like to calm him down with a command that might slow him down when he speaks for "x" secondes.
So I would like to know if this is possible? and if yes, how?
Thank you for your kindness =) (and sorry for this english i use GoogleTraductor)
Here's how I'd do that.
let ratelimits = [];
client.on("message", (msg) => {
// APPLYING RATELIMITS
const appliedRatelimit = ratelimits.find(
(value) =>
value.user === msg.author.id && value.channel === msg.channel.id
);
if (appliedRatelimit) {
// Can they post the message?
const canPostMessage =
msg.createdAt.getTime() - appliedRatelimit.ratelimit >=
appliedRatelimit.lastMessage;
// They can
if (canPostMessage)
return (ratelimits[
ratelimits.indexOf(appliedRatelimit)
].lastMessage = msg.createdAt.getTime());
// They can't
msg.delete({ reason: "Enforcing ratelimit." });
}
// SET RATELIMIT
if (msg.content === "!ratelimit") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// You can change these values in function of the received message
const targetedUserId = "whatever id you want";
const targetedChannelId = msg.channel.id;
const msRateLimit = 2000; // 2 seconds
// Delete existant ratelimit if any for this user on this channel
ratelimits = ratelimits.filter(
(value) =>
!(
value.user === targetedUserId &&
value.channel === targetedChannelId
)
);
// Add ratelimit
ratelimits.push({
user: targetedUserId,
channel: targetedChannelId,
ratelimit: msRateLimit,
lastMessage: 0,
});
}
// CLEAR RATELIMITS
if (msg.content === "!clearRatelimits") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// Clearing all ratelimits
ratelimits = [];
}
});

Discord.js - Command that after 10 seconds if you not typing something it will tell you you run of time

I'm trying to do bot in js that when users do the command: !mugg #someone //someone is another user mention.
it will say: The Mugger is approaching ${user}, and then after 10 seconds if the user that got mugged won't type !killmugger he will get the message The Mugger mugged ${user} but if he does he will get the message: The mugger didn't mug ${user}.
This is what i tried to do: (I tried to play with if and roles)
bot.on("message", (message) => {
let args = message.content.substring(PREFIX.length).split(" ");
bot.user.setActivity("!mugg #someone");
switch (args[0]) {
case "mug":
const user = message.mentions.members.first();
let Role = message.guild.roles.cache.get("772195872133742634");
if (user) {
const member = message.guild.member(user);
if (member) {
message.reply(`The Mugger is approaching ${user}`);
user.roles.add("Role");
} else {
message.reply("That user isn't in this server.");
}
} else {
message.reply("You need to mention a user");
}
setTimeout(function () {
if (!message.mentions.roles.has("772195872133742634")) {
message.channel.send(`The Mugger mugged ${user}`);
user.roles.remove(Role);
}
}, 10000);
break;
case "killmugger":
const user1 = message.mentions.members.first();
let Role1 = message.guild.roles.cache.get("772195872133742634");
if (!message.mentions.roles.has("772195872133742634")) {
message.channel.send(`The Mugger not mugged ${user1}`);
user1.roles.remove(Role1);
}
}
});
Welcome,
Like #Saddy mentioned you can use awaitMessages, in the following way you don't need to verify if the user has the needed roles.
message.channel.send(`The Mugger mugged ${user}`);
//filter where m is message and the author needs to be the user you mentioned and the content needs to be equal to killmugger or you can change it to !killmugger
const filter = m => m.author.id == user!.id && m.content.toLowerCase() == "killmugger"
//awaitMessage function max: maximum messages, time: in milliseconds and the errors in this case we just need time to make sure that after
//10s it will return the message if he doesn't write killmuger in time
message.channel.awaitMessages(filter, { max: 1, time: 10000, errors: ['time'] }).then(m => {
return console.log("He got it in time")
}).catch(() => {
return message.channel.send(`The Mugger not mugged ${user1}`);
})

Discord.js channelUpdate event, ignore certain channels

Hello Stackoverflow community. I'm quite curious, regarding the channelUpdate event in Discord.js, is it possible to ignore some channels but log the rest?
bot.on("channelUpdate", async (oldChannel, newChannel) => {
// Get stat channel IDs
let totalUsers = oldChannel.guild.channels.get('667335552558956554');
let onlineUsers = oldChannel.guild.channels.get('667335645894541331');
let totalBots = oldChannel.guild.channels.get('667337560179343374');
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
if (totalUsers || onlineUsers || totalBots) return;
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = "None";
if (!guildsChannel || !guildsChannel.available) return;
let types = {
"text" : "Text channel",
"voice" : "Voice channel",
"null" : "None"
};
const logchannel = channel.guild.channels.find(channel => channel.name === "server-logs")
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor("#ffc500")
.setDescription("Channel name updated.")
.addField("Old channel name", `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField("New channel name", `\`${newChannel.name}\``, true)
.addField("Channel type", `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField("Channel category", `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} πŸ”₯`)
.setTimestamp()
logchannel.send(channelNameUpdateEmbed).catch()
}
});
Those marked as so called "Stat channels", is it possible to ignore those? Else log channels will get flooded every time a member goes online or offline
Thanks in advance!
Sure, you can create ingoreChannel arr and check if channel in ignore arr.
Like this:
bot.on('channelUpdate', async (oldChannel, newChannel) => {
const ignoreChannels = ['667335552558956554', '667335645894541331', '667337560179343374'];
// Get stat channel IDs
if (ignoreChannels.includes(oldChannel.id)) return;
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = 'None';
if (!guildsChannel || !guildsChannel.available) return;
let types = {
text: 'Text channel',
voice: 'Voice channel',
null: 'None',
};
const logchannel = channel.guild.channels.find(channel => channel.name === 'server-logs');
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor('#ffc500')
.setDescription('Channel name updated.')
.addField('Old channel name', `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField('New channel name', `\`${newChannel.name}\``, true)
.addField('Channel type', `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField('Channel category', `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} πŸ”₯`)
.setTimestamp();
logchannel.send(channelNameUpdateEmbed).catch();
}
});

Resources