diff --git a/src/calendar.py b/src/calendar.py index fb97a80..1d6e1b3 100644 --- a/src/calendar.py +++ b/src/calendar.py @@ -238,14 +238,23 @@ async def update_channel_name(self, events: list[Event]) -> None: await channel.edit(name=new_name) def events_list_str(self, events: list[Event]) -> str: - strs = [event.embed_str() for event in events] - estimated_length = sum(len(s + "\n") for s in strs) + len("_... (truncated)_") - if estimated_length > 1024: - strs = [event.embed_str() for event in events if event.upcoming()] - if events[0].embed_str() != strs[0]: - # This means that the first event will not be shown, so we should - # mark that - strs.insert(0, "_... (truncated)_") + upcoming_events = [event for event in events if event.upcoming()] + past_events = [event for event in events if not event.upcoming()] + + upcoming_strs = [event.embed_str() for event in upcoming_events] + strs = upcoming_strs.copy() + past_strs = [event.embed_str() for event in past_events][::-1] + max_length = 1024 - len("_... (99 before)_") - len("\n".join(upcoming_strs)) + for event in past_strs: + if max_length - len(event + "\n") > 0: + max_length -= len(event + "\n") + strs.insert(0, event) + else: + strs.insert( + 0, + f"_... ({len(past_strs) - (len(strs) - len(upcoming_strs))} before)_", + ) + return capped_str(strs) or "No events scheduled." @tasks.loop(minutes=5) diff --git a/src/utils.py b/src/utils.py index 50d4214..4438be5 100644 --- a/src/utils.py +++ b/src/utils.py @@ -109,12 +109,14 @@ def capped_str(parts: list[str], cap: int = 1024) -> str: Joins the most parts possible with a new line between them. If the resulting length is greater than the cap length, then the remaining parts are truncated. - If the parts are capped, "_... (truncated)_" is appended to the end. + If the parts are capped, "_... (X after)_" is appended to the end. """ result = "" + made_it = 0 for part in parts: - if len(result) + len(part) + len("\n... (truncated)") > cap: - result += "_... (truncated)_" + if len(result) + len(part) + len("\n_... (99 after)_") > cap: + result += f"_... ({len(parts) - made_it} after)_" break result += part + "\n" + made_it += 1 return result.strip()