Day Grouping in the Chat Log Parser!

Finally, I’ve added a feature to my chat log parser to group messages by day. It’s something I’ve wanted to be able to do for a while now. This took a bit of work to add a new data structure and update the HTML Jinja2 templates. But now the base of it is done and if I want, I can customise the styles.

Screenshot of Chat Log with day grouping

Oh hey Sunny!

Originally, I tried to do the day grouping inside the Jinja2 templates, but this proved rather difficult – I ended up spending hours in the library trying to work out nested loops inside a templating language. Eventually, I realised I should perform the day grouping on the data structure instead, so I just loop over each day, then created the minute bundles inside.

Technical Info!

Creating the day grouping in the ChatLog data structure turned out to be surprisingly easy:

def group_by_day(self) -> List[List[Message]]:
        """
        Groups messages by day
        :return: list
        """
        days: list = []
        for i, msg in enumerate(self._messages.items()):
            if i == 0:
                days.append([])
                days[0].append(msg[1])
            elif msg[1].timestamp.date() == self._messages[i-1].timestamp.date():
                days[-1].append(msg[1])
            elif msg[1].timestamp.date() != self._messages[i-1].timestamp.date():
                days.append([])
                days[-1].append(msg[1])
        return days

Basically, I loop over each item in the ChatLog: if it’s the first item, create a new sub-list and add that message to it. If the current message has the same date as the previous message, append that message to the most recent sub-list. If it’s a different date, add a new sub-list to the parent list and add the current message to that one. Then I can simply return the main list to the template and loop over each inner list which contains Message objects.

This actually makes the templates easier to read too because I have a more logical (but complex) data structure.

Have at it!

The updated code is now available on Github (chat log parser). Also, feel free to fork it and help with the styling or if you have any suggestion on how to fix the Facebook sender issue, let me know!

Posted by Anthony