Skip to content

Attach some long code links in files #233

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
26 changes: 18 additions & 8 deletions app/components/github_integration/code_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import string
import urllib.parse
from collections.abc import AsyncIterator
from io import BytesIO
from typing import NamedTuple

import discord
Expand Down Expand Up @@ -96,7 +97,7 @@ async def get_snippets(content: str) -> AsyncIterator[Snippet]:
)


def _format_snippet(snippet: Snippet) -> str:
def _format_snippet(snippet: Snippet, *, include_body: bool = True) -> str:
repo_url = f"https://github.com/{snippet.repo}"
tree_url = f"{repo_url}/tree/{snippet.rev}"
file_url = f"{repo_url}/blob/{snippet.rev}/{snippet.path}"
Expand All @@ -115,37 +116,46 @@ def _format_snippet(snippet: Snippet) -> str:
f"[`{unquoted_path}`](<{file_url}>), {range_info}"
f"\n-# Repo: [`{snippet.repo}`](<{repo_url}>),"
f" {ref_type}: [`{snippet.rev}`](<{tree_url}>)"
f"\n```{snippet.lang}\n{snippet.body}\n```"
)
) + (f"\n```{snippet.lang}\n{snippet.body}\n```" * include_body)


async def snippet_message(message: discord.Message) -> tuple[str, int]:
async def snippet_message(
message: discord.Message,
) -> tuple[tuple[str, list[discord.File]], int]:
snippets = [s async for s in get_snippets(message.content)]
if not snippets:
return "", 0
return ("", []), 0

blobs = list(map(_format_snippet, snippets))

if len(blobs) == 1 and len(blobs[0]) > 2000:
# When there is only a single blob which goes over the limit, upload it
# as a file instead.
fp = BytesIO(snippets[0].body.encode())
file = discord.File(fp, filename=f"code.{snippets[0].lang}")
return (_format_snippet(snippets[0], include_body=False), [file]), 1

if len("\n\n".join(blobs)) > 2000:
while len("\n\n".join(blobs)) > 1970: # Accounting for omission note
blobs.pop()
if not blobs:
return "", -1 # Signal that all snippets were omitted
return ("", []), -1 # Signal that all snippets were omitted
blobs.append("-# Some snippets were omitted")
return "\n".join(blobs), len(snippets)
return ("\n".join(blobs), []), len(snippets)


async def reply_with_code(message: discord.Message) -> None:
if message.author.bot:
return
msg_content, snippet_count = await snippet_message(message)
(msg_content, files), snippet_count = await snippet_message(message)
if snippet_count != 0:
await message.edit(suppress=True)
if snippet_count < 1:
return

sent_message = await message.reply(
msg_content,
files=files,
suppress_embeds=True,
mention_author=False,
allowed_mentions=discord.AllowedMentions.none(),
Expand Down
1 change: 0 additions & 1 deletion app/components/github_integration/comments/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,4 @@ async def comment_processor(msg: discord.Message) -> tuple[list[discord.Embed],
message_processor=comment_processor,
interactor=reply_with_comments,
view_type=DeleteMention,
embed_mode=True,
)
1 change: 0 additions & 1 deletion app/components/xkcd_mentions.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,4 @@ async def handle_xkcd_mentions(message: discord.Message) -> None:
message_processor=xkcd_mention_message,
interactor=handle_xkcd_mentions,
view_type=DeleteButton,
embed_mode=True,
)
35 changes: 22 additions & 13 deletions app/utils/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from collections import defaultdict
from collections.abc import Awaitable, Callable
from contextlib import suppress
from typing import cast

import discord

Expand Down Expand Up @@ -48,23 +47,27 @@ def unlink_if_expired(self, reply: discord.Message) -> bool:
return False


def create_edit_hook( # noqa: PLR0913
def create_edit_hook(
*,
linker: MessageLinker,
message_processor: Callable[
[discord.Message], Awaitable[tuple[str | list[discord.Embed], int]]
[discord.Message],
Awaitable[
tuple[str | tuple[str, list[discord.File]] | list[discord.Embed], int]
],
],
interactor: Callable[[discord.Message], Awaitable[None]],
view_type: Callable[[discord.Message, int], discord.ui.View],
view_timeout: float = 30.0,
embed_mode: bool = False,
) -> Callable[[discord.Message, discord.Message], Awaitable[None]]:
def resolve_embed_mode(
content: str | list[discord.Embed],
) -> tuple[str, list[discord.Embed]]:
if embed_mode:
return "", cast("list[discord.Embed]", content)
return cast("str", content), []
def extract_content(
content: str | tuple[str, list[discord.File]] | list[discord.Embed],
) -> tuple[str, list[discord.File], list[discord.Embed]]:
if isinstance(content, list):
return "", [], content
if isinstance(content, str):
return content, [], []
return content[0], content[1], []

async def edit_hook(before: discord.Message, after: discord.Message) -> None:
if before.content == after.content:
Expand All @@ -76,7 +79,7 @@ async def edit_hook(before: discord.Message, after: discord.Message) -> None:
return

if not (replies := linker.get(before)):
if not old_objects[1]:
if old_objects[1] <= 0:
# There were no objects before, so treat this as a new message
await interactor(after)
# The message was removed from the linker at some point
Expand All @@ -93,11 +96,17 @@ async def edit_hook(before: discord.Message, after: discord.Message) -> None:
if linker.unlink_if_expired(reply):
return

content, embeds = resolve_embed_mode(content)
content, files, embeds = extract_content(content)
if not (content or files or embeds):
# The message is empty, don't send a message with only a view
linker.unlink(before)
await reply.delete()
return
await reply.edit(
content=content,
embeds=embeds,
suppress=not embed_mode,
attachments=files,
suppress=not embeds,
view=view_type(after, count),
allowed_mentions=discord.AllowedMentions.none(),
)
Expand Down