Search code examples
discord.js

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


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 :)


Solution

  • 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);