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
Related
const data = suggestedEmbed.embeds[0];
Hi, I'm having this error and I don't know why it is saying that the code above is the problem. Any solutions for this problem? Thank you for reading.
Code:
module.exports = {
category: "Utility",
description: "Accept valid suggestions!",
expectedArgs: "<messageID> <Reason>",
minArgs: 2,
guildOnly: true,
ownerOnly: true,
callback: ({message, args}) => {
const messageID = args[0]
const acceptQuery = args.slice(1).join(" ");
try{
const suggestionChannel = message.guild.channels.cache.get('834459599699443782');
const suggestedEmbed = suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(data.author.name, data.author.iconURL())
.setColor('GREEN')
.setDescription(data.description)
.addField("📊 Status ✅ Accepted! Expect this coming soon!", acceptQuery);
suggestedEmbed.edit(acceptEmbed);
const user = client.users.cache.find((u) => u.tag === data.author.name);
user.send("Your suggestion has been accepted! Thank you for this suggestion, expect this coming soon!")
} catch(err) {
console.log(err)
}
}
}
I've been making a suggestion command and I don't know what the current problem is, please help.
module.exports = {
name: 'suggestions',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestions!',
execute(message, args, cmd, client, discord){
const channel = message.guild.channels.cache.find(c => c.name === 'suggestions');
if(!channel) return message.channel.send('suggestions channel does not exist!');
}
}
Here's the error message:
TypeError: Cannot read property 'channels' of undefined
at Object.execute (C:\Users\MyName\Desktop\DiscordBots\commands\suggestions.js:7:39)
Here's my main file:
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"]});
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})
client.login('MYTOKEN');
Here's where I run execute() i think:
module.exports = (Discord, client, message) => {
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(command) command.execute(client, message, args, Discord);
}
Please try to define channel and then send message
client.channels.cache.get("CHANNELID").send(`TEST`);
this may be work;
module.exports = {
name: 'suggestions',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestions!',
execute(client, message, args, Discord){ // CHANGED
const channel = message.guild.channels.cache.find(c => c.name === 'suggestions');
if(!channel) return message.channel.send('suggestions channel does not exist!');
}
}
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);
})
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);
});
}
}
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]
}