'Making a Discord bot assign a role after a certain time from the member join date?

I have no idea how to make my discord bot able to assign a role after a certain time from the join date. Someone suggested me to use node-cron, but i have no idea how to implement it correctly, because the bot seems to ignore the code. Any ideas?



Solution 1:[1]

You can use setTimeout, for example you can use it like that :

client.on("guildMemberAdd", member => {
    setTimeout(() => {
        // Add role to member
    }, 1000 * 60 /* Time in ms here */);
});

More informations about setTimeout

Solution 2:[2]

The best way to do this is saving the join date, and in another recurrent cron comprove if the join date - current date >= neccessary time.

I recommend this way, because if you use setTimeout or similar methods, when your bot shuts down, this action will be lost and will never be executed.

To do this, you will need to store this data externally (in a database or even in a text file).

Solution 3:[3]

It all depends on how long they need to be in the guild, if say a few minutes or so, then both of the above answers would work (may be helpful if they showed how though) otherwise cron jobs work great, the do not go into any event listener. So you would add this to the main bot.js file.

Key - for other methods you can use this site to build your key

every min = '*/1 * * * *'
every hour = '0 */1 * * *'
every day @ midnight = '0 0 * * *'
const cron = require('node-cron');
// as example runs every min
cron.schedule('*/1 * * * *', function () {
    const guild = client.guilds.cache.get(guildID);
    guild.memmbers.cache.fetch().forEach(member => {
        if (member.roles.cache.has(roleID)) {
            return;
        } else {
            // 2 months as an example is 5259600000
            if (member.joinedTimestamp - new Date().getTime() >= 5259600000) {
                member.roles.add(roleID)
            }
        }
    })
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KristN
Solution 2 Danild Zambrana
Solution 3 Gh0st