Просмотр исходного кода

Video preview descriptions truncated to avoid API errors

main
Rocketsoup 1 неделю назад
Родитель
Сommit
859abbaf66
2 измененных файлов: 21 добавлений и 0 удалений
  1. 2
    0
      rocketbot/cogs/videopreviewcog.py
  2. 19
    0
      rocketbot/utils.py

+ 2
- 0
rocketbot/cogs/videopreviewcog.py Просмотреть файл

13
 	blockquote_markdown,
13
 	blockquote_markdown,
14
 	format_bytes,
14
 	format_bytes,
15
 	suppress_markdown_url_previews,
15
 	suppress_markdown_url_previews,
16
+	truncate_markdown,
16
 )
17
 )
17
 
18
 
18
 
19
 
205
 			link_description += f", {format_bytes(best_format.get('filesize_approx'))}"
206
 			link_description += f", {format_bytes(best_format.get('filesize_approx'))}"
206
 		content = "Here's a preview of that video link."
207
 		content = "Here's a preview of that video link."
207
 		if len(description) > 0:
208
 		if len(description) > 0:
209
+			description = truncate_markdown(description, 1000)
208
 			content += "\n\n" + blockquote_markdown(suppress_markdown_url_previews(description)) + "\n"
210
 			content += "\n\n" + blockquote_markdown(suppress_markdown_url_previews(description)) + "\n"
209
 		if link.spoiler:
211
 		if link.spoiler:
210
 			content += f"\n||[{link_description}]({video_url})||"
212
 			content += f"\n||[{link_description}]({video_url})||"

+ 19
- 0
rocketbot/utils.py Просмотреть файл

195
 	"""Finds URLs in markdown and encloses them in <...> to suppress the preview."""
195
 	"""Finds URLs in markdown and encloses them in <...> to suppress the preview."""
196
 	return re.sub(r'(?<!<)(https?://\S+)(?!>)', '<\\1>', markdown)
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
 def format_bytes(size: int) -> str:
217
 def format_bytes(size: int) -> str:
199
 	"""Formats s size in bytes to a human readable description (e.g. "3.2 KiB")"""
218
 	"""Formats s size in bytes to a human readable description (e.g. "3.2 KiB")"""
200
 	size = max(size, 0)
219
 	size = max(size, 0)

Загрузка…
Отмена
Сохранить