Discord.js struggling to add a role to a discord member through id's - discord.js

const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a Member in secret")
.addUserOption((option) =>
option.setName("target").setDescription("Select a user").setRequired(true)
),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true,
});
const guild = client.guilds.cache.get("872567903839453215");
const userId = interaction.options.getUser("target").id;
console.log(userId);
const user = interaction.guild.roles.cache.get(userId);
console.log(user);
const newMessage = `Muted : ${user}`;
let fRole = message.guild.roles.cache.get("1005988662472888370");
let rRole = message.guild.roles.cache.get("1004543262884888636");
user.roles.add(fRole);
await interaction.editReply({
content: newMessage,
});
},
};
in the code i grab the user mentioned in the message and try to convert to something that would be recognised in user.roles.add(frole);
does anyone know a way to do this?
TypeError: Cannot read properties of undefined (reading 'add')
at Object.execute (DiscordBot\src\commands\tools\MuteMember.js:25:16)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.execute (DiscordBot\src\events\client\interactionCreate.js:11:9)
node:events:505
throw er; // Unhandled 'error' event
^
Error [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
at ChatInputCommandInteraction.reply (discord.js\src\structures\interfaces\InteractionResponses.js:101:46)
at Object.execute (DiscordBot\src\events\client\interactionCreate.js:14:27)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:384:10)
at processTicksAndRejections (node:internal/process/task_queues:85:21) {
code: 'InteractionAlreadyReplied'
}
this is the error message i get when i do /mute #user
i have no idea what it means please help :)

You're searching for the user ID using interaction.guild.roles.cache instead of searching for members.
Change that to:
const user = interaction.guild.members.cache.get(userId);

A better way of mute can be through the usage of the new timeout feature.
Read more here

Related

Can't registry slash commands. Getting missing access error

I'm getting a missing access error when trying to add slash commands to my guild. I already kicked the bot, deleted the bot and changed the intents.
My intent number is 32265
This is my code for adding it the commands:
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
const arrayOfSlashCommands = [];
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
arrayOfSlashCommands.push(file);
}
});
client.on("ready", () => {
client.guilds.cache.get("783606158669381663").commands.set(arrayOfSlashCommands);
});
But I'm getting this error:
E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async GuildApplicationCommandManager.set (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\managers\ApplicationCommandManager.js:146:18) {
method: 'put',
path: '/applications/893555323200237599/guilds/783606158669381663/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: [
{
name: 'search',
description: 'Search',
type: undefined,
options: undefined,
default_permission: undefined
}
],
files: []
}
}
The solution was to invite the bot using:

TypeError: Cannot read properties of null (reading 'id')

So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs

How to add roles when user send message

I want to give a role when users send messages any text channel. But I am making mistake somewhere.
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", msg => {
var sender = msg.author;
var message= msg.content;
const guild = client.guilds.cache.get("847874027149721680");
let role = message.guilds.roles.cache.find("848033734909231156");
if (message) {
message.author.addRole(role).catch(console.error);
}
});
client.login(process.env.DISCORD_TOKEN);
And i constantly get this error
/home/runner/Project/index.js:23
let role = message.guilds.roles.cache.find("848033734909231156");
^
TypeError: Cannot read property 'roles' of undefined
at Client.<anonymous> (/home/runner/Project/index.js:23:29)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Project/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Project/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/Project/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:314:20)
Im new so i may be dumb. sorry
It’s message.guild.roles.cache.get(), not message.guilds.roles.cache.get().
As japanballdev noted, you are committing a spelling error. The reason it still persists after you fix it is because you make this error in two places:
client.on("message", msg => {
var sender = msg.author;
var message= msg.content;
const guild = client.guild.cache.get("847874027149721680"); //ERROR WAS HERE
let role = message.guild.roles.cache.find("848033734909231156"); //ERROR WAS HERE TOO
if (message) {
message.author.addRole(role).catch(console.error);
}
});

How can I add a role to a member

So I am trying to make a verify script so when a member join he/she has to write !verify and then he/she will get a rank on the discord so we won't get raided by bot's
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.author
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
}
module.exports.help = {
name: "verify" //Name of the command
}
And when I try this code out I get this error And I have tried to research it but I can't find anything on it
This is my error
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
^
TypeError: Cannot read property 'add' of undefined
at Object.module.exports.run (C:\Users\lauri\Desktop\QuebecCity\utility\verify.js:12:76)
at Client.<anonymous> (C:\Users\lauri\Desktop\QuebecCity\index.js:257:33)
at Client.emit (node:events:376:20)
at MessageCreateAction.handle (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:376:20)
roles is a property of the GuildMember object. You are unable to add roles to a User object (AKA message.author that returns the user object of the author of a message). From that instance, we would simply want to instead use the member property of the message object, resulting in message.member.
Final Code
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.member
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(msg => msg.delete({ timeout: 5000 }));
member.roles.add(myRole)
}
module.exports.help = {
name: "verify" //Name of the command
}

How do I fix my member count in v12 of discord.js

I am trying to get the member count but I keep getting an error and I don't know what to do now.
Here is my code:
bot.on('ready',() =>{
let myGuild = bot.guilds.fetch('759858083718496266'); // Discord server ID
let memberCount = myGuild.memberCount;
let memberCountChannel = channel.messages.cache.get('123456789012345678');; // kanalens ID
memberCountChannel.setName('👤Members • ' + memberCount)
.catch(error => console.log(error));
console.log(`${bot.user.username} er klar.`)
//.then(result => console.log(result))
})
bot.on('guildMemberAdd', member => {
let myGuild = bot.guilds.fetch('759858083718496266');
let memberCount = myGuild.memberCount;
let memberCountChannel = myGuild.channels.fetch('792504113673142333');
memberCountChannel.setName('👤Members • ' + memberCount)
.catch(error => console.log(error));
});
bot.on('guildMemberRemove', member => {
let myGuild = bot.guilds.fetch('759858083718496266');
let memberCount = myGuild.memberCount;
let memberCountChannel = myGuild.channels.fetch('792504113673142333');
memberCountChannel.setName('👤Members ' + memberCount)
.catch(error => console.log(error));
});
I have tried with get instance of fetch and I have tried cache.get but received the same error:
let memberCountChannel = myGuild.channels.fetch('792504113673142333'); // kanalens ID
^
TypeError: Cannot read property 'fetch' of undefined
at Client.<anonymous> (C:\Users\lauri\Desktop\QuebecCity\index.js:140:47)
at Client.emit (node:events:376:20)
at WebSocketManager.triggerClientReady (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard.<anonymous> (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (node:events:376:20)
at WebSocketShard.checkReady (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
at WebSocketShard.onPacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)
at WebSocketShard.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\ws\lib\event-target.js:132:16)
.fetch() does not return a value, it returns a Promise. You are trying to treat myGuild as if it is a Guild object, when in reality it is a Promise that is "promising" you a Guild object. So how do you obtain the Guild object? There are two methods: Promises have a .then(value => {}) function which you could use, or you could use the simpler async/await method.
So here's how that would look in your ready event:
bot.on("ready", async () => {
let myGuild = await bot.guilds.fetch('759858083718496266'); // Discord server ID
let memberCount = myGuild.memberCount;
let memberCountChannel = await myGuild.channels.fetch('123456789012345678');
//rest of your code
});
Simply add async before your function declaration, and add await before each .fetch(). You need to do this in each of your event handlers; the above is only an example in your ready event handler.

Resources