refactor: async I/O, input sanitisation, and shared utilities cleanup

This commit is contained in:
2026-05-08 22:59:31 -05:00
parent 52a9621d50
commit f822d6a450
21 changed files with 1351 additions and 2709 deletions
+23 -62
View File
@@ -1,25 +1,15 @@
"""
Plugin for providing a command to search for YouTube videos in the room.
Plugin for providing a command to search for YouTube videos.
Uses async wrapper around youtube_search library (synchronous).
"""
import logging
import asyncio
import simplematrixbotlib as botlib
from youtube_search import YoutubeSearch
from plugins.common import html_escape, collapsible_summary
async def handle_command(room, message, bot, PREFIX, config):
"""
Asynchronously handles the command to search for YouTube videos in the room.
Args:
room (Room): The Matrix room where the command was invoked.
message (RoomMessage): The message object containing the command.
bot (MatrixBot): The Matrix bot instance.
PREFIX (str): The command prefix.
config (dict): The bot's configuration.
Returns:
None
"""
match = botlib.MessageMatch(room, message, bot, PREFIX)
if match.is_not_from_this_bot() and match.prefix() and match.command("yt"):
args = match.args()
@@ -27,62 +17,33 @@ async def handle_command(room, message, bot, PREFIX, config):
await bot.api.send_text_message(room.room_id, "Usage: !yt <search terms>")
else:
search_terms = " ".join(args)
logging.info(f"Performing YouTube search for: {search_terms}")
results = YoutubeSearch(search_terms, max_results=3).to_dict()
logging.info(f"YouTube search for: {search_terms}")
results = await asyncio.to_thread(YoutubeSearch, search_terms, max_results=3)
results = results.to_dict()
if results:
output = generate_output(results)
await send_collapsible_message(room, bot, output)
safe_terms = html_escape(search_terms)
msg = collapsible_summary(f"🍄 Funguy ▶YouTube Search: {safe_terms}", output)
await bot.api.send_markdown_message(room.room_id, msg)
else:
await bot.api.send_text_message(room.room_id, "No results found.")
def generate_output(results):
"""
Generates HTML output for displaying YouTube search results.
Args:
results (list): A list of dictionaries containing information about YouTube videos.
Returns:
str: HTML formatted output containing YouTube search results.
"""
output = ""
for video in results:
output += f'<a href="https://www.youtube.com/watch?v={video["id"]}">'
output += f'<img src="{video["thumbnails"][0]}"></img><br>'
output += f'<strong>{video["title"]}</strong><br>'
output += f'Length: {video["duration"]} | Views: {video["views"]}<br>'
if video["long_desc"]:
output += f'Description: {video["long_desc"]}<br>'
output += "</a><br>"
vid_id = html_escape(video["id"])
title = html_escape(video["title"])
thumb = video["thumbnails"][0]
duration = html_escape(str(video["duration"]))
views = html_escape(str(video["views"]))
output += f'<a href="https://www.youtube.com/watch?v={vid_id}">'
output += f'<img src="{thumb}"></img><br>'
output += f'<strong>{title}</strong><br>'
output += f'Length: {duration} | Views: {views}<br></a><br>'
return output
async def send_collapsible_message(room, bot, content):
"""
Sends a collapsible message containing YouTube search results to the room.
Args:
room (Room): The Matrix room where the message will be sent.
bot (MatrixBot): The Matrix bot instance.
content (str): HTML content to be included in the collapsible message.
Returns:
None
"""
message = f'<details><summary><strong>🍄Funguy ▶YouTube Search🍄<br>⤵︎Click Here To See Results⤵︎</strong></summary>{content}</details>'
await bot.api.send_markdown_message(room.room_id, message)
# ---------------------------------------------------------------------------
# Plugin Metadata
# ---------------------------------------------------------------------------
__version__ = "1.0.0"
__version__ = "1.0.1"
__author__ = "Funguy Bot"
__description__ = "YouTube video search"
__help__ = """
<details>
<summary><strong>!yt</strong> Search YouTube</summary>
<p><code>!yt &lt;search terms&gt;</code> Returns top 3 results with thumbnails and descriptions.</p>
</details>
"""
__description__ = "YouTube video search (async)"
__help__ = """<details><summary><strong>!yt</strong> Search YouTube</summary>
<p><code>!yt &lt;search terms&gt;</code></p></details>"""