I keep getting an error in my !giverole command - discord

When the owner of the server runs the command, it works but whenever any other admin/person with admin privileges uses it, the bot replies with "You do not have the required permissions"
Here is the code:
module.exports = {
commands: ['giverole', 'addrole', 'ar','gr'], // The command names/aliases
permissions: 'ADMINISTRATOR', //required permissions
requiredRoles: ['Admins'], // required roles
callback: (message, arguments) => {
const targetUser = message.mentions.users.first()
if (!targetUser) {
message.channel.send('Please specify someone to give a role to.')
return
}
arguments.shift()
const roleName = arguments.join(' ')
const { guild } = message
const role = guild.roles.cache.find((role) => {
return role.name === roleName
})
if (!role) {
message.channel.send(`There is no role with the name "${roleName}"`)
return
}
const member = guild.members.cache.get(targetUser.id)
member.roles.add(role)
message.channel.send(`That user now has the "${roleName}" role`)
},
}
Edit: Here is the command base since it was asked for by #Caladan
const validatePermissions = (permissions) => {
const validPermissions = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
module.exports = (client, commandOptions) => {
let {
commands,
expectedArgs = '',
permissionError = 'You do not have permission to run this command.',
minArgs = 0,
maxArgs = null,
cooldown = -1,
requiredChannel = '',
permissions = [],
requiredRoles = [],
callback,
} = commandOptions
// Ensure the command and aliases are in an array
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering command "${commands[0]}"`)
// Ensure the permissions are in an array and are all valid
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
Hope it helps in figuring out the issue.

Related

discord interaction.deferUpdate() is not a function

I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('WΓ€hle eine rolle')
.setDescription('WΓ€hle die rolle, die du gern haben mΓΆchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})

DiscordJS Roles Won't Add

const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
user.roles.add(member.guild.roles.cache.get("958443243836702859"));
return interaction.editReply("Muted!")
},
};
TypeError: Cannot read properties of undefined (reading 'add')
It won't let me add a roles to a user please help!
You are calling user.roles.add() in the middle of the hash definition of module_exports.
Read through your code again. It's a syntax error.
The issue stems from this, roles is an element of a member which is the parent of a user. user does not contain the element of roles. The code was trying to add roles to a user rather than a member.
This will help you out.
const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
//adding the below line
const member2mute = interaction.guild.members.cache.get(user.id)
//changing the below line
member2mute.roles.add("958443243836702859");
return interaction.editReply("Muted!")
},
};

TypeError: Cannot read property '0' of undefined on discord.js

I am using the WOK Command Handler and it was working fine for a few commands, then it suddenly stopped working when I created a new command, then went backwards and deleted the command, and still got the same error meaning that the error is in this file.
It's giving the error for the console.log(`Registering the "${commands[0]}" command!`) snippet.
const Discord = require('discord.js')
const { prefix } = require('../config.json')
const validatePermissions = (permissions) => {
const validPermissions = [
'ADMINISTRATOR',
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS_AND_STICKERS',
'USE_SLASH_COMMANDS',
'REQUEST_TO_SPEAK',
'MANAGE_THREADS',
'USE_PUBLIC_THREADS',
'USE_PRIVATE_THREADS',
'USE_EXTERNAL_STICKERS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
const allCommands = {
}
module.exports = (commandOptions) => {
let {
commands,
permissions = [],
} = commandOptions
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering the "${commands[0]}" command!`)
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
for (const command of commands) {
allCommands[command] = {
...commandOptions,
commands,
permissions
};
}
}
module.exports.listen = (client) => {
client.on('message', (message) => {
const { member, content, guild } = message;
const arguments = content.split(/[ ]+/);
const name = arguments.shift().toLowerCase();
if (name.startsWith(prefix)) {
const command = allCommands[name.replace(prefix, '')]
if (!command) {
return
}
const {
permissions,
permissionError = "You do not have the permission to run this command.",
requiredRoles = [],
minArgs = 0,
maxArgs = null,
expectedArgs,
callback
} = command
for (const permission of permissions) {
if (!member.hasPermission(permission)) {
message.reply(permissionError)
return
}
}
for (const requiredRole of requiredRoles) {
const role = guild.roles.cache.find((role) => role.name === requiredRole)
if (!role || !member.roles.cache.has(role.id)) {
message.reply(`You must have the "${requiredRole}" role to use this command.`)
return
}
}
if (arguments.length < minArgs || (
maxArgs !== null && arguments.length > maxArgs
)) {
const embed = new Discord.MessageEmbed()
embed.setTitle(`Incorrect syntax! Use ${prefix}${alias} ${expectedArgs}`)
message.reply(embed)
return
}
callback(message, arguments, arguments.join(' '), client)
}
})
}

How to embed a message in a command base

