Discord.js | Cannot read property 'displayName' of undefined - discord

I am making a discord bot for a friend and everything worked until i tried to make an unban command. when i tried to unban someone it did not work. then i looked at the error. it displayed:
TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Unhandled promise rejection: TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
this is my code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
console.log(message.content);
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length >= 1) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
message.channel.send(embedMsg);
}
if (args.length < 2) {
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
newargs = "";
for (var i = 1; i < args.length; i++) {
newargs += (args[i] + " ");
}
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
}
does anyone know what i am doing wrong?

It says in the discord.js's official docs that the unban method returns a member object https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=unban
The reason why it says 'undefined' is because the member object you are trying to access is not in the server/guild. So, therefore you need add a reference to the member object that the method returns:
message.guild.unban('some user ID').then((member) => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}

Unbun method return a user promise, so user dont have property displayName, you need use .username
And you can use user.id for unban, so right way will be let member = message.mentions.members.first() || args[0]
This check doing wrong, because its not stop code execute
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
Amm and whats this part code doing? Why its duplicate?
if (args.length < 2) {
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
The edited code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first() || args[0]
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
let newargs = args.splice(1,args.length).join(' ')
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
}
}

Related

How to fix this.uuid is not a function discord.js

Hello actually I wanted to make minecraft playerinfo command but I wanted it and I got it on github it was a bit old but I tried to convert it to discord.js v14 code. But I got this error.
TypeError: this.getUuid is not a function
Can you help me please heres the original code: https://github.com/Jystro/Minecraft-info-bot/blob/master/commands/player.js
const mojang = require('mojang-api');
const https = require('https');
const {
EmbedBuilder
} = require('discord.js');
module.exports = {
name: 'playerinfo',
description: 'Diplays player\'s name, uuid, skin, cape and name history',
run: async (client, message, args) => {
//check that a value is sent
if(!args.length) {
message.reply('please specify the player\'s uuid');
return;
}
let uuid = args[0]
//get uuid
this.getUuid(args[0], (err, uuid) => {
if(err) {
message.channel.send('An error occurred. This might be because the player does not exist');
return;
}
//check that uuid exists
mojang.profile(uuid, (err, resp) => {
if(err) {
message.reply('that player\'s uuid does not exist');
return;
}
//get name history
mojang.nameHistory(uuid, (err, resp1) => {
if(err) {
message.reply('there was an error trying to retrieve the data');
console.log(err);
return;
}
let nameHistory = [];
resp1.forEach(element => {
nameHistory.push(element.name);
});
nameHistory = nameHistory.join(', ');
//create embed message
const embedMessage = new EmbedBuilder()
.setColor('Random')
.setTitle(resp.name)
.setDescription(resp.name + "'s profile")
.setThumbnail('https://crafatar.com/avatars/' + resp.id + '.png?overlay')
.addFields(
{
name: 'Name',
value: resp.name
},
{
name: 'UUID',
value: resp.id
},
{
name: 'Skin',
value: 'https://crafatar.com/skins/' + resp.id + '.png'
})
.setImage('https://crafatar.com/renders/body/' + resp.id + '.png?overlay')
//check if cape exists
let cape = 'https://crafatar.com/capes/' + resp.id + '.png';
const req = https.request(cape, res => {
if(res.statusCode == 200) {
embedMessage.fields.push({ name: 'Cape', value: cape });
}
embedMessage.fields.push({ name: 'Name history', value: nameHistory });
//send embed
message.channel.send({ embed: embedMessage });
});
req.on('error', err => {
console.log(err);
message.reply('there was an error while retrieving the cape');
})
req.end();
});
});
})
},
//function to get uuid from uuid/name
getUuid(value, cb) {
let error = false;
let regex = /^[a-f0-9]{32}$/i //regex for uuids
if(!value.match(regex)) {
mojang.nameToUuid(value, (err, resp) => {
if(err || !resp.length) {
error = true;
cb(error, null);
return;
}
cb(error, resp[0].id);
});
}
else { cb(error, value); }
}
}
The issue is your usage of the this keyword and arrow functions.
The main takeaway is this:
Arrow functions don't redeclare this, while anonymous functions do.
This means that when you call the run() method somewhere else in the code, the this keyword in the run method will refer to whatever this is in the current context of where it was executed, which isn't what you want.
To redeclare this to your object, you should rewrite your arrow function as an anonymous function.
module.exports = {
run: async function(client, message, args) {
// you can now safely use `this` in this method
}
}

