0
votes

I am fairly new to programming. I've been trying to create a discord bot with the sole purpose of the bot messaging in chat when a specific user is talking. My code works but i want to add a cooldown timer so it is not happening everytime the user talks (otherwise it would be very annoying!)

I have tried to use @commands.cooldown(1, 1000, commands.BucketType.user) but I understand it is only for commands and not events. I have spent a while trying to research what to code to use but I'm really struggling. Does anybody have any suggestions? Many thanks.

@bot.event
@commands.cooldown(1, 1000, commands.BucketType.user)
async def on_message(message):
    if message.author == bot.user:
        return
        
    if message.author.id == XXXXXXX40387821569:
        await message.channel.send('Haaaaaaaaaaaarrrryyyyy!')
1

1 Answers

1
votes

You need to implement a custom cooldown handler for this, but it's pretty simple.

COOLDOWN_AMOUNT = 4.0  # seconds
last_executed = time.time()
def assert_cooldown():
    global last_executed  # you can use a class for this if you wanted
    if last_executed + COOLDOWN_AMOUNT < time.time():
        last_executed = time.time()
        return True
    return False


@client.event
async def on_message(message):
    if message.author.id == client.user.id:
        return
    if not assert_cooldown():
        return
    await message.channel.send('a')