check if the user has role assigned to it on discord js
- User
check if the user has role assigned to it on discord js
- Assistant
You can check if a user has a specific role assigned to them using the
member.roles.cache.has()method. Here's an example:// Assuming `message` is the message object passed to your command const user = message.member; // Get the member object for the user if (user.roles.cache.has('ROLE_ID')) { // User has the role } else { // User does not have the role }Replace
ROLE_IDwith the ID of the role you want to check. You can also check for multiple roles by chaining multiplehas()calls, like this:if (user.roles.cache.has('ROLE_1_ID') && user.roles.cache.has('ROLE_2_ID')) { // User has both roles } else { // User does not have both roles } - User
check if the user have role or not in this code before starting if() if (reaction.message.channel.id !== channel_Id) return; if (user.bot) return;
const roleName = await searchRoleName(emojisList, reaction.emoji.name); if (!roleName) return; // get the role object from the guild const guild = reaction.message.guild; await guild.roles.fetch(); const role = guild.roles.cache.find((r) => r.name === roleName); if (!role) return; // remove the role from the user/member const member = await guild.members.fetch(user.id); await member.roles.remove(role); console.log(`Removed ${roleName} role from ${member.user.tag}`);} catch (error) { console.error("Error removing role:", error); } }
- Assistant
Here's an example of checking if the user has a role before the
if()statement:if (reaction.message.channel.id !== channel_Id) return; if (user.bot) return; const roleName = await searchRoleName(emojisList, reaction.emoji.name); if (!roleName) return; // get the role object from the guild const guild = reaction.message.guild; await guild.roles.fetch(); const role = guild.roles.cache.find((r) => r.name === roleName); if (!role) return; // check if the user has the role const member = await guild.members.fetch(user.id); if (!member.roles.cache.has(role.id)) { // user does not have the role, nothing to remove return; } // remove the role from the user/member await member.roles.remove(role); console.log(`Removed ${roleName} role from ${member.user.tag}`); } catch (error) { console.error("Error removing role:", error); }The
if()statement now includes a check to see if the user has the role before attempting to remove it. If the user does not have the role, the function returns without doing anything. - User
Events.MessageReactionRemove not working on old messages
- Assistant
The
MessageReactionRemoveevent in discord.js only fires for reactions that are removed from messages that have already been cached by the bot. If the message was sent before the bot started running or if the bot's cache is cleared, the event will not fire.Here are a couple of solutions you can try:
-
Fetch the message object when the bot starts up: When your bot starts up, you can fetch the message objects for the old messages that may have reactions on them, and cache them in memory. This will ensure that when a reaction is removed from an old message, the corresponding event will fire.
-
- User
import { Client, GatewayIntentBits, Routes, Partials, Events, } from "discord.js"; import { config } from "dotenv"; import { REST } from "discord.js"; import commandManger from "./commands/order.js"; import rolesCommand from "./commands/roles.js"; import usersCommand from "./commands/user.js"; import channelsCommand from "./commands/channel.js"; import banCommand from "./commands/ban.js"; import getEmojiiListRoles from "./emojiiList.js" import reactionAdded from "./reaction-manger/reactionAdd.js"; import reactionRemoved from "./reaction-manger/reactionRemove.js"; import mongoose from "mongoose";
config(); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessageReactions, ], partials: [Partials.Message, Partials.Channel, Partials.Reaction], }); const Token = process.env.BOT_TOKEN; const CLIENT_ID = process.env.CLIENT_ID; const GUILD_ID = process.env.GUILD_ID; const channel_Id = process.env.CHOOSE_ID; const emojisList = await getEmojiiListRoles();
- Assistant
- User
can you add the messages to this code function import searchRoleName from "../utility/searchRoleName.js"; export default async function reactionAdded( reaction, user, emojisList, channel_Id ) { if (reaction.message.channel.id !== channel_Id) return;
if (user.bot) return;
const roleName = await searchRoleName(emojisList, reaction.emoji.name); if (!roleName) return;
try { await reaction.fetch();
// get the role object from the guild const guild = reaction.message.guild; await guild.roles.fetch(); const role = guild.roles.cache.find((r) => r.name === roleName); if (!role) return; // add the role to the user/member const member = await guild.members.fetch(user.id); await member.roles.add(role); console.log(`Added ${roleName} role to ${member.user.tag}`);} catch (error) { console.error("Error assigning role:", error); } }
- Assistant
You can add support for checking if the message is an old message and caching it in the
reactionAddedfunction as follows:import searchRoleName from "../utility/searchRoleName.js"; export default async function reactionAdded( reaction, user, emojisList, channel_Id, message ) { const isOldMessage = !!message; if (isOldMessage) { message.reactions.cache.add(reaction); // add the reaction to the message's cache } if (reaction.message.channel.id !== channel_Id) return; if (user.bot) return; const roleName = await searchRoleName(emojisList, reaction.emoji.name); if (!roleName) return; try { await reaction.fetch(); // get the role object from the guild const guild = reaction.message.guild; await guild.roles.fetch(); const role = guild.roles.cache.find((r) => r.name === roleName); if (!role) return; // add the role to the user/member const member = await guild.members.fetch(user.id); await member.roles.add(role); console.log(`Added ${roleName} role to ${member.user.tag}`); } catch (error) { console.error("Error assigning role:", error); } } - User
file:///D:/Home/discord%20bots/vtuber-assistant-aki/src/index.js:43 const messages = await channel.messages.fetch({ limit: 100 });
^TypeError: Cannot read properties of null (reading 'messages') at file:///D:/Home/discord%20bots/vtuber-assistant-aki/src/index.js:43:32 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
- Assistant
This error message suggests that the value of
channelis null or undefined. When you try to access themessagesproperty of a null or undefined value, you get the "Cannot read properties of null (reading 'messages')" error.To fix this error, you should add some error checking to ensure that the
channelvariable is not null or undefined before calling thefetch()method on it. Here's an updated example:client.on('ready', async () => { console.log(`${client.user.tag} has logged in`); // Fetch the old messages that may have reactions on them try { const channel = await client.channels.fetch(channelId); if (!channel) { console.error(`Channel not found with id: ${channelId}`); return; } const messages = await channel.messages.fetch({ limit: 100 }); messages.forEach(message => { // Do something with each message }); } catch (error) { console.error('Error fetching old messages:', error); } });In this example, we've added an statement to check if the variable is null or undefined before continuing. If it is, we log an error message and return early. If the is found, we proceed to fetch the old messages as normal. Also, we've wrapped the entire block in a try-catch block to catch any errors that might occur when fetching the old messages. This way, if there's an error, we log an error message instead of crashing the whole program.
- User
fetch messages using the guild property
- Assistant
To fetch messages using the
Guildproperty, you can use thefetch()method on aTextChannelobject with thebeforeandlimitoptions set. Here's an example:const guild = client.guilds.cache.get(guildId); if (!guild) { console.error(`Could not find guild with ID ${guildId}`); return; } const channel = guild.channels.cache.get(channelId); if (!channel || channel.type !== 'GUILD_TEXT') { console.error(`Could not find text channel with ID ${channelId}`); return; } const options = { limit: 100 }; const messages = await channel.messages.fetch(options); messages.forEach((message) => { console.log(`ID: ${message.id}, content: ${message.content}`); });In this example, we first get the
Guildobject by its ID usingclient.guilds.cache.get(guildId). We check if the guild exists, and if not, log an error message and return early.Next, we get the
TextChannelobject from the guild's channels cache using . We also check if the channel exists and is a text channel (not a voice channel, for example).