Count the number of messages in a given time period

Viewed 191

For a Discord server, I have a bot that whenever the frequency of messages from members is too great, the bot enables slowmode. The problem is that I do not know how to tackle the problem (i.e. how do you detect the number of messages in any time span?). I just need to divide numberOfMessages by timePeriod (timePeriod will reset itself every 10 seconds so that we take the average messages per 10 seconds.)


How do I get the number of messages that were sent in the last 10 seconds?

1 Answers

To retrieve messages sent within a certain period of time, you can use the TextChannel history method:

In this method, there are two parameters that will interest you, before and after. You can specify a minimum date (in datetime or snowflake) and a maximum post date for the messages that will be returned in your channel history. So here it's after that will interest you, with your datetime.now() -10s.

(And then you apply len() on your history which is returned to you at the end)


Attention: discord.py is discontinued, use another fork, like nextcord.

Related