I am using WOK's advanced command handler and I just want the final message that will be returned to be an embed.
I am working on a specific test command where I type the prefix (for example !) when I run !add 5 10 I want the bot to ping me so it says #Ping , 5 + 10 = 15.
I want to solve 2 things:
I don't want the comma after the ping
I want the message that appears on discord to be an embed.
Here is the code for the command base:
const Discord = require('discord.js')
const { prefix } = require('../config.json')
const validatePermissions = (permissions) => {
const validPermissions = [
'ADMINISTRATOR',
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS_AND_STICKERS',
'USE_SLASH_COMMANDS',
'REQUEST_TO_SPEAK',
'MANAGE_THREADS',
'USE_PUBLIC_THREADS',
'USE_PRIVATE_THREADS',
'USE_EXTERNAL_STICKERS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
module.exports = (client, commandOptions) => {
let {
commands,
expectedArgs = '',
permissionError = 'You do not have the permission to run this command.',
minArgs = 0,
maxArgs = null,
permissions = [],
requiredRoles = [],
callback
} = commandOptions
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering the "${commands[0]}" command!`)
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
client.on('message', (message) => {
const { member, content, guild } = message
for (const alias of commands) {
const command = `${prefix}${alias.toLowerCase()}`
if (
content.toLowerCase().startsWith(`${command} `) ||
content.toLowerCase() === command
) {
for (const permission of permissions) {
if (!member.hasPermission(permission)) {
message.reply(permissionError)
return
}
}
for (const requiredRole of requiredRoles) {
const role = guild.roles.cache.find((role) => role.name === requiredRole)
if (!role || !member.roles.cache.has(role.id)) {
message.reply(`You must have the "${requiredRole}" role to use this command.`)
return
}
}
const arguments = content.split(/[ ]+/)
arguments.shift()
if (arguments.length < minArgs || (
maxArgs !== null && arguments.length > maxArgs
)) {
const embed = new Discord.MessageEmbed()
embed.setTitle(`Incorrect syntax! Use ${prefix}${alias} ${expectedArgs}`)
message.reply(embed)
return
}
callback(message, arguments, arguments.join(' '), client)
return
}
}
})
}
And here is the code for the specific add command:
module.exports = {
commands: ['add', 'addition'],
expectedArgs: '<num1> <num2>',
permissionError: 'You do not have the permission to run this command.',
minArgs: 2,
maxArgs: 2,
callback: (message, arguments, text) => {
const num1 = +arguments[0]
const num2 = +arguments[1]
message.reply(`${num1} + ${num2} = ${num1 + num2}`)
},
permissions: ['SEND_MESSAGES'],
requiredRoles: ['.𝐄𝐗𝐄 β‚ͺ | π•πžπ«π’πŸπ’πžπ'],
}
Please advise.
require discord.js in your function and use Discord.MessageEmbed() to create the embed.
To ping the user who ran the command use <#${message.author.id}>
module.exports = {
commands: ['add', 'addition'],
expectedArgs: '<num1> <num2>',
permissionError: 'You do not have the permission to run this command.',
minArgs: 2,
maxArgs: 2,
callback: (message, arguments, text) => {
const Discord = require("discord.js")
const num1 = +arguments[0]
const num2 = +arguments[1]
const addEmbed = new Discord.MessageEmbed()
.setTitle(`<#${message.author.id}> ${num1} + ${num2} = ${num1 + num2}`)
message.reply(addEmbed)
},
permissions: ['SEND_MESSAGES'],
requiredRoles: ['.𝐄𝐗𝐄 β‚ͺ | π•πžπ«π’πŸπ’πžπ'],
}

I want users not to be able to hand out higher privileges than they have themselves

A moderator who has manage_roles permissions can even give the owner role to anyone. Is there a way that it can give out no higher role than to his own role?
So if he is admin, he can give at most admin, so not everyone can give random roles to anyone.
const { MessageEmbed } = require('discord.js');
const config = require('../../configs/config.json');
module.exports = {
config: {
name: "give-roles",
},
run: async (client, message, args) => {
message.delete();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send({
embed: {
title: `You dont have permission to use this command`
}
})
if (!args[0] || !args[1]) return message.channel.send({
embed: {
title: "Incorrect usage, It's `<username || user id> <role name || id>"
}
})
try {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
const alreadyHasRole = member._roles.includes(roleName.id);
if (alreadyHasRole) return message.channel.send({
embed: {
title: "User already has the role defined"
}
})
const embed = new MessageEmbed()
.setTitle(`Role Name: ${roleName.name}`)
.setDescription(`${message.author} has successfully given the role ${roleName} to ${member.user}`)
.setColor('f3f3f3')
.setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
.setFooter(new Date().toLocaleString())
return member.roles.add(roleName).then(() => message.channel.send(embed));
} catch (e) {
return message.channel.send({
embed: {
title: "Try to give a role that exists next time"
}
})
}
}
}
You're able to use roles.highest.position:
let taggedMember = ... //(guildMember)
if (message.member.roles.highest.position < taggedMember.roles.highest.position) {
//code...
}
Docs: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=highest

Resources