pythondiscorddiscord.pydisnake

Add different cooldown for different users for python bot


I use disnake library in python. I have list of premium users in bot and I want they to have a shorter cooldown for commands, than regular users. For example regular users have cooldown of 10 s, and premium users have cooldown of 3 s

import disnake
from disnake.ext import commands


pro_users = [1234567890, 907508957384]
intents = disnake.Intents.all()
client = commands.InteractionBot(intents=intents)


@commands.cooldown(1, 10, commands.BucketType.user)
@client.slash_command()
async def super_command(inter):
    await inter.channel.send('Hello')


client.run('TOKEN')

I had an idea to raise CooldownError in command's body, but I want to know if I can do it without raising


Solution

  • I think you could do this by having your own cooldown method. By having some kind of data structure that tracks when a user last used the command you can have different cooldowns for different users.

    import datetime
    
    pro_users = [1234567890, 907508957384]
    SUPER_COOLDOWNS = {}
    NORMAL_TIMEOUT = 60 # in seconds
    PRO_TIMEOUT = 30 # in seconds
    
    intents = disnake.Intents.all()
    client = commands.InteractionBot(intents=intents)
    
    
    @client.slash_command()
    async def super_command(inter):
        user_id = inter.author.id
        now = datetime.datetime.now()
    
        if prev_time := SUPER_COOLDOWNS.get(user_id):
            timeout = PRO_TIMEOUT if user_id in pro_users else NORMAL_TIMEOUT
            if (now - prev_time).total_seconds() < timeout:
                message = f"You used this command too recently. Please wait `{timeout}` seconds."
                await inter.send(message, ephemeral=True)
    
        # set the time they last used the command to now
        SUPER_COOLDOWNS[user_id] = now
        await inter.channel.send('Hello')
    

    You can expand the SUPER_COOLDOWNS dict as needed, etc. But hopefully you get the gist.