Discord bot mute command by mention - javascript

I want to add few moderation commands to the bot, but I get stuck with "mute" command:
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(message.member.roles.cache.some(r => r.name === "Siren")){
const role = message.guild.roles.cache.find(r => r.name === "Muted");
const user = message.mentions.members.first().id;
user.roles.add(role);
}
}
}
I keep getting error:
TypeError: Cannot read property 'add' of undefined
I've been reading various guides and going through documentation and I keep failing on finding where I have made a mistake or what even causes this error.

At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined.
Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code.
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command')
const role = message.guild.roles.cache.get('21321321312');
if (!role) return message.reply('can`t get a role')
const member = message.mentions.members.first()
if (!member) return message.reply('Pls mention a member')
member.roles.add(role).then(newMember => {
message.channel.send(`successfully muted member ${member.user}`)
})
}
}

Related

discord.js v13 permissions.has() function not working (TypeError: Cannot read properties of undefined (reading 'has'))

I want to program a ban command for my Discord bot. I have this line where the bot should check if a user has the Administrator permission. If the user that should get banned has them, the bot doesn't ban the user and crashes. When I try to run this command I get this:
TypeError: Cannot read properties of undefined (reading 'has')
I don't understand why. Noone I asked could help me, I found nothing online, so I hope I can find here help.
My Code:
const discord = require('discord.js');
const { Permissions } = require('discord.js');
module.exports.run = async (Client, message, args) => {
if (!message.member.roles.cache.some(role => role.id == 589850931785498624)) {
return message.reply("You don't have the perms.");
}
const mention = message.mentions.users.first();
if (!mention) {
return message.reply('You need to tag a user!');
}
if (mention.permissions.has(Permissions.FLAGS.MANAGE_CHANNELS)) {
return message.reply("You can't ban an Administrator!")
}
//message.guild.members.ban(mention);
}
module.exports.help = {
name: "ban",
aliases: ["b"],
}
"TypeError: Cannot read properties of undefined (reading 'has')" means that mention.permissions is undefined. It's because your mention variable is a User and only GuildMembers have permissions.
Another error is that you try to check if the role.id is equal to a number/integer but snowflakes (like 589850931785498624) should always be strings as these are greater than the MAX_SAFE_INTEGER.
module.exports.run = async (Client, message, args) => {
if (!message.member.roles.cache.some((role) => role.id == '589850931785498624'))
return message.reply("You don't have the perms.");
const mentionedMember = message.mentions.members.first();
if (!mentionedMember)
return message.reply('You need to tag a user!');
if (mentionedMember.permissions.has(Permissions.FLAGS.MANAGE_CHANNELS))
return message.reply("You can't ban an Administrator!");
message.guild.members.ban(mentionedMember);
};

I can't understand why does it not send Discord.js v13

I can't understand why doesn't send the welcome message
Here's Code from index.js
client.on('guildMemberAdd', (member) => {
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
client.channels.cache.get(chx).send(`Welcome to ${message.guild.name}`);
});
Here's Code From channel.js
module.exports = {
name: "channel",
description: "Help Command",
category: "Help",
execute(client, message, args, Discord) {
const db = require("quick.db")
let channel = message.mentions.channels.first() //mentioned channel
if(!channel) { //if channel is not mentioned
return message.channel.send("Please Mention the channel first")
}
db.set(`welchannel_${message.guild.id}`, channel.id)
const embed = new Discord.MessageEmbed()
.setColor('#b5b5b5')
.setTitle(`Channel set: ${channel.name} `)
message.channel.send({ embeds: [embed] });
}
}
EDIT: I found out the problem i didn't have a intent flag GUILD_MEMBERS
and also thanks UltraX that helped also
Basically, the reason is simple, you need to go to your dev portal then after choosing your bot/application just go to bot and you need to enable member intents Server Member Intent after that it should work, if it didn't just give it a 10 minute, then try again!
The best way to ensure you get a channel object within the event is to use the guild property off the emitted member.
client.on("guildMemberAdd", (member) => {
const { guild } = member;
let chx = db.get(`welchannel_${member.guild.id}`);
if(chx === null) {return}
const channel = guild.channels.cache.get(chx);
if (!channel) return;
channel.send(`Welcome to ${message.guild.name}`)
.catch(console.error);
})
You will need the Guild Member's intent enabled as stated in This Answer for the event to emit.

