Discord.js role position - javascript

I am making a nickname command for my Discord.JS bot. I want to make it so that if the bot or member has a lower role than the target, it returns an error message. I am using the Commando command handler. Here is my code:
const Commando = require('discord.js-commando')
module.exports = class NicknameCommand extends Commando.Command {
constructor(client) {
super(client, {
name: 'nickname',
aliases: ['nick'],
group: 'misc',
memberName: 'nickname',
userPermissions: [
'MANAGE_NICKNAMES',
'CHANGE_NICKNAME'
],
clientPermissions: [
'MANAGE_NICKNAMES',
'CHANGE_NICKNAME'
],
description: 'Changes the nickname of a user',
argsType: 'multiple'
})
}
run = (message, args) => {
const target = message.mentions.users.first()
if(!target) {
return message.reply('Please specify a valid member to change the nickname of')
}
if(message.member.roles.highest.position < target.roles.highest.position) {
return message.channel.send('You do not have a high enough role to change this member\'s nickname')
}
if(message.guild.me.roles.highest.position < target.roles.highest.position) {
return message.channel.send('I do not have a high enough role to change this member\'s nickname')
}
const member = message.guild.members.cache.get(target.id)
args.shift()
const nickname = args.join(' ')
if(nickname.length > 32) {
return message.reply('That nickname is too long! Please make it less than 32 characters')
}
member.setNickname(nickname)
message.reply(`Successfully changed the user's nickname to '${nickname}'`)
}
}
The Discord Commando makes it so it throws an error through a message in the bot, so I do not have a specific console log error, but the bot responded:
An error occurred while running the command: TypeError: Cannot read property 'highest' of undefined
The error appears to be around line 28. I know that the syntax for the highest role is not correct, but I don't know the correct one. Is there a fix to this? Thanks

Related

ReferenceError: msg is not defined

Hello i wanted to mentions the user that are running the command but i am getting a Error
Here is the Code!
const Discord = require("discord.js")
module.exports = {
name: 'not-dropping',
description: 'sets the dropping status!',
execute(message, args) {
if (message.channel.id === '1059798572855476245') {
message.delete(1000);
const name = ("dropping-🔴")
message.channel.setName(name)
message.channel.send(`Successfully set the dropping status to **${name}**\n<#${msg.author.id}> is not Dropping anymore!\nDont Ping Him in your Ticket.`)
}
}
}
I do not understand waht the Problem is
As the error states "msg" is not defined.
In the code "{msg.author.id}" you are using msg while the actual variable is "message".
Change it to {message.author.id}
"msg" There is no such use
You should use "message"
I changed where you need to change in the code :)
const Discord = require("discord.js")
module.exports = {
name: 'not-dropping',
description: 'sets the dropping status!',
execute(message, args) {
if (message.channel.id === '1059798572855476245') {
message.delete(1000);
const name = ("dropping-🔴")
message.channel.setName(name)
message.channel.send(`Successfully set the dropping status to **${name}**\n<#${message.author.id}> is not Dropping anymore!\nDont Ping Him in your Ticket.`)
}
}
}

Check if first argument is a mention

I'm coding a discord bot and I'm trying to make a kick command right now. I managed to find how to check if there's any mention in the command message with message.mentions.members.first() but I couldn't find anything to check if a specific argument is a mention.
Code I have so far:
module.exports = {
name: "kick",
category: "moderation",
permissions: ["KICK_MEMBERS"],
devOnly: false,
run: async ({client, message, args}) => {
if (args[0]){
if(message.mentions.members.first())
message.reply("yes ping thing")
else message.reply("``" + args[0] + "`` isn't a mention. Please mention someone to kick.")
}
else
message.reply("Please specify who you want to kick: g!kick #user123")
}
}
I looked at the DJS guide but couldn't find how.
MessageMentions has a USERS_PATTERN property that contains the regular expression that matches the user mentions (like <#!813230572179619871>). You can use it with String#match, or RegExp#test() to check if your argument matches the pattern.
Here is an example using String#match:
// make sure to import MessageMentions
const { MessageMentions } = require('discord.js')
module.exports = {
name: 'kick',
category: 'moderation',
permissions: ['KICK_MEMBERS'],
devOnly: false,
run: async ({ client, message, args }) => {
if (!args[0])
return message.reply('Please specify who you want to kick: `g!kick #user123`')
// returns null if args[0] is not a mention, an array otherwise
let isMention = args[0].match(MessageMentions.USERS_PATTERN)
if (!isMention)
return message.reply(`First argument (_\`${args[0]}\`_) needs to be a member: \`g!kick #user123\``)
// kick the member
let member = message.mentions.members.first()
if (!member.kickable)
return message.reply(`You can't kick ${member}`)
try {
await member.kick()
message.reply('yes ping thing')
} catch (err) {
console.log(err)
message.reply('There was an error')
}
}
}

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 bot mute command by mention

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}`)
})
}
}

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