Unhandled promise rejection: ReferenceError: member is not defined - discord.js

My code has an error: Unhandled promise rejection: ReferenceError: member is not defined. My code used to work, but now it just doesn't work. I haven't made any changes with the code. Here's my code:
module.exports = {
name: "mute",
description: "Mute a member from your server",
async run(client, message, args) {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send('You can\'t use this command ( ͡° ͜ʖ ͡°).');
let user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!user) message.channel.send("Please tag a user to mute.");
if (user.id === message.author.id) return message.channel.send('lmao you can\'t mute yourself');
if (!member.bannable) return message.channel.send('This user can\'t be muted.');
let role = message.guild.roles.cache.find(x => x.name === "Muted");
if (!role) return message.channel.send("Something went wrong.");
let reason = args.slice(1).join(" ");
if (reason === null) reason = "Unspecified"
user.roles.add(role);
await message.channel.send(`${user} was muted. That was nice.`);
}
}

Change this line if (!member.bannable) return message.channel.send('This user can\'t be muted.'); into if (!user.bannable) return message.channel.send('This user can\'t be muted.');

Related

How to check a users permissions in a certain server

So I am making a DM command and I want to make it so when the user uses the command it will check the users permissions in a certain server. This is my current code:
bot.on("message", async msg => {
if(msg.channel.type === "dm") {
if(msg.content.startsWith(";announce")) {
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await msg.channel.send(Question1)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error = new Discord.MessageEmbed()
.setDescription("You must have a certain permission to do this. If your roles have just been changed, please type `retry` now so I can check again.")
ERRMSG = await msg.channel.send(error)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if(msg2.content === "retry") {
if(msg.member.hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await ERRMSG.edit(Question1)
msg2.delete()
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error2 = new Discord.MessageEmbed()
.setDescription("I still could not find your permissions. Please retry when you have the correct permissions.")
ERRMSG.edit(error2)
msg2.delete()
}
}
})
}
}
}
})
This gives me the error:
(node:347) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
(node:347) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:347) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This just throws this error but I am not sure how I can check the actual permissions in this discord server. How can I manipulate this feature into my Discord Bot?
Well, first of all, you would want to get the guild object of the guild you're referring to, and obviously check if that guild even exists. something that could be done using:
const guildObject = client.guilds.cache.get('place guild id here'); // gets the guild object of the id provided
if (!guildObject) return console.log('Guild could not be found!'); // Would console log in the case that the guild you've provided does not exist.
From there on, we could use the guild object we've found to check if the message author actually exists in this guild, which can be done using
const memberObject = guildObject.member(message.author.id)
if (!memberObject) return console.log('User could not be found in the provided guild!');
Finally, we could determine whether or not the user has the wanted permissions using:
if (!memberObject.hasPermission('Permission here')) return console.log('User does not have the corresponding permissions needed!')
The error you get comes from this line:
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS"))
What are you checking with this line of code? If the author has permission?
You can check if the author has permission by doing:
if(msg.guild.member(msg.author).hasPermission("BAN_MEMBERS"))

How to add member to role without having to mention it? [Discord.JS]

at the moment I am trying to make a role command for my bot. For example: t!role add #person <name of role>. But I can't figure out how to get the role as people have usernames with different lengths so I cannot use .slice which I have been able to use for creating a role
Currently my bot says that it can't find that role
My code:
const config = require("../../config.json");
module.exports = {
name: "role",
description: "Creates/removes roles from server and adds/removes roles from members",
category: "utility",
run: async (client, message, args) => {
const mentionedMember = message.mentions.members.first();
let messageRole = message.content.slice(config.prefix.length + 12).trim();
const findRole = message.guild.roles.cache.find(r => r.name === messageRole);
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("You do not have permission to use this command");
if (args[0].toLowerCase() == "create") {
let roleName = message.content.slice(config.prefix.length + 12);
if (!roleName) return message.channel.send("You need to specify a name for the role");
let newRole = await message.guild.roles.create({ data: { name: roleName, permissions: false } });
message.channel.send(`**${roleName}** has been created`);
} else if (args[0].toLowerCase() === "delete") {
if (!findRole) return message.channel.send("You need to specify a role to be deleted\n\n" + messageRole);
findRole.delete();
message.channel.send(`${findRole.name} has been deleted`);
} else if (args[0].toLowerCase() === "add") {
if (!args[1]) return message.channel.send("You need to mention the member you want to give the role to");
if (!mentionedMember) return message.channel.send("I can't find that member");
if (!args[2]) return message.channel.send("You need to specify a role I have to give");
if (!findRole) return message.channel.send("I can't find that role");
if (mentionedMember.roles.cache.has(findRole)) return message.channel.send(`${mentionedMember.name} already has that role`);
mentionedMember.addRole(findRole);
message.channel.send(`${mentionedMember.name} has been given the role ${findRole.name}`)
return undefined
} else if (args[0].toLowerCase() === "remove") {
if (!args[1]) return message.channel.send("You need to mention the member you want to remove the role from");
if (!mentionedMember) return message.channel.send("I can't find that member");
if (!args[2]) return message.channel.send("You need to specify a role I have to remove");
if (!mentionedRole) return message.channel.send("I can't find that role");
if (!mentionedMember.roles.cache.has(mentionedRole.id)) return message.channel.send(`${mentionedMember} doesnt have that role`);
mentionedMember.roles.remove(mentionedRole.id);
message.channel.send(`**${mentionedRole.name}** has been removed from ${mentionedMember}`);
return undefined
}
}
}
Slice the amount of args. If you slice an array, it will remove one entire value from it.
[1, 2, 3].slice(2)
// result: [3]
Since args is an array, all you have to do is args.slice(2), assuming args does not include the command message.

