How do I count the number of messages per day in pycord?

Question:

So I basicly count all the messages in a channel.
I also want to count the number of messages per day.
I know message.created_at returns a datetime, but how do I count how many times a date is present in this list?

this is my current code:

count = 0
async for message in channel.history(limit=None):
    count += 1
    print(message.created_at)

I tried to do it like this:

count = 0
async for message in channel.history(limit=None):
    count += 1
    dates.append(message.created_at)
print(dates.count(dates[0]))

But this just returns "1" (while there are far more different days in the list)

This is my first post on stack overflow, don’t be toxic please, feedback is welcome!

Asked By: Infinibyte

||

Answers:

Your code isn’t counting the number of messages on a certain date, it’s counting the message on a certain datetime.datetime object, which represents a specific point in time (could be down to a microsecond depending on the API precision).

This is because message.created_at returns the time and date of the message, what you want is probably message.created_at.date() (see datetime docs).

If you want to know for each date how many messages there were, you can use a dictionary to count:

messages_per_date = {}  # empty dictionary
async for message in channel.history(limit=None):
    message_date = message.created_at.date()
    # Add the date to the dictionary if necessary
    if message_date not in messages_per_date:
        messages_per_date[message_date] = 0
    # Increment the number of messages on that date
    messages_per_date[message_date] += 1
# Print the number of messages today
print(messages_per_date[datetime.date.today()])

You can use collections.defaultdict to make the code significantly shorter:

import collections

# This creates a dictionary in which the default value is zero
messages_per_date = collections.defaultdict(int)

async for message in channel.history(limit=None):
    # Now the values can be incremented without checking the key
    messages_per_date[message.created_at.date()] += 1

print(messages_per_date[datetime.date.today()])
Answered By: Zeroji
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.