Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix truncated events from breaking calendar #30

Merged
merged 1 commit into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Loading