Python Discord Bot: Efficiently Tallying User Message Counts

I am developing a Discord bot in Python to analyze channel data by determining how many messages each user posts. My current approach involves iterating through a channel’s history to count messages from the user who issued the command. Here is a revised example:

if incoming_message.text.startswith('!stats'):
    status_reply = await bot.post_message(incoming_message.channel, 'Counting messages...')
    total_messages = 0
    async for entry in bot.fetch_history(incoming_message.channel, max_count=5000000):
        if entry.author == incoming_message.author:
            total_messages += 1
    await bot.modify_message(status_reply, f"{incoming_message.author} has posted {total_messages} messages in this channel.")

The current method is slow since it processes a vast number of messages. Is there a more optimized method to achieve the same result?

Rather than iterating through every message in the channel, I found that keeping a running tally with event listeners is far more efficient. In my projects, I record the message count at the time of message reception and store this data in a database or an in-memory cache. This way, when someone requests stats, the bot can simply query the stored count rather than processing thousands of messages. Although this method requires additional management of state, it typically results in a significant performance improvement.