Discord.js cannot read property 'content' of null

Hello guys i try to do command "warns" and i can't fix error can you help me please?
I know the problem is in "if(data.content.length)" and if i remove ".content.length" and use command the bot says "User has not warns" but i have.
Code:
const db = require('../warns')
const { Message, MessageEmbed } = require('discord.js')
module.exports.run = async (_client, message, args) => {
if(!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('You don\'t have permissions to.')
const user = message.mentions.members.first() || message.guild.members.cache.get(args[0])
if(!user) return message.channel.send('User not found.')
const reason = args.slice(1).join(" ")
db.findOne({ guildid: message.guildid, user: user.user.id}, async(err, data) => {
if(err) throw err;
if(data.content.length){
var warny = new MessageEmbed()
.setTitle(`${user.user.tag} warns`)
.setDescription(
data.content.map(
(w, i) =>
`${i + 1}. | Moderator: ${message.guild.members.cache.get(w.moderator).user.tag}\nReason: ${w.reason}`
))
.setColor('RANDOM')
message.channel.send(warny)
} else {
message.channel.send('User has not warns')
}
})
}
module.exports.help = {
name: 'warns'
}
Error:
(node:5564) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'content' of null
at C:\Users\cyber\Desktop\CzikiBot\commands\warns.js:11:17

discord.js Welcome message

yea hello I'm making a discord.js bot and I have this code currently and it REFUSES to send a message (it doesn't error either
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
let data = await canva.welcome(member, { link: "https://i.pinimg.com/originals/f3/1c/39/f31c39d56512dc8fbf30f9d0fb3ee9d3.jpg" })
const attachment = new discord.MessageAttachment(
data,
"welcome-image.png"
);
client.channels.cache.get(chx).send("Welcome to our Server " + member.user.username, attachment);
});
and then i have welcome.js with this code but it aint sending and i cant figure out why ...
const db = require("quick.db")
module.exports = {
name: "setwelcome",
category: "moderation",
usage: "setwelcome <#channel>",
description: "Set the welcome channel",
run: (client, message, args) => {
let channel = message.mentions.channels.first()
if(!channel) {
return message.channel.send("Please Mention the channel first")
}
//Now we gonna use quick.db
db.set(`welchannel_${message.guild.id}`, channel.id)
message.channel.send(`Welcome Channel is set to ${channel}`)
}
}```
just a guess that your not checking for undefined on CHX
if (chx === null && chx === undefined) {
return;
}
This is my modified code from my discord bot (just to keep it general).
this.client.on('ready', () => {
if(botChannelID){
this.client.channels.fetch(botChannelID).then(ch => {
ch.send(`Welcome message here.`);
}).catch(e => {
console.error(`Error: ${e}`);
});
}
//Other stuff. Blah blah blah...
});

Discord.js command handler problems

I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})

TypeError: Cannot read property 'forEach' of undefined discord.js

I'm having this issue: TypeError: Cannot read property 'forEach' of undefined on my discord bot after adding aliases. It worked before I added aliases to it so I'm assuming the problem is somewhere around there. I can't seem to find where the problem is originating from so any help would be appreciated!
code:
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
let profile = require("./profiles.json");
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log("Couldn't find commands");
return;
};
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
});
});
});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online`);
bot.user.setActivity("$ Made by xkillerx15");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length)) || bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot,message,args);
if(!profile[message.author.id]){
profile[message.author.id] = {
coins: 0
};
}
let coinAmt = Math.floor(Math.random() * 15) + 1;
let baseAmt = Math.floor(Math.random() * 15) + 1;
if(coinAmt === baseAmt){
profile[message.author.id] = {
coins: profile[message.author.id].coins + coinAmt
};
fs.writeFile("./profiles.json", JSON.stringify(profile), (err) => {
if(err) console.log(err)
});
}
});
bot.login(botconfig.token);
exact error:
TypeError: Cannot read property 'forEach' of undefined
at jsfile.forEach (C:\Users\Jordy\Desktop\jbot\index.js:23:28)
at Array.forEach (<anonymous>)
at fs.readdir (C:\Users\Jordy\Desktop\jbot\index.js:19:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
your problem is that aliases is undefined which means is not an object so you can't use forEach
there is one possibility:
commands file should contains aliases inside help object.
so it should something like this
exports.help = {
aliases:[...props]
}

Resources