discord.js UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined - javascript

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) ...

Related

Does fetching embeds through messages from msg.reference.messageID not work?

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn't a thing. Is there anything wrong with my code?
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.
The error reads TypeError: Cannot read properties of undefined (reading '0'), and when I remove the [0], it's undefined. This whole thing is in a module.exports.run, if that helps.
module.exports.run = async (client, msg, args) => {
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
if (args.length === 5) {
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(await msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
//do things with fetchedMsg
You can get the MessageEmbed() same as normal Message using:
const messages = args[0]
if(!messages) return message.reply("Provide an ID for message.")
if(isNaN(messages)) return message.reply("Message ID should be
number, not a letter")
message.channel.messages.fetch(`${messages}`)
.then(msg => {
console.log(msg.content) || console.log(msg.embeds)
})
You can find more here about fetching a message

Discord bot failing to call username of person who calls it

I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.

Delete the latest message of the bot in dms

I have a command where the bot sends a message to a specific user trough private messages. Now I want that I can delete the last message of the bot in DMs when there is like an error or something.
What I come up with is this:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
execute(message, args) {
const mentionedMember = message.mentions.members.first().id
const User = client.users.fetch(mentionedMember)
try {
if (!mentionedMember) {
return respond('', 'Bitte erwähne einen Nutzer.', message.channel)
}
User.dmChannel.messages.fetch( {limit: 1} )
.then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete()
});
} catch (error) {
console.error('an error has occured', error);
}
}
}
The error that I'm getting now is:
TypeError: Cannot read property 'messages' of undefined
And yes, I have direct messages with the bot.
Anyone knows what I did wrong?
There are a couple of errors. First, users.fetch and dmChannel.messages.fetch both return a promise, so you'll need for them to be resolved.
In your code above, User is a pending Promise that has no dmChannel property. As it has no dmChannel prop (i.e. it's undefined), you can't read its messages property and you will receive TypeError: Cannot read property 'messages' of undefined.
After you fixed these problems with fetch, there could be another error with the dmChannel. Sometimes (or most of the times?), user.dmChannel returns null. To avoid this, you can create a DM channel first using the createDM() method. It also returns a promise, so you will need to resolve it first :)
Check out the working code below:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
async execute(message, args) {
const mentionedUser = message.mentions.users.first();
if (!mentionedUser)
return respond('', 'Bitte erwähne einen Nutzer.', message.channel);
const user = await client.users.fetch(mentionedUser.id);
const dmChannel = user.dmChannel || (await user.createDM());
try {
const messages = await dmChannel.messages.fetch({ limit: 1 });
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete();
} catch (error) {
console.error('an error has occured', error);
}
},
};

Discord Embed made my code stop working? What is happening?

I have been trying to fix this error for hours now, but I can't find out why it's happening. It doesn't even send the error message added to the code. When I try to use the command, it sends nothing in chat, and just spams the console with errors. It did all of this when I added the error embed. Here's my code:
if(!message.author.bot) {
if(message.member.roles.cache.some(r => r.name === "Admin") || message.member.roles.cache.some(r => r.name === "Mod")){
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
let reason = args.slice(1).join(' ');
if(!reason) reason = "No reason provided";
let successkick = new Discord.MessageEmbed()
successkick.setTitle("SUCCESS")
successkick.setColor('GREEN')
successkick.setFooter('http://kroxbotweb.deflowo.repl.co/kick.html')
successkick.setThumbnail(member.user.displayAvatarURL())
successkick.setDescription(`${member} has been successfully kicked from the server. \n Reason: ${reason}`);
let errormsg = new Discord.MessageEmbed()
errormsg.setTitle('ERROR')
errormsg.setColor('RED')
errormsg.setFooter('http://kroxbotweb.deflowo.repl.co/kick.html')
errormsg.setThumbnail(member.user.displayAvatarURL())
errormsg.setDescription(`**An error has occurred.** \n **1.** Does this user have higher permissions than me? \n **2.** Did you ping the user? \n **3.** Do they have server permissions? \n \n Targetted user: ${member}`)
try {
member.kick(reason)
} catch (err) {
message.channel.send(errormsg)
return
}
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
} else {
message.reply("You need a role named Admin/Mod to do this!")
}
} else {
message.channel.send("Nice try.")
}
break;```
I fixed the issue. It was actually that I forgot to put await in try. What it should have looked like is put below. I noticed how with await it worked fine, but without it stopped working strangely. The code was skipping the try and telling me it worked, even though it didn't. I think await stops the code from going forward until it is finished. I hope this helps other people. :)
if(message.member.roles.cache.some(r => r.name === "Admin") || message.member.roles.cache.some(r => r.name === "Mod")){
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
let reason = args.slice(1).join(' ');
if(!reason) reason = "No reason provided";
let successkick = new Discord.MessageEmbed()
successkick.setTitle("SUCCESS")
successkick.setColor('GREEN')
successkick.setFooter('http://kroxbotweb.deflowo.repl.co/kick.html')
successkick.setThumbnail(member.user.displayAvatarURL())
successkick.setDescription(`${member} has been successfully kicked from the server. \n Reason: ${reason}`);
let errormsg = new Discord.MessageEmbed()
errormsg.setTitle('ERROR')
errormsg.setColor('RED')
errormsg.setFooter('http://kroxbotweb.deflowo.repl.co/kick.html')
errormsg.setThumbnail(member.user.displayAvatarURL())
errormsg.setDescription(`**An error has occurred.** \n **1.** Does this user have higher permissions than me? \n **2.** Did you ping the user? \n **3.** Do they have server permissions? \n \n Targetted user: ${member}`)
try {
await member.kick(reason)
} catch (err) {
message.channel.send(errormsg)
return
}
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
} else {
message.reply("You need a role named Admin/Mod to do this!")
}
} else {
message.channel.send("Nice try.")
}
break;

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

Categories

Resources