Search code examples
javascriptnode.jsdiscorddiscord.jsnedb

Use Discord.js/Node.js/NeDB to Remove Role From User After X Number of Hours


I'm relatively new to Javascript and Node, but I have managed to create a bot for my discord server and implement a basic economy, granting points based off of post submissions. These points are stored in an NeDB. I'd like to allow users to redeem points to give someone a specific role for X amount of time.

I'm not sure how to even begin approaching this problem. Do I log a timestamp in my NeDB database with the user ID, and then somehow check this database at regular intervals to see if the timestamp has elapsed? Can I do this without blocking the bots other regular functions and command responses?

Additionally, how might I make the code robust so that if my bot disconnects unexpectedly, the user is not stuck with the temporary role?

I'm curious how someone with programming experience might approach this problem, and what solutions might be available that I don't know about.

Thank you so much in advance!


Solution

  • In your index.js file, you can create a function that will connect to your database, check if enough time has elapsed for each entry (have it logged earlier in a database), and act accordingly. Then, you can call this function repeatedly with:

    setInterval(functionName, intervalMilliseconds);
    

    The above line only needs to be run once. The function will be called regularly and this won't block the rest of your bot's functions. Since this command would be run every time the bot restarts, you will always be checking the database and acting appropriately as long as the bot is online (make sure you are storing the NeDB database as a file, not in memory).