Search code examples
pythondiscorddiscord.pychatbot

cooldown on an on_message event, discord.py


I'm trying to apply a cooldown on the on_message event. how can I do that?

here is the code

import discord
from discord.ext import commands
json
import os

client = commands.Bot(command_prefix = '!')

#more code

@client.event
async def on_message(message):
  await open_account(message.author) #opens an account in a json file for this particular user
  
   users = await get_users_data() #returns the users in the json file
   user = message.author

   #more code

this code is used for a leveling system and I would like it to only happen every 1 minute once so people won't spam, how can that be done?


Solution

  • This isn't possible in discord.py. A custom handler is necessary. For example:

    COOLDOWN_AMOUNT_SECONDS = 60
    last_executed = {}
    
    async def on_message(message):
        # ...
        if last_executed.get(message.author.id, 1.0) + COOLDOWN_AMOUNT_SECONDS < time.time():
            do_things()
            last_executed[message.author.id] = time.time()
        else:
            do_things_if_the_cooldown_isnt_over_or_just_do_nothing()
    

    This keeps a dict last_executed with the timestamp that the event ran for each user. Every time it is fired, it checks that enough time has passed, and if so, does things and sets the time to the current time.