""" 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): match = botlib.MessageMatch(room, message, bot, PREFIX) if match.is_not_from_this_bot() and match.prefix() and match.command("yt"): args = match.args() if len(args) < 1: await bot.api.send_text_message(room.room_id, "Usage: !yt ") else: search_terms = " ".join(args) 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) 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): output = "" for video in results: 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'' output += f'
' output += f'{title}
' output += f'Length: {duration} | Views: {views}

' return output __version__ = "1.0.1" __author__ = "Funguy Bot" __description__ = "YouTube video search (async)" __help__ = """
!yt – Search YouTube

!yt <search terms>

"""