Skip to content

Commit

Permalink
Fix truncated events from breaking calendar
Browse files Browse the repository at this point in the history
  • Loading branch information
cbrxyz committed Mar 6, 2024
1 parent 8b148c2 commit b8a8ab2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
25 changes: 17 additions & 8 deletions src/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 5 additions & 3 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit b8a8ab2

Please sign in to comment.