discord.js the bot crash when there's no mention in my unmute command - javascript

so i made a mute and unmute command, the mute one works pretty well and i just gotta add some things, the unmute one also works well but when there's no mentioned person (for example q!unmute and not q!unmute [user]) the bot crashes, i tried catch and that stuff but i really don't understand how they work, i'm pretty new to js, this is the string that should send the "you have to mention a user" error:
if (!member) return message.channel.send("You have to mention a valid member");
this is the rest of the code:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
if (!member) return message.channel.send("You have to mention a valid member");
}
}
}
i hope you can help

In your code you're checking if the user mentioned is null, but it is at the end of the function. I think that putting the if just after you get the value should work:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
if (!member) return message.channel.send("You have to mention a valid member");
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
}
}
}

Move
if (!member) return message.channel.send("You have to mention a valid member");
Below where you define member.
const member = message.mentions.members.first();

Related

Mute system discord.js

Hello I have problem with my code! When I use my mute command it always spams "You need permission to use command"! Here is my code:
client.on('message', message => {
if(message.content.startsWith("$mute")) {
if (!message.member.permissions.has("KICK_MEMBERS")) return
message.channel.send("You need permissions to use command")
let role = message.guild.roles.cache.find(role => role.name === "Muted")
let member = message.mentions.members.first()
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) return message.channel.send("You didn't write a reason")
if(!role) return message.channel.send("This server don't have Muted role")
if(!member) return message.channel.send("You didn't mention the user to mute!")
member.roles.add(role)
.then(() => {
message.channel.send(`Successfully muted ${member} with reason: ${reason}`)
})
.catch(() => {
message.channel.send("Error")
})
}
})
if (!message.member.permissions.has("KICK_MEMBERS")) return
message.channel.send("You need permissions to use command")
This translates to "If the member doesn't have the permission to kick other members, exit the function and return undefined. Else, if the member HAS permission, send a message saying he DOESN'T have permission".
if (!message.member.permissions.has("KICK_MEMBERS")) return message.channel.send("You need permissions to use command")
You should write it like this instead.

Cannot read property 'first' of undefined

I'm trying to make a mute command for my discord bot and I'm getting the error:
Cannot read property 'first' of undefined
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
const MuteroleCommand = require('./MuteroleCommand');
const { muterole } = require('./MuteroleCommand.js')
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if(!message.guild.me.hasPermission("MUTE_MEMBERS")) return message.channel.send("I do not have Permissions to mute members.");
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu'},
{ name: '**Info**', value: 'In order for the command to work, a muterole must be provided. this can be done by "=muterole <role ID>"\nYou cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours\nYou cannot mute members that have already been muted'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
const mentionedMember = message.mentions.member.first() || await message.guild.members.fetch(args[0]);
let reason = args.slice(1).join(" ");
const banEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL());
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (typeof muterole === undefined) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.has(muterole.id)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
await mentionedMember.send(banEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muterole.id).catch(err => console.log(err).then(message.channel.send('There was an error while muting the member')))
}
}
I'm not sure why this error occurred and I'm also not sure if there are more errors in this code, I would very much like to know what the issue is.
The problem is with this line:
const mentionedMember = message.mentions.member.first() || await message.guild.members.fetch(args[0]);
Your issue seems to be that message.mentions.member is undefined
The MessageMentions class does not contain a field called member, however it does have a field called members which I assume is what you're looking for.
Replace member with members and you should be good to go! :)
acoording to Discord js Documentation it is message.mentions.members.first() not message.mentions.member.first()

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.

How Do I Add Roles via Discord.js?

I'm currently creating a bot through Discord.js, and I want someone to be able to state a command in order to gain a role. However, I can't figure this out for the life of me.
In my bot folder, I've created an addrole.js file with the following chunk of code:
const Discord = require("discord.js");
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first ||
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e.message));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.RichEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL)
.addField("Moderation:", "Addrole")
.addField("Mutee:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt.toLocaleString());
letsChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
I followed THIS tutorial to get here: https://www.youtube.com/watch?v=GCSbZ2UbriU
I've given my bot the Manage_Roles permission and have attempted to state both "beans addrole (role) (user)" and "beans addrole (user) (role)". I'm expecting him to even specify error messages, or even better yet, add the role. However, he isn't even spitting out error messages, and neither is my console. Everything else works fine, it's just that this particular function won't work. Any input/feedback would help a LOT.
I found a lot of typos inside of your code, and also, it has some problem because you mixed discord.js^11.x with discord.js^12.x. I fixed your code below, but make sure your bot has the ADMINISTRATOR permission as well required by your command.
const Discord = require("discord.js");
// You defined the 3 lines here twice, which requires `message` to be defined.
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
// `Member.hasPermissions()` is deprecated
if (!message.member.permissions.has(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.MessageEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("Moderation:", "Addrole")
.addField("Mute:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt); // `.toLocaleString()` isn't required, discord automatically coonverts it to string.
let sChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
To learn more, try visiting the links below:
Discordjs.guide - Guide - Updating from v11 to v12
Discordjs.guide - Guide - Permissions
Discordjs.guide - Guide - Handling Commands
if (rMember.roles.cache.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
I used this snippet to get my bot to add roles. Thanks to user above. I had to add cache though. in first line.
Your problem mainly appears from these lines:-
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
The problem happens because message is not defined until you define a function. Try moving the code inside the run function.

How do I fix this to add a role mentioned in the command to the user?

I am coding a custom discord bot for my server and I ran into this issue. I want to add a role to a user that is not predefined. IE: I want to be able to &addrole #user anyrole and add that role to a user. Here is the code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
//!addrole #andrew anyrole
if(!message.member.hasPermission("MANAGE_MEMBERS")) return
message.reply("Sorry pal, you can't do that.");
let rMember = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if(!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("Specify a role!");
let gRole = message.guild.roles.find('name', any);
if(!gRole) return message.reply("Couldn't find that role.");
if(rMember.roles.has(gRole.id)) return message.reply("They already have
that role.");
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Congrats, you have been given the role
${gRole.name}`)
}catch(e){
message.channel.send(`Congrats to <#${rMember.id}>, they have been given
the role ${gRole.name}. We tried to DM them, but their DMs are locked.`)
}
}
module.exports.help = {
name: "addrole"
}

Categories

Resources