Search code examples
javascriptnode.jsdiscorddiscord.jsbots

How can I give discord users with a specific role limitations?


I want to limit the actions of users on a discord server that are interacting with a discord bot for a specific time. As an example: The user with the role "user" can only press a button 10 times in a day (24h). A other user with the role "user2" can press the button 20 times in a day. After that the user gets a message that he reached the daily limit. How can I do that in js?

I couldn't find anything about the topic.


Solution

  • You have to create a function that will check whenever the member is rate limited and another where you add 1 to the limit. I decided to merge those 2 functions so you can call it when someone runs a command and it will add 1 to the limit.

    I assume that this is for a guild (since its role-based). So you must give a GuildMember as a variable of the function.

    let Limits = {};
    
    function isRateLimited(member){
        let Today = new Date();
        Limits[member.id] ??= {Date:Today,Rate:0}; //if Limits[member.id] has no value, then it will set it as an object.
        if(!(Limits[member.id].Date.getDate() == Today.getDate() && Limits[member.id].Date.getMonth() == Today.getMonth() && Limits[member.id].Date.getFullYear() == Today.getFullYear())){//if not today, then reseting the rate limit & setting date as today.
            Limits[member.id].Date = Today;
            Limits[member.id].Rate = 0;
        };
        if(member.roles.cache.find(role => role.name == "ROLE 1") && Limits[member.id].Rate < 20){ //if member has a specific role and his rate limit is lower than authorized, then adding 1 to the rate limit and returning true
            Limits[member.id].Rate++;
            return true;
        }else if(member.roles.cache.find(role => role.name == "ROLE 2") && Limits[member.id].Rate < 10){ //if member has a specific role and his rate limit is lower than authorized, then adding 1 to the rate limit and returning true
            Limits[member.id].Rate++;
            return true;
        }else if(member.roles.cache.find(role => role.name == "ROLE 3") && Limits[member.id].Rate < 5){ //if member has a specific role and his rate limit is lower than authorized, then adding 1 to the rate limit and returning true.
            Limits[member.id].Rate++;
            return true;
        };
        return false; //the member is rate limited (he has reached the limit), it will return false;
    }