How to log into the ban section of discord using discord.js v12? - javascript

I'm working on my ban command and it's fully functional, but I was wondering, how I would log the ban reason into the ban section of discord (example in the attachment)? My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: "Mentioned user will be banned",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.members.first()) || message.guild.members.cache.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Invalid Permissions a")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban
console.log(`Ban reason = ${banReason}`)
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
Any help? Thanks :)

It's actually quite easy, just add ({reason: banReason}) after the User.ban part, making it:
User.ban({reason: banReason})
That should log it there properly :)

You can use the reason property of the options parameter in the GuildMember.ban() method:
User.ban({ reason: 'real life danger' })
.then(member => console.log(`${member.name} was banned.`))
.catch(console.error)
Also, in your code, there's no reason for using the Guild.member() method when defining User. Guild.member(user) is used to turn a User object into a GuildMember object.
However, MessageMentions.members.first() already returns a GuildMember object, making it obsolete.

Related

Discord.js Dev detector

I am making a discord bot and I have a few dev only commands. However, the system I use to detect if someone is a bot developer doesn't work.
My code:
const { MessageEmbed } = require("discord.js");
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return message.channel.send("Slow down, poke. This is devs only, poke?"); // return if author isn't bot owner
let user = message.mentions.users.first();
if (!user) return message.channel.send("Send money to who?");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply("That isn't a valid amount.");
let data = client.eco.addMoney(user.id, parseInt(amount));
const embed = new MessageEmbed()
.setTitle(`You'll be rich! The money has been added.`)
.addField(`User`, `<#${data.user}>`)
.addField(`Balance Given`, `${data.amount} 💸`)
.addField(`Total Amount`, data.after)
.setColor("#f54242")
.setThumbnail(user.displayAvatarURL)
.setTimestamp();
return message.channel.send(embed);
}
exports.help = {
name: "addmoney",
aliases: ["addbal"],
usage: `addmoney #user <amount>`
}
I shouldn't have received the devs only message, but when I tested in discord, I did.
Thought I'd just make this an answer than a comment, as I've had time to test.
This works, but it may be related to how you store your IDs in the admin array.
.includes() is type sensitive, so a string wont match a number. Discord IDs are a string, so your array has to match it.
Example:
const admins = [96876194712018944];
console.log(admins.includes("96876194712018944")); // false

TypeError: message.author is not a function

For this piece of code, I aim for the author of the message that sent the ban command to be checked for whether they have the permissions necessary to ban the member, instead of instantly being allowed to, however I am unsure of what the const mod should be equivalent to to do so. Any help would be appreciated, thanks.
module.exports = {
name: 'ban',
description: "This command ban a member!",
execute(message, args) {
const target = message.mentions.users.first();
const mod = message.author();
if (mod.hasPermission('BAN_MEMBERS')) {
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.ban();
message.channel.send("User has been banned");
}
} else if (mod.hasPermission(!'BAN_MEMBERS')) {
message.channel.send(`You couldn't ban that member either because they don't exist or because you dont have the required roles!`);
}
}
}
As it says, Message.author is not a function. It is a property. You access it without the brackets
const mod = message.author
Another problem you may get is you can't get permissions. You will need Message.member for that
const mod = message.member

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

discord.js Cant use command with user ID

I'm making a command that rickrolls the mentioned user by sending them a dm and when i try to use it by mentioning someone using their ID it dosent work and sends the error message i added saying: The mentioned user is not in the server
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
const BaseCommand = require('../../utils/structures/BaseCommand');
module.exports = class RickrollCommand extends BaseCommand {
constructor() {
super('rickroll', 'fun', []);
}
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You really thought i was boutta rickroll myself? AINT NO WAY CHEIF');
const rickrollEmbed = new Discord.MessageEmbed()
.setTitle("You've Been Rickrolled!")
.setThumbnail('https://i1.wp.com/my-thai.org/wp-content/uploads/rick-astley.png?resize=984%2C675&ssl=1')
.setDescription('Rick astley sends his regards')
.setColor('#FFA500');
await mentionedMember.send('https://tenor.com/view/dance-moves-dancing-singer-groovy-gif-17029825')
await mentionedMember.send(rickrollEmbed)
.then(() => {
message.channel.send("Successfully rickrolled the user.");
})
.catch(err => {
message.channel.send('I was unable to rickroll the user.');
});
}
}
The wierd part is it only works with my ID and not any other user's ID.
I think the problem is, that you are using the cache and not the guilds member manager. Therefore, when no other user is cached it will only work with your ID since you are the one sending the message => getting loaded into the cache.
Try this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}
I don't know for sure, but it might also be a bit more optimized if you still prefer the cache, but just use the member manager as an additional backup, like this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first()
|| message.guild.members.cache.get(args[0])
|| await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}

Discord js no role added

Hi I am following a tutorial on Youtube but I can't figure out why it's not working. Can someone explain to me why it isn't working?
There are no errors in the console but the role doesn't get added
Since you're using discord.js^12.x module, I can still see you use member.removeRoles() and member.addRoles(), which are deprecated. And also, the member variable you made was a user property not a guildMember property. Try to follow the code below:
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'coloradd',
description: 'Give You Your Color',
execute(message, args, client) {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const colors = message.guild.roles.cache.filter(c => c.name.startsWith('#'))
let str = args.join(' ')
let role = colors.find(role => role.name.slice(1).toLowerCase() === str.toLowerCase());
if (!role) {
return message.channel.send('That color doens\'t exist')
} try {
const member = message.member; // Use `message.member` instead to get the `guldMember` property.
// `addRoles()` and `removeRoles()` are deprecated.
member.roles.remove(colors);
member.roles.add(role);
message.channel.send('Your Have Received Your Color !')
} catch (e) {
let embed = new Discord.MessageEmbed()
.setTitle('Error')
.setColor('RED')
.setDescription('There is an error with the role Hierarchy Or my permissions. Make Sure I am above the color roles')
return (embed)
}
}
}
Visit these guides to help you understand more about the subject:
Discordjs.guide - Guide - Changes from v11 to v12
Discordjs.guide - Guide - Adding a role to a guildMember
Discord.js.org - Docs - guildMember Property
Discord.js.org - Docs - User Property

Categories

Resources