Search code examples
javascriptbotsdiscorddiscord.jsroles

How do i make a discord bot that simply gives me a role when i type a certain phrase in Javascript?


I've done tons and tons of searches but they're all super complex codes such as, when i say "!Role (role)" then it gives me the role i specified. However, what i am looking for is something much simpler like if i were to say "Hello", then the bot would give me the role that's in the code.

I also tried a lot of the complex ones but most of them used the "addRole" function but the output didn't like it

Do you think you can help me with this?


Solution

  • Discord JS V12:

    client.on("message", (message) => {
        // Checking if the message equals to "hello".
        // Since we use .toLowerCase() which converts any uppercase letter to lowercase, HeLLo will result in hello.
        if (message.content.toLowerCase() == "hello") {
            // Trying to find the role by ID.
            const Role = message.guild.roles.cache.get("RoleID");
            // Checking if the role exists.
            if (!Role) { // The role doesn't exist.
                message.channel.send(`I'm sorry, the role doesn't exist.`);
            } else { // The role exists.
                // Adding the role to the user.
                message.member.roles.add(Role).catch((error) => {console.error(error)});
                message.channel.send(`You received the role ${Role.name}.`);
            };
        }
    });
    

    Discord JS V11:

    client.on("message", (message) => {
        if (message.content.toLowerCase() == "hello") {
            const Role = message.guild.roles.get("RoleID");
            if (!Role) {
                message.channel.send(`I'm sorry, the role doesn't exist.`);
            } else {
                message.member.addRole(Role).catch((error) => {console.error(error)})
                message.channel.send(`You received the role ${Role.name}.`);
            };
        }
    });