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
Related
My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.
I made a Discord.js Ban Command with reason and stuff however i overcome an error whenever i try to use it. Here is my code :
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user from the server by using mentioning them!',
guildOnly: true,
aliases: ['ban', 'banbanban'],
usage: `-ban <USER_MENTION> <OPTIONAL_REASON>`,
cooldown: 5,
async execute(message, args, client) {
const daidinevermantion = new MessageEmbed()
daidinevermantion.setTitle('Incorrect arguments provided!')
daidinevermantion.setDescription('Please Mention a user to ban ;-;. Make sure it a mention. The bot may not be able to ban users not in the server')
daidinevermantion.addField('Usage','``;ban <USER_MENTION> <OPTIONAL REASON>``')
daidinevermantion.addField('Example Usage', ';ban <#760773438775492610> Good Bot')
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send(daidinevermantion);
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/. Make sure you are mentioning the user and the user is in the server!');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban({ days: 7, reason: reason }).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Banned by', message.author)
.addField('Reason', reason)
.setFooter('Banned On:', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
Here whenever i send this command I this message in return "This user can't be banned. It is either because they are a mod/admin, or their highest role is higher than mine" regardless of whatever the case is whether its position is higher or lower. I'm a bit new to Discord.js please help me out thanks a lot!
You are getting that message because member.bannable is always false, and the reason for that is your bot doesn't have the required permissions to ban a user. Use this permission calculator and reinvite the bot to the server with required permissions i.e "Ban Members" or "Administrator".
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.
im trying to make a userinfo command right now on my discord bot. one of the fields is the time that the user joined the server.
heres my code
module.exports.run = async (Client, msg, args, UserDataBase, messages, commands_ran) => {
let user = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
if(!user) {
user = msg.author
}else {
user = user.user
}
const embed = new Discord.RichEmbed()
.setTitle('**User info**')
.setThumbnail(user.avatarURL)
.addField('Name:', user.username,true)
.addField('Tag:', `#${user.discriminator}`,true)
.addField('Date Joined:', user.createdAt)
.addField('Joined Server:', user.joinedAt)
msg.channel.send(embed)
}
it always returns Undefined in the final product
User objects don't have a joinedAt property because a User is not specific to any server. The representation of a user in a server is a GuildMember, which is what you're getting in the first line of your function.
You could just remove the part that forces it to be a User object and your code should work due to discord.js adding getters for all User properties on the GuildMember.
module.exports.run = async (Client, msg, args, UserDataBase, messages, commands_ran) => {
let user = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
const embed = new Discord.RichEmbed()
.setTitle('**User info**')
.setThumbnail(user.avatarURL)
.addField('Name:', user.username,true)
.addField('Tag:', `#${user.discriminator}`,true)
.addField('Date Joined:', user.createdAt)
.addField('Joined Server:', user.joinedAt)
msg.channel.send(embed)
}
user doesn't have any joinedAt property, so you will need to use GuildMember.
This can be obtained by member = msg.guild.member(user)
and then .addField('Joined at:' member.joinedAt)
I am coding a custom discord bot for my server and I ran into this issue. I want to add a role to a user that is not predefined. IE: I want to be able to &addrole #user anyrole and add that role to a user. Here is the code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
//!addrole #andrew anyrole
if(!message.member.hasPermission("MANAGE_MEMBERS")) return
message.reply("Sorry pal, you can't do that.");
let rMember = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if(!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("Specify a role!");
let gRole = message.guild.roles.find('name', any);
if(!gRole) return message.reply("Couldn't find that role.");
if(rMember.roles.has(gRole.id)) return message.reply("They already have
that role.");
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Congrats, you have been given the role
${gRole.name}`)
}catch(e){
message.channel.send(`Congrats to <#${rMember.id}>, they have been given
the role ${gRole.name}. We tried to DM them, but their DMs are locked.`)
}
}
module.exports.help = {
name: "addrole"
}