Bobjoerules
Bobjoerules

Reputation: 29

How could i use user id instead of mention on discord.js to give role?

This is my code for mentions but I want to use id instead

if (message.member.roles.cache.some(r => r.name === "Mod")) {
    if (message.mentions.members.first()) {
        let role = message.guild.roles.cache.find(r => r.name === "Muted");
        let member = message.mentions.members.first();
        member.roles.add(role);
        message.channel.send(member);
    }
}

Here is what I say for mention: moder! Mute @bigboitest What I want to do: moder! Mute 862743465594191882

Upvotes: 0

Views: 303

Answers (1)

Tyler2P
Tyler2P

Reputation: 2370

Simply, to get the user from their ID you'll need to find the ID in a message and then search for it in the clients users.
Example:

let args = <Message>.content.split(/ +/g); // Define message arguments
let member = <Message>.mentions.users.first() || <Message>.guild.members.fetch(args[2]); // Get the user from a mention or ID

Full example:

if (message.member.roles.cache.some(r => (r.name).toLowerCase() === "mod")) { // Search for the role "Mod"
    let role = message.guild.roles.cache.find(r => (r.name).toLowerCase() === "muted"); // Search for the "Muted" role
    let args = message.content.split(/ +/g); // Define message arguments
    let member = message.mentions.members.first() || message.guild.members.fetch(args[2]); // Get the user from a mention or ID

    if (!role) return message.channel.send('I cannot find a muted role'); // If the role doesn't exist, notify the user
    if (!member) return message.channel.send(`<@!${message.author.id}>, ${member} is not in this server`); // If the member doesn't exist

    member.roles.add(role); // Mute the member by adding the muted role
    message.channel.send(`<@!${member.user.id}> was muted by <@!${message.author.id}`); // Send a response
} else {
    message.channel.send('You are not a mod'); // Notify the user that they are not able to use the command
}

Upvotes: 1

Related Questions