discord.py command cooldown for ban command

Jack Thorn

I've got this code for my bot, which allows banning users for certain people. However, is there a way to make it so that a staff member can only use the ban command once every 2 hours. I want every other command to have no cooldown, but just for the ban command, have a way to only allow it to be used once per 2 hours per user. Here's the code I've got so far:

@commands.has_permissions(administrator=True)
async def pogoban (ctx, member:discord.User=None, *, reason =None):
    if member == None or member == ctx.message.author:
        await ctx.channel.send("You cannot ban yourself")
        return
    if reason == None:
        reason = "For breaking the rules."
    message = f"You have been banned from {ctx.guild.name} for {reason}"
    await member.send(message)
    await ctx.guild.ban(member, reason=reason)
    await ctx.channel.send(f"{member} is banned!")

What would I need to add/change to add a command cooldown of 2 hours per user for this command. I've tried looking around, but I've only found ways to make all commands have a cooldown, instead of this one specific command. Thanks!

Sujit

How about something like this:

cooldown = []

@client.command()
async def pogoban(ctx, member: discord.Member = None, *, reason = None):
    author = str(ctx.author)
    if author in cooldown:
        await ctx.send('Calm down! You\'ve already banned someone less that two hours ago.')
        return

    try:
        if reason == None:
            reason = 'breaking the rules.'
        await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
        await member.ban(reason = reason)
        await ctx.send(f'{member.mention} has been banned.')
        cooldown.append(author)
        await asyncio.sleep(2 * 60 * 60)    #The argument is in seconds. 2hr = 7200s
        cooldown.remove(author)
    except:
        await ctx.send('Sorry, you aren\'t allowed to do that.')

Note: Remember to import asyncio. Also remember that once your bot goes offline, all the users stored in the list will be erased.


Please Read

A better approach would be to store the time of banning along with the the authors name and check if the current time is at least an hour more than the saved time. And to make it a lot safer, the authors name along with the time can be saved in a database or an external text file, this way your data won't get erased if the bot goes offline.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related