unload plugin loadplugin.py. youtube-preview now gets lyrics.

This commit is contained in:
Hash Borgir 2024-03-10 05:58:21 -06:00
parent d2acef611b
commit 5d746027e2
3 changed files with 73 additions and 27 deletions

View File

@ -6,6 +6,7 @@ import os
import logging import logging
import importlib import importlib
import simplematrixbotlib as botlib import simplematrixbotlib as botlib
import sys # Import sys module for unloading plugins
# Dictionary to store loaded plugins # Dictionary to store loaded plugins
PLUGINS = {} PLUGINS = {}
@ -32,9 +33,33 @@ async def load_plugin(plugin_name):
logging.error(f"Error loading plugin {plugin_name}: {e}") logging.error(f"Error loading plugin {plugin_name}: {e}")
return False return False
async def unload_plugin(plugin_name):
"""
Asynchronously unloads a plugin.
Args:
plugin_name (str): The name of the plugin to unload.
Returns:
bool: True if the plugin is unloaded successfully, False otherwise.
"""
try:
if plugin_name in PLUGINS:
del PLUGINS[plugin_name] # Remove the plugin from the PLUGINS dictionary
del sys.modules[f"plugins.{plugin_name}"] # Unload the plugin module from sys.modules
logging.info(f"Unloaded plugin: {plugin_name}")
return True
else:
logging.warning(f"Plugin '{plugin_name}' is not loaded")
return False
except Exception as e:
# Log an error if the plugin fails to unload
logging.error(f"Error unloading plugin {plugin_name}: {e}")
return False
async def handle_command(room, message, bot, prefix, config): async def handle_command(room, message, bot, prefix, config):
""" """
Asynchronously handles the command to load a plugin. Asynchronously handles the command to load or unload a plugin.
Args: Args:
room (Room): The Matrix room where the command was invoked. room (Room): The Matrix room where the command was invoked.
@ -47,8 +72,9 @@ async def handle_command(room, message, bot, prefix, config):
None None
""" """
match = botlib.MessageMatch(room, message, bot, prefix) match = botlib.MessageMatch(room, message, bot, prefix)
if match.is_not_from_this_bot() and match.prefix() and match.command("load"): if match.is_not_from_this_bot() and match.prefix():
# Check if the sender is the admin command = match.command()
if command == "load":
if str(message.sender) == config.admin_user: if str(message.sender) == config.admin_user:
args = match.args() args = match.args()
if len(args) != 1: if len(args) != 1:
@ -69,3 +95,21 @@ async def handle_command(room, message, bot, prefix, config):
else: else:
# Send unauthorized message if the sender is not the admin # Send unauthorized message if the sender is not the admin
await bot.api.send_text_message(room.room_id, "You are not authorized to load plugins.") await bot.api.send_text_message(room.room_id, "You are not authorized to load plugins.")
elif command == "unload":
if str(message.sender) == config.admin_user:
args = match.args()
if len(args) != 1:
# Send usage message if the command format is incorrect
await bot.api.send_text_message(room.room_id, "Usage: !unload <plugin>")
else:
plugin_name = args[0]
# Unload the plugin
success = await unload_plugin(plugin_name)
if success:
await bot.api.send_text_message(room.room_id, f"Plugin '{plugin_name}' unloaded successfully")
else:
await bot.api.send_text_message(room.room_id, f"Error unloading plugin '{plugin_name}'")
else:
# Send unauthorized message if the sender is not the admin
await bot.api.send_text_message(room.room_id, "You are not authorized to unload plugins.")

View File

@ -11,7 +11,7 @@ from pytubefix import YouTube
import simplematrixbotlib as botlib import simplematrixbotlib as botlib
from youtube_title_parse import get_artist_title from youtube_title_parse import get_artist_title
LYRICIST_API_URL = "https://lyrist.vercel.app/api/song/{}" LYRICIST_API_URL = "https://lyrist.vercel.app/api/{}"
def seconds_to_minutes_seconds(seconds): def seconds_to_minutes_seconds(seconds):
@ -29,11 +29,12 @@ def seconds_to_minutes_seconds(seconds):
return f"{minutes:02d}:{seconds:02d}" return f"{minutes:02d}:{seconds:02d}"
async def fetch_lyrics(artist): async def fetch_lyrics(song, artist):
""" """
Asynchronously fetches lyrics for a song from the Lyricist API. Asynchronously fetches lyrics for a song from the Lyricist API.
Args: Args:
song (str): The name of the song.
artist (str): The name of the artist. artist (str): The name of the artist.
Returns: Returns:
@ -42,7 +43,7 @@ async def fetch_lyrics(artist):
""" """
try: try:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(LYRICIST_API_URL.format(artist)) as response: async with session.get(LYRICIST_API_URL.format(song, artist)) as response:
data = await response.json() data = await response.json()
return data.get("lyrics") return data.get("lyrics")
except Exception as e: except Exception as e:
@ -50,6 +51,7 @@ async def fetch_lyrics(artist):
return None return None
async def fetch_youtube_info(youtube_url): async def fetch_youtube_info(youtube_url):
""" """
Asynchronously fetches information about a YouTube video. Asynchronously fetches information about a YouTube video.
@ -73,7 +75,7 @@ async def fetch_youtube_info(youtube_url):
description_with_breaks = description.replace('\n', '<br>') description_with_breaks = description.replace('\n', '<br>')
# Fetching lyrics # Fetching lyrics
lyrics = await fetch_lyrics(artist) lyrics = await fetch_lyrics(song, artist)
lyrics = lyrics.replace('\n', "<br>") lyrics = lyrics.replace('\n', "<br>")
info_message = f"""<strong>🎬🎝 Title:</strong> {title} | <strong>Length</strong>: {length} minutes | <strong>Views</strong>: {views}\n<details><summary><strong>⤵Description⤵</strong></summary>{description_with_breaks}</details>""" info_message = f"""<strong>🎬🎝 Title:</strong> {title} | <strong>Length</strong>: {length} minutes | <strong>Views</strong>: {views}\n<details><summary><strong>⤵Description⤵</strong></summary>{description_with_breaks}</details>"""

View File

@ -8,5 +8,5 @@ watchdog
emoji emoji
python-slugify python-slugify
youtube_title_parse youtube_title_parse
dnspython