2

I am using Discord.py Rewrite to make a Discord bot. I have a command called work, with the following code:

import discord
from discord.ext import commands
client = commands.Bot(command_prefix="c!")
# on_ready command
@client.command()
async def work(ctx):
 author_id = ctx.author.id
 currency_dict[author_id] += 50
 await ctx.send("You Gained 50 Coins")
# currency_dict is a dictionary that is already defined

Is there any way to make it so that the user can only use the command once every 30 seconds? Thanks!

asked Dec 19, 2020 at 23:34

1 Answer 1

5

First, you would have to import from discord.ext.commands.cooldowns import BucketType. This is what will help you with cooldowns. Below is both the cooldown check as well as the max_concurrency check you can use with this import.

from discord.ext.commands.cooldowns import BucketType
# BucketType can be BucketType.default, member, user, guild, role, or channel
@commands.cooldown(rate,per,BucketType) 
# Limit how often a command can be used, (num per, seconds, BucketType)
@commands.max_concurrency(number, per=BucketType.default, *, wait=False)
# Limit how many instances of the command can be running at the same time.
# Setting wait=True will queue up additional commands. False will raise MaxConcurrencyReached
# Checks can be stacked, and will Raise a CheckFailure if any check fails.

In your case, you would want to use commands.cooldown(rate,per,BucketType).

import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
client = commands.Bot(command_prefix="c!")
# on_ready command
@client.command()
@commands.cooldown(1,30,commands.BucketType.user) # one command, every 30 seconds, per user
async def work(ctx):
 author_id = ctx.author.id
 currency_dict[author_id] += 50
 await ctx.send("You Gained 50 Coins")
# currency_dict is a dictionary that is already defined
# cooldown error-handling
@work.error
async def work_error(ctx, error):
 if isinstance(error, commands.CommandOnCooldown):
 await ctx.send(f'This command is on cooldown, you can use it in {round(error.retry_after, 2)} seconds')

references:

answered Dec 20, 2020 at 2:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.