discorddiscord.js

Discord bot that allows members to assign roles to other members


I'm VERY new to coding in JavaScript and I'm trying to create a very simple bot for an event I'm planning in a Discord server.

Basically all it should do is assign a role to a mentioned member (only the first member) if the mentioned member doesn't have a role set in an array.

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const ignoredRoles = ["Overseer, Staff, Bots"],
    mutedRole = "Dead";
client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`) });
client.on("message", (message) => {
    if (message.content.startsWith("!kill")) {
        let member = message.mentions.members.first();
        if (!member)
            return message.channel.send('You forgot to mention who to kill');
        if (member.roles.find(r => ignoredRoles.includes(r.name)))
            return message.channel.send(`${member.toString()} is not participating in the event!`);
        if (member.roles.find(r => r.name == mutedRole))
            return message.channel.send(`${member.toString()} user is already dead!`);
        member.roles.add(mutedRole)
        message.channel.send(`${member.toString()} has been eliminated!`);
    }
});
client.login('token.env');

While the code itself doesn't throw any errors (the bot logs in and it prints the ready state), any time I attempt to summon the bot it does absolutely nothing. I don't think my skill is good enough to figure this out on my own, so any help would be highly appreciated! Thanks!


Solution

  • You'll need to do this in 4 steps:

    Step 1(Get user and ID at the same time):

    //this'll fetch the first user mentioned, ".id" will return user's id
    let member = message.mentions.users.first().id;
    

    Step 2(Fetch the role):

    //replace [Role ID] by role's actual ID.
    let role = message.guild.roles.cache.find(r => r.id === "[Role ID]");
    

    Step 3:(Check if user has a role)

    if (message.member.roles.cache.find(role)){
      //user is having role, tell them that they already have the role.
    }
    

    Step 4:(Add role to member, continue this after step 3)

    else{
      // Add role to the member
      member.roles.add(role);
    }
    

    Final Code:

    let member = message.mentions.users.first().id;
    let role = message.guild.roles.cache.find(r => r.id === "[Role ID]");
    
    if (message.member.roles.cache.find(role)){
      //user is having role, tell them that they already have the role.
    } else {
      // Add role to the member
      member.roles.add(role);
    }
    

    Please check discord.js official docs, you can find everything related to discord.js there.