Search code examples
pythonpython-3.xdiscorddiscord.py

How can i make this command to be used once in 3 days?


Im making a command that sends an api key for my website but i don't want it to get abused so i need the command to be used once in 3 days (72 hours) Or once in 2 days or even 1 day i just don't want it to get regenerated every second

This is my code atm

@bot.command()
async def key(ctx):
  await ctx.send(next(keys))

By the way if you're curious the api keys are in a txt file.


Solution

  • You can save the last access timestamp to a file and check if the cooldown time has already passed with datetime.timedelta You could do it like this:

    from datetime import datetime, timedelta
    
    
    @bot.command()
    async def key(ctx):
        def save_timestamp(timestamp):  # Function to save the timestamp to file
            timestamp = int(timestamp)
            with open("last_credentials.txt", 'w') as f:
                f.write(str(timestamp))
    
        try:  # Try reading last credentials usage from file 'last_credentials.txt'
            with open("last_credentials.txt", 'r') as f:
                timestamp = int(f.read())
    
        except FileNotFoundError:
            # Create new timestamp if the file does not exist
            timestamp = datetime(year=1970, day=1, month=1).timestamp()
    
        creds_datetime = datetime.fromtimestamp(timestamp)
    
        if datetime.now() - creds_datetime > timedelta(hours=72):  # check if 3 days have passed from last usage. You could also use days=3 instead of hours=72
            save_timestamp(datetime.now().timestamp())
            await ctx.send(next(keys))
    

    You could also store this timestamp in memory, but that would not keep last timestamp in case you would restart your program