瀏覽代碼

Video preview descriptions truncated to avoid API errors

main
Rocketsoup 1 周之前
父節點
當前提交
859abbaf66
共有 2 個文件被更改,包括 21 次插入0 次删除
  1. 2
    0
      rocketbot/cogs/videopreviewcog.py
  2. 19
    0
      rocketbot/utils.py

+ 2
- 0
rocketbot/cogs/videopreviewcog.py 查看文件

@@ -13,6 +13,7 @@ from rocketbot.utils import (
13 13
 	blockquote_markdown,
14 14
 	format_bytes,
15 15
 	suppress_markdown_url_previews,
16
+	truncate_markdown,
16 17
 )
17 18
 
18 19
 
@@ -205,6 +206,7 @@ class VideoPreviewCog(BaseCog, name='Video Link Previews'):
205 206
 			link_description += f", {format_bytes(best_format.get('filesize_approx'))}"
206 207
 		content = "Here's a preview of that video link."
207 208
 		if len(description) > 0:
209
+			description = truncate_markdown(description, 1000)
208 210
 			content += "\n\n" + blockquote_markdown(suppress_markdown_url_previews(description)) + "\n"
209 211
 		if link.spoiler:
210 212
 			content += f"\n||[{link_description}]({video_url})||"

+ 19
- 0
rocketbot/utils.py 查看文件

@@ -195,6 +195,25 @@ def suppress_markdown_url_previews(markdown: str) -> str:
195 195
 	"""Finds URLs in markdown and encloses them in <...> to suppress the preview."""
196 196
 	return re.sub(r'(?<!<)(https?://\S+)(?!>)', '<\\1>', markdown)
197 197
 
198
+def truncate_markdown(markdown: str, max_length: int) -> str:
199
+	"""Truncates markdown in a way that attempts to minimize formatting disruption."""
200
+	if len(markdown) <= max_length:
201
+		return markdown
202
+	markdown = markdown[:max_length]
203
+
204
+	# Try to cut at a newline if it's in the latter 20% of the max length
205
+	last_newline_index = markdown.rfind('\n')
206
+	if last_newline_index >= 0 and last_newline_index < (max_length * 8 / 10):
207
+		return markdown[:last_newline_index] + "\n\u2026"
208
+
209
+	# Cut at the last space
210
+	last_space_index = markdown.rfind(' ')
211
+	if last_space_index >= 0:
212
+		return markdown[:last_space_index] + " \u2026"
213
+
214
+	# Last resort, do a blind substring
215
+	return markdown[:max_length - 1] + "\u2026"
216
+
198 217
 def format_bytes(size: int) -> str:
199 218
 	"""Formats s size in bytes to a human readable description (e.g. "3.2 KiB")"""
200 219
 	size = max(size, 0)

Loading…
取消
儲存