Time Variable Is Not Defined in Discord.JS

My setTimeout() is used for a certain amount of time as the user states. So, if the user put in 20, the muted member would be muted for 20 minutes. The problem I am having is that the time says it is undefined at the end. I'm not sure why it's not working. The syntax would be something like !mute user time reason.
module.exports = {
name: "mute",
description: "Mute those members!",
execute(message, args) {
const {RichEmbed} = require("discord.js");
setTimeout(() => {
if(!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("You do not have sufficient permissions to perform this command. Please try again");
let muteMember = message.mentions.members.first() || message.members.get(args[0]);
if(!muteMember) return message.channel.send("You did not provide a member to mute. Please provide a user to mute");
let time = parseInt(args[2]) * 60000;
if(!time) return message.channel.send("You did not provide how long to mute this member. Please provide a time in minutes");
let reason = args.slice(2).join(" ");
if(!reason) reason = "No reason provided";
if(!message.guild.me.hasPermission("MANAGE_ROLES")) return message.channel.send("I do not have sufficient permissions to mute this member. Please try again");
let muteRole = message.guild.roles.find(role => role.name === "Muted");
if(!muteRole) {
try {
muteRole = message.guild.createRole({
name: "Muted",
permissions: []
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(muteRole, {
SEND_MESSAGE: false,
ADD_REACTIONS: false,
SEND_TTS_MESSAGES: false,
ATTACH_FILES: false,
SPEAK: false
})
})
} catch (e) {
console.log(e.stack);
}
}
muteMember.addRole(muteRole.id). then(() => {
message.delete();
muteMember.send(`You have been muted in ${message.guild.name} for ${reason}`).catch(err =>console.log(err));
message.channel.send(`${muteMember.user.username} has been successfully muted`);
let muteEmbed = new RichEmbed()
.setColor("#FF0000")
.addField("Moderation Action", "mute")
.addField("Muted Member", muteMember.user.username)
.addField("Moderator", message.author.username)
.addField("Reason", reason)
.addField("Date:", message.createdAt.toLocaleAString());
let modChannel = message.guild.channels.find(channel => channel.name === "mod-log");
modChannel.send(muteEmbed);
})
}, time)
},
};
You need to get the time argument first before the reason argument since at the moment you're putting the time variable into the reason variable
if (isNaN(args[1]) return message.reply('Please enter a valid number');
let time = parseInt(args[2]) * 60000;
let reason = args.slice(2).join(" ");
if (!reason) reason = "No reason provided";
if (!message.guild.me.hasPermission("MANAGE_ROLES")) return message.channel.send("I do not have sufficient permissions to mute this member. Please try again");

TypeError: Cannot read property 'roles' of undefined at Object.module.exports.run

I am trying to make a tempmute command which saves data to JSON then reads it every 3 seconds to see is the time experied. I made the mute command but I recive an error TypeError: Cannot read property 'roles' of undefined. I delete the if(!message.member.roles.has("675376537272582154")) return message.channel.send('Bu komutu kullanabilmek için「🔪」Mute Premission rolüne sahip olmasınız.') but this time it said TypeError: Cannot read property 'members' of undefined. Can someone help me?
Information
Discord.js Version: v11.6.1
Node.js Version: 12.0.0
Code
const { RichEmbed } = require('discord.js');
const fs = require('fs');
module.exports.run = async (message, args, bot) => {
if(!message.member.roles.has("675376537272582154")) return message.channel.send(`Bu komutu kullanabilmek için \`「🔪」Mute Premission\` rolüne sahip olmasınız.`);
let toMute = message.mentions.member.first() || message.guild.members.get(args[0])
if(!toMute) return message.channel.send(`:x: Susturulacak kullanıcıyı etiketlemelisin!`)
let timeMute = args[1]
if(!timeMute) return message.channel.send(':x: Susturma süresini dakika cinsinden yazmalısın!')
if(isNaN(args[1])) return message.channel.send(':x: Senin de bildiğin gibi süre sadece sayı olabilir!')
let reason = args.slice(2).join(" ")
if(!reason) return message.channel.send(':x: Susturma sebebini yazmalısın!')
if(toMute.id === message.author.id) return message.channel.send(`:x: Kendini susturamazsın bea!`)
if(toMute.roles.has('675376537272582154')) return message.channel.send(`:x: \`「🔪」Mute Premission\` rolüne sahip olan birini susturamazsın!`)
let role = message.guild.roles.find(x => x.name === '「🔇」Muted')
if(!role) return message.channel.send(':x: `「🔇」Muted` adlı rolü bulamıyorum!')
if(toMute.roles.has(role.id)) return message.channel.send(':x: Bu kullanıcı zaten susturulmuş!')
let modlog = message.guild.channels.find(c => c.name === '『🔰』punishment')
if(!modlog) return message.channel.send(':x: Mod-Log kanalını bulamıyorum!')
const embed = new RichEmbed()
.setTitle('Susturma')
//.setThumbnail(`${toMute.avatarURL}`)
.setDescription(`**Susturlan Kişi: \`${toMute.tag}\`** \n **ID Numarası: \`${toMute.id}\`**\n **Susturan Yetkili: \`${message.author.tag}\`**\n **Süre: \`${timeMute}\`** **Sebep: \`${reason}\`** `)
.setColor("#ff0000")
.setFooter('Kurallara Uymayanın Sonu')
.setTimestamp();
bot.mutes[toMute.id] = {
guild: message.guild.id,
time: Date.now() + parseInt(args[1]) * 10000
}
await toMute.addRole(role)
fs.writeFile("./mutes.json", JSON.stringify(bot.mutes, null, 4), err => {
if(err) throw err;
modlog.send(embed)
})
}
module.exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sustur'],
permLevel: 0
};
module.exports.help = {
name: 'mute',
description: 'Sustur gitsin',
usage: '!sustur #kullanıcı süre sebep'
}
member and guild are most likely undefined because your bot is receiving a DM message. Check if the message is from a guild before continuing with your code:
module.exports.run = async (message, args, bot) => {
if(!message.guild) return
// rest of code
}

How to ban and kick a GuildMember

Well, I followed "The Source Code" "discord.js" tutorial, (even copy-pasted his code from GitHub) but the ban and kick commands he's shown don't work, I assume they got broken by a recent update. It sends the embed to the incidents channel but doesn't actually ban the player. Also, if you have any suggestions for me to change things, please suggest!
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban(bReason);
message.delete().catch(O_o => {});
incidentchannel.send(banEmbed);
return;
}
message.guild.member(bUser).ban(bReason);
This will not ban the member. The message has a member property so you don't need to use message.guild.member you can just easily use message.member.
So it should look like this:
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.members.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser.user.tag} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel.name)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban({
reason: bReason
});
message.delete();
incidentchannel.send({
embed: banEmbed
});
return;
}
I changed a lot because a lot was outdated and could not work. It could be that I haven't seen one or the other mistake.
Let me know if it worked! :)
Best regards,
Monkeyyy11
This seems awfully complicated, I hope my command can make things a bit easier!
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "kick") {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("Permissions invalid");
const userKick = message.mentions.users.first();
if (userKick) {
var member = message.guild.member(userKick);
if (member) {
member.kick({
reason: `This person was kicked using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`A user been kicked.`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "ban") {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Permissions invalid");
const userBan = message.mentions.users.first();
if (userBan) {
var member = message.guild.member(userBan);
if (member) {
member.ban({
reason: `This person was banned using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`a user has been banned!`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
If you use discord.js v12 or higher, then RichEmbed is now deprecated. Instead, use MessageEmbed

Resources