Timed Mute Command 'UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role' error

I'm making a timed mute command, but i get a lot of errors, the principal one being :
(node:6584) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Role
at RequestHandler.execute (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async GuildMemberRoleManager.remove (c:\Users\user\Desktop\DiscordJSBOT\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:125:7)
(Use `node --trace-warnings ...` to show where the warning was created)
Here is the bugged code :
const ms = require('ms');
module.exports = {
name : 'mute',
description: 'Mutes given user',
execute(client, message, args) {
if(!message.member.hasPermission('MUTE_MEMBERS') && message.member.hasPermission('MANAGE_ROLES')) {
return message.reply('You need permissions to use this command !');
}
const target = message.mentions.users.first();
if(target) {
const member = message.guild.members.cache.get(target.id)
if(member) {
const muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if(muteRole) {
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
member.roles.add(muteRole.id)
setTimeout(function () {
member.roles.remove(muteRole.id)
RoleFolder.forEach(roles => {
member.roles.add(roles)
})
}, ms(args[1]));
} else {
return message.reply('Make sure you have a role nammed "Muted" when trying to mute a member');
}
} else {
return message.reply('There was an error while attempting to get member object of mentioned user !')
}
} else {
return message.reply('You need a user to mute ! ');
}
}
}
The problem comes from the fact that I get all roles from the user, store it and then give it back. I don't know if there is any other way to do it but that's what I found.
Thanks !
The error DiscordAPIError: Unknown Role is showing up because you are trying to remove a role from a user that the discord API cannot find. This role is the #everyone role which all members have.
You also do not need to run map on the roles, as you can already iterrate over the cache collection.
The code in your question:
const RoleFolder = []
const roles = member.roles.cache.map(role => role);
roles.forEach(role => {
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
Can be changed to:
const RoleFolder = []
member.roles.cache.forEach(role => {
if (role.id === member.guild.id) return;
RoleFolder.push(role.id)
member.roles.remove(role.id)
});
To ignore the role that doesn't exist in the discord API, you can check for:
role.id === member.guild.id or role.rawPosition === 0
You can use return to skip executing code for that particular role, meaning it isn't added to the RoleFolder, and doesn't try to remove the role.
Edit: I would avoid using role.name === '#everyone' as a user can create a role called #everyone and this would be missed, so I have updated my answer to check for a better condition.

discord.js Banning users outside server

I was able to ban users outside the servers easily but I'm facing trouble in banning members outside or not in the server, here is my code:
const Discord = require('discord.js');
module.exports = {
name: "ban",
description: "Kicks a member from the server",
async run (client, message, args) {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send('Please specify a user');
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban(`${reason}`).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Kicked by', message.author)
.addField('Reason', reason)
.setFooter('Time kicked', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
I couldn't find out how to do son. Can you help me? Thanks in advance
The reason why your code will not work and run into errors is that the user is not a member, while you are trying to stick them into a GuildMember object, which is not possible.
The way to fix this is to use a user object instead.
guild.members.ban() is a method that accepts a user as a parameter.
Another thing to note is that getting msg.mentions.members.first() will create an error because you are not mentioning a member of your server. (again)
Therefore member needs to be changed to message.mentions.users.first() or client.users.cache.get(args[0])
And your ban code needs to be changed to:
message.guild.members.ban(member).then(user => {
message.channel.send(`Banned ${user.id}`);
}).catch(console.error);

How to fix a complex Discord command in JS based off of webhooks and roles

I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.

Categories