Im trying to make a command with in my Discord bot to make unban a person. When I finnished the code I got an error. The error is Cannot read properties of undefined (reading 'fetchBans'). The code I use to make it is
message.guild.cache.fetchBans().then(async bans => {
if (bans.size === 0) return message.channel.send("No one is banned on the server!")
let bannedUser = bans.find(ban => ban.user.id == userID)
if (!bannedUser) return message.channel.send("This user isn't banned!")
await message.guild.members.unban(bannedUser.user, reason).catch(err => {
return message.channel.send("Something went wrong!")
}).then(() => {
let embed = new MessageEmbed()
.setColor("GREEN")
.setTitle(`Member unbanned!`)
.setDescription("")
.setTimestamp()
.setFooter(this.client.user.username)
embed.addField(`member = ${target.username}`, `reason = ${reason}`, false)
message.channel.send({embeds: [embed]});
if (row[0].logs_channel != null) this.client.channels.cache.get(row[0].logs_channel).send({embeds: [embed]})
message.delete()
})
The line where it goes wrong is this line:
message.guild.cache.fetchBans().then(async bans => {
When I run this command it will give the error. I also tried to do something else. The code i tried else for that line is:
message.guild.fetchBans().then(async bans => {
This line also gave an error that says: TypeError: message.guild.fetchBans is not a function.
I don't know what i can do about this. I hope somebody can help me.
Node.js version: 16.9.1
discord.js version: 13.1.0
According to the documentation there is no fetchBans on Guild. Maybe you're looking for message.guild.bans.fetch().
It's also worth noting that message.guild is nullable - if the message was a direct message (not sent in a guild) it will be null.
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.
This is my discord reject code:
client.on('message', msg => {
if (msg.channel instanceof Discord.DMChannel && msg.author.id !== "828093594098204702") {
const Reject = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle('Error')
.setDescription('This command can only be used in the server.')
msg.author.send(Reject);
}
})
This is the error I'm getting:
const member = msg.guild.members.cache.get(msg.author.id);
^
TypeError: Cannot read property 'members' of null
at Client.<anonymous>
How can I fix this?
(v13)
I know, that you are using messages, but if you will you'll change your mind and will start using slash commands, use if (!interaction.guild) return;, this will disable slash commands in DMS. Also you can add interaction.followUp to return a message.
client.on("message", message => {
if(message.author.bot
|| message.channel.type === "dm") return;
// your code here
}
this is what I use to filter out bots and dms.
i try to mention a member on my server discord and with this it's create a webhook with his username and avatarURL but it's not working, it's tell me my usermentioned don't have displayName
My code:
if (cmd === "say")
{
message.delete()
let usermentioned = message.mentions.members.first();
let msg = args.slice(1).join(" ");
message.channel.createWebhook(usermentioned.displayName,
usermentioned.user.displayAvatarURL).then(wb =>
{
var Hook = new hookcord.Hook()
.setLink(`https://discordapp.com/api/webhooks/${wb.id}/${wb.token}`)
.setPayload({
'title': usermentioned.displayName,
'avatar': usermentioned.user.displayAvatarURL,
'content': msg
})
.fire()
.then(function(response)
{
wb.delete();
})
.catch(function(e) {})
})
}
The error:
message.channel.createWebhook(usermentioned.displayName, usermentioned.user.displayAvatarURL).then(wb =>
^
TypeError: Cannot read property 'displayName' of undefined
at first you shoud try to run with debugger and track your variable usermentioned. Or make output this variable to console. It give to you information about structure of user's profile. May be you get wrong level of profile
Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...
const Discord = require ("Discord.js")
exports.exec = async (client, message, args) => {
const bug = args.slice().join(" ");
if (!args[0]) return message.channel.send(`${message.author}\` Please right, in as much detail about the bug\``);
const channel = client.channels.get('498750658569306123')
const embed = new Discord.RichEmbed()
.setAuthor(message.author.tag, message.author.avatarURL)
.setColor(0)
.setDescription(bug)
.setTimestamp()
.setFooter(`Suggestion by ${message.author.tag} from ${message.guild.name}`)
channel.send(embed)
Error thrown back is:
TypeError: Cannot read property 'send' of undefined
at Object.exports.exec (C:\Users\Cake\Peepo\modules\help\bugreport.js:14:11)
Everything seems to work fine.. I'm unsure how "send" is undefined? Someone care to explain?
Try doing this to find your report channel.
let channel = message.guild.channels.find(c => c.name === "report-channel-name-here");
channel.send(embed);
if that fails, make sure that your bot can access the channel.