fix: Properly initialize and register hybrid commands for both slash and legacy support

This commit is contained in:
pacnpal
2024-11-15 00:26:48 +00:00
parent 7a0fd441b0
commit f6edef4658
2 changed files with 41 additions and 156 deletions

View File

@@ -13,6 +13,12 @@ class VideoArchiverCommands(commands.Cog):
self.config = config_manager self.config = config_manager
self.update_checker = update_checker self.update_checker = update_checker
self.processor = processor self.processor = processor
super().__init__()
async def cog_load(self) -> None:
"""Initialize commands when cog loads"""
# Ensure all commands are synced for slash command support
await self.bot.sync_commands()
@commands.hybrid_group(name="videoarchiver", aliases=["va"]) @commands.hybrid_group(name="videoarchiver", aliases=["va"])
@commands.guild_only() @commands.guild_only()
@@ -24,6 +30,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(embed=embed) await ctx.send(embed=embed)
@videoarchiver.command(name="updateytdlp") @videoarchiver.command(name="updateytdlp")
@commands.guild_only()
@checks.is_owner() @checks.is_owner()
async def update_ytdlp(self, ctx: commands.Context): async def update_ytdlp(self, ctx: commands.Context):
"""Update yt-dlp to the latest version""" """Update yt-dlp to the latest version"""
@@ -31,6 +38,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send("" + message if success else "" + message) await ctx.send("" + message if success else "" + message)
@videoarchiver.command(name="toggleupdates") @videoarchiver.command(name="toggleupdates")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def toggle_update_check(self, ctx: commands.Context): async def toggle_update_check(self, ctx: commands.Context):
"""Toggle yt-dlp update notifications""" """Toggle yt-dlp update notifications"""
@@ -39,18 +47,21 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Update notifications {status}") await ctx.send(f"Update notifications {status}")
@videoarchiver.command(name="addrole") @videoarchiver.command(name="addrole")
@commands.guild_only()
async def add_allowed_role(self, ctx: commands.Context, role: discord.Role): async def add_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Add a role that's allowed to trigger archiving""" """Add a role that's allowed to trigger archiving"""
await self.config.add_to_list(ctx.guild.id, "allowed_roles", role.id) await self.config.add_to_list(ctx.guild.id, "allowed_roles", role.id)
await ctx.send(f"Added {role.name} to allowed roles") await ctx.send(f"Added {role.name} to allowed roles")
@videoarchiver.command(name="removerole") @videoarchiver.command(name="removerole")
@commands.guild_only()
async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role): async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Remove a role from allowed roles""" """Remove a role from allowed roles"""
await self.config.remove_from_list(ctx.guild.id, "allowed_roles", role.id) await self.config.remove_from_list(ctx.guild.id, "allowed_roles", role.id)
await ctx.send(f"Removed {role.name} from allowed roles") await ctx.send(f"Removed {role.name} from allowed roles")
@videoarchiver.command(name="listroles") @videoarchiver.command(name="listroles")
@commands.guild_only()
async def list_allowed_roles(self, ctx: commands.Context): async def list_allowed_roles(self, ctx: commands.Context):
"""List all roles allowed to trigger archiving""" """List all roles allowed to trigger archiving"""
roles = await self.config.get_setting(ctx.guild.id, "allowed_roles") roles = await self.config.get_setting(ctx.guild.id, "allowed_roles")
@@ -65,6 +76,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Allowed roles: {', '.join(role_names)}") await ctx.send(f"Allowed roles: {', '.join(role_names)}")
@videoarchiver.command(name="setconcurrent") @videoarchiver.command(name="setconcurrent")
@commands.guild_only()
async def set_concurrent_downloads(self, ctx: commands.Context, count: int): async def set_concurrent_downloads(self, ctx: commands.Context, count: int):
"""Set the number of concurrent downloads (1-5)""" """Set the number of concurrent downloads (1-5)"""
if not 1 <= count <= 5: if not 1 <= count <= 5:
@@ -74,6 +86,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Concurrent downloads set to {count}") await ctx.send(f"Concurrent downloads set to {count}")
@videoarchiver.command(name="setchannel") @videoarchiver.command(name="setchannel")
@commands.guild_only()
async def set_archive_channel( async def set_archive_channel(
self, ctx: commands.Context, channel: discord.TextChannel self, ctx: commands.Context, channel: discord.TextChannel
): ):
@@ -82,6 +95,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Archive channel set to {channel.mention}") await ctx.send(f"Archive channel set to {channel.mention}")
@videoarchiver.command(name="setnotification") @videoarchiver.command(name="setnotification")
@commands.guild_only()
async def set_notification_channel( async def set_notification_channel(
self, ctx: commands.Context, channel: discord.TextChannel self, ctx: commands.Context, channel: discord.TextChannel
): ):
@@ -92,6 +106,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Notification channel set to {channel.mention}") await ctx.send(f"Notification channel set to {channel.mention}")
@videoarchiver.command(name="setlogchannel") @videoarchiver.command(name="setlogchannel")
@commands.guild_only()
async def set_log_channel( async def set_log_channel(
self, ctx: commands.Context, channel: discord.TextChannel self, ctx: commands.Context, channel: discord.TextChannel
): ):
@@ -100,6 +115,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Log channel set to {channel.mention}") await ctx.send(f"Log channel set to {channel.mention}")
@videoarchiver.command(name="addmonitor") @videoarchiver.command(name="addmonitor")
@commands.guild_only()
async def add_monitored_channel( async def add_monitored_channel(
self, ctx: commands.Context, channel: discord.TextChannel self, ctx: commands.Context, channel: discord.TextChannel
): ):
@@ -108,6 +124,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Now monitoring {channel.mention} for videos") await ctx.send(f"Now monitoring {channel.mention} for videos")
@videoarchiver.command(name="removemonitor") @videoarchiver.command(name="removemonitor")
@commands.guild_only()
async def remove_monitored_channel( async def remove_monitored_channel(
self, ctx: commands.Context, channel: discord.TextChannel self, ctx: commands.Context, channel: discord.TextChannel
): ):
@@ -118,42 +135,49 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Stopped monitoring {channel.mention}") await ctx.send(f"Stopped monitoring {channel.mention}")
@videoarchiver.command(name="setformat") @videoarchiver.command(name="setformat")
@commands.guild_only()
async def set_video_format(self, ctx: commands.Context, format: str): async def set_video_format(self, ctx: commands.Context, format: str):
"""Set the video format (e.g., mp4, webm)""" """Set the video format (e.g., mp4, webm)"""
await self.config.update_setting(ctx.guild.id, "video_format", format.lower()) await self.config.update_setting(ctx.guild.id, "video_format", format.lower())
await ctx.send(f"Video format set to {format.lower()}") await ctx.send(f"Video format set to {format.lower()}")
@videoarchiver.command(name="setquality") @videoarchiver.command(name="setquality")
@commands.guild_only()
async def set_video_quality(self, ctx: commands.Context, quality: int): async def set_video_quality(self, ctx: commands.Context, quality: int):
"""Set the maximum video quality in pixels (e.g., 1080)""" """Set the maximum video quality in pixels (e.g., 1080)"""
await self.config.update_setting(ctx.guild.id, "video_quality", quality) await self.config.update_setting(ctx.guild.id, "video_quality", quality)
await ctx.send(f"Maximum video quality set to {quality}p") await ctx.send(f"Maximum video quality set to {quality}p")
@videoarchiver.command(name="setmaxsize") @videoarchiver.command(name="setmaxsize")
@commands.guild_only()
async def set_max_file_size(self, ctx: commands.Context, size: int): async def set_max_file_size(self, ctx: commands.Context, size: int):
"""Set the maximum file size in MB""" """Set the maximum file size in MB"""
await self.config.update_setting(ctx.guild.id, "max_file_size", size) await self.config.update_setting(ctx.guild.id, "max_file_size", size)
await ctx.send(f"Maximum file size set to {size}MB") await ctx.send(f"Maximum file size set to {size}MB")
@videoarchiver.command(name="toggledelete") @videoarchiver.command(name="toggledelete")
@commands.guild_only()
async def toggle_delete_after_repost(self, ctx: commands.Context): async def toggle_delete_after_repost(self, ctx: commands.Context):
"""Toggle whether to delete local files after reposting""" """Toggle whether to delete local files after reposting"""
state = await self.config.toggle_setting(ctx.guild.id, "delete_after_repost") state = await self.config.toggle_setting(ctx.guild.id, "delete_after_repost")
await ctx.send(f"Delete after repost: {state}") await ctx.send(f"Delete after repost: {state}")
@videoarchiver.command(name="setduration") @videoarchiver.command(name="setduration")
@commands.guild_only()
async def set_message_duration(self, ctx: commands.Context, hours: int): async def set_message_duration(self, ctx: commands.Context, hours: int):
"""Set how long to keep archive messages (0 for permanent)""" """Set how long to keep archive messages (0 for permanent)"""
await self.config.update_setting(ctx.guild.id, "message_duration", hours) await self.config.update_setting(ctx.guild.id, "message_duration", hours)
await ctx.send(f"Archive message duration set to {hours} hours") await ctx.send(f"Archive message duration set to {hours} hours")
@videoarchiver.command(name="settemplate") @videoarchiver.command(name="settemplate")
@commands.guild_only()
async def set_message_template(self, ctx: commands.Context, *, template: str): async def set_message_template(self, ctx: commands.Context, *, template: str):
"""Set the archive message template. Use {author}, {url}, and {original_message} as placeholders""" """Set the archive message template. Use {author}, {url}, and {original_message} as placeholders"""
await self.config.update_setting(ctx.guild.id, "message_template", template) await self.config.update_setting(ctx.guild.id, "message_template", template)
await ctx.send(f"Archive message template set to:\n{template}") await ctx.send(f"Archive message template set to:\n{template}")
@videoarchiver.command(name="enablesites") @videoarchiver.command(name="enablesites")
@commands.guild_only()
async def enable_sites(self, ctx: commands.Context, *, sites: Optional[str] = None): async def enable_sites(self, ctx: commands.Context, *, sites: Optional[str] = None):
"""Enable specific sites (leave empty for all sites). Separate multiple sites with spaces.""" """Enable specific sites (leave empty for all sites). Separate multiple sites with spaces."""
if sites is None: if sites is None:
@@ -177,6 +201,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(f"Enabled sites: {', '.join(site_list)}") await ctx.send(f"Enabled sites: {', '.join(site_list)}")
@videoarchiver.command(name="listsites") @videoarchiver.command(name="listsites")
@commands.guild_only()
async def list_sites(self, ctx: commands.Context): async def list_sites(self, ctx: commands.Context):
"""List all available sites and currently enabled sites""" """List all available sites and currently enabled sites"""
enabled_sites = await self.config.get_setting(ctx.guild.id, "enabled_sites") enabled_sites = await self.config.get_setting(ctx.guild.id, "enabled_sites")
@@ -210,6 +235,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(embed=embed) await ctx.send(embed=embed)
@videoarchiver.command(name="queue") @videoarchiver.command(name="queue")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def show_queue(self, ctx: commands.Context): async def show_queue(self, ctx: commands.Context):
"""Show current queue status with basic metrics""" """Show current queue status with basic metrics"""
@@ -248,6 +274,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(embed=embed) await ctx.send(embed=embed)
@videoarchiver.command(name="queuemetrics") @videoarchiver.command(name="queuemetrics")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def show_queue_metrics(self, ctx: commands.Context): async def show_queue_metrics(self, ctx: commands.Context):
"""Show detailed queue performance metrics""" """Show detailed queue performance metrics"""
@@ -298,6 +325,7 @@ class VideoArchiverCommands(commands.Cog):
await ctx.send(embed=embed) await ctx.send(embed=embed)
@videoarchiver.command(name="clearqueue") @videoarchiver.command(name="clearqueue")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def clear_queue(self, ctx: commands.Context): async def clear_queue(self, ctx: commands.Context):
"""Clear the video processing queue for this guild""" """Clear the video processing queue for this guild"""

View File

@@ -29,7 +29,13 @@ from videoarchiver.exceptions import (
logger = logging.getLogger('VideoArchiver') logger = logging.getLogger('VideoArchiver')
class VideoArchiver(commands.Cog): def setup(bot):
"""Load the VideoArchiver cog."""
cog = VideoArchiver(bot)
bot.add_cog(cog)
return cog
class VideoArchiver(VideoArchiverCommands):
"""Archive videos from Discord channels""" """Archive videos from Discord channels"""
def __init__(self, bot: commands.Bot) -> None: def __init__(self, bot: commands.Bot) -> None:
@@ -76,13 +82,8 @@ class VideoArchiver(commands.Cog):
self.update_checker = UpdateChecker(self.bot, self.config_manager) self.update_checker = UpdateChecker(self.bot, self.config_manager)
self.processor = VideoProcessor(self.bot, self.config_manager, self.components) self.processor = VideoProcessor(self.bot, self.config_manager, self.components)
# Initialize commands last # Initialize base class last
self.commands = VideoArchiverCommands( super().__init__(self.bot, self.config_manager, self.update_checker, self.processor)
self.bot,
self.config_manager,
self.update_checker,
self.processor
)
# Initialize components for existing guilds # Initialize components for existing guilds
for guild in self.bot.guilds: for guild in self.bot.guilds:
@@ -122,6 +123,10 @@ class VideoArchiver(commands.Cog):
try: try:
# Wait for initialization to complete # Wait for initialization to complete
await asyncio.wait_for(self.ready.wait(), timeout=30) await asyncio.wait_for(self.ready.wait(), timeout=30)
# Sync commands for slash command support
await self.bot.sync_commands()
except asyncio.TimeoutError: except asyncio.TimeoutError:
await self._cleanup() await self._cleanup()
raise ProcessingError("Cog initialization timed out") raise ProcessingError("Cog initialization timed out")
@@ -274,154 +279,6 @@ class VideoArchiver(commands.Cog):
except Exception as log_error: except Exception as log_error:
logger.error(f"Failed to log error to guild: {str(log_error)}") logger.error(f"Failed to log error to guild: {str(log_error)}")
# Create command group
@commands.hybrid_group(name="videoarchiver", aliases=["va"])
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def videoarchiver(self, ctx: commands.Context):
"""Video Archiver configuration commands"""
if ctx.invoked_subcommand is None:
embed = await self.config_manager.format_settings_embed(ctx.guild)
await ctx.send(embed=embed)
# Add command methods that delegate to VideoArchiverCommands
@videoarchiver.command(name="updateytdlp")
@commands.guild_only()
@checks.is_owner()
async def update_ytdlp(self, ctx: commands.Context):
"""Update yt-dlp to the latest version"""
await self.commands.update_ytdlp(ctx)
@videoarchiver.command(name="toggleupdates")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def toggle_update_check(self, ctx: commands.Context):
"""Toggle yt-dlp update notifications"""
await self.commands.toggle_update_check(ctx)
@videoarchiver.command(name="addrole")
@commands.guild_only()
async def add_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Add a role that's allowed to trigger archiving"""
await self.commands.add_allowed_role(ctx, role)
@videoarchiver.command(name="removerole")
@commands.guild_only()
async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Remove a role from allowed roles"""
await self.commands.remove_allowed_role(ctx, role)
@videoarchiver.command(name="listroles")
@commands.guild_only()
async def list_allowed_roles(self, ctx: commands.Context):
"""List all roles allowed to trigger archiving"""
await self.commands.list_allowed_roles(ctx)
@videoarchiver.command(name="setconcurrent")
@commands.guild_only()
async def set_concurrent_downloads(self, ctx: commands.Context, count: int):
"""Set the number of concurrent downloads (1-5)"""
await self.commands.set_concurrent_downloads(ctx, count)
@videoarchiver.command(name="setchannel")
@commands.guild_only()
async def set_archive_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the archive channel"""
await self.commands.set_archive_channel(ctx, channel)
@videoarchiver.command(name="setnotification")
@commands.guild_only()
async def set_notification_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the notification channel (where archive messages appear)"""
await self.commands.set_notification_channel(ctx, channel)
@videoarchiver.command(name="setlogchannel")
@commands.guild_only()
async def set_log_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the log channel for error messages and notifications"""
await self.commands.set_log_channel(ctx, channel)
@videoarchiver.command(name="addmonitor")
@commands.guild_only()
async def add_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Add a channel to monitor for videos"""
await self.commands.add_monitored_channel(ctx, channel)
@videoarchiver.command(name="removemonitor")
@commands.guild_only()
async def remove_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Remove a channel from monitoring"""
await self.commands.remove_monitored_channel(ctx, channel)
@videoarchiver.command(name="setformat")
@commands.guild_only()
async def set_video_format(self, ctx: commands.Context, format: str):
"""Set the video format (e.g., mp4, webm)"""
await self.commands.set_video_format(ctx, format)
@videoarchiver.command(name="setquality")
@commands.guild_only()
async def set_video_quality(self, ctx: commands.Context, quality: int):
"""Set the maximum video quality in pixels (e.g., 1080)"""
await self.commands.set_video_quality(ctx, quality)
@videoarchiver.command(name="setmaxsize")
@commands.guild_only()
async def set_max_file_size(self, ctx: commands.Context, size: int):
"""Set the maximum file size in MB"""
await self.commands.set_max_file_size(ctx, size)
@videoarchiver.command(name="toggledelete")
@commands.guild_only()
async def toggle_delete_after_repost(self, ctx: commands.Context):
"""Toggle whether to delete local files after reposting"""
await self.commands.toggle_delete_after_repost(ctx)
@videoarchiver.command(name="setduration")
@commands.guild_only()
async def set_message_duration(self, ctx: commands.Context, hours: int):
"""Set how long to keep archive messages (0 for permanent)"""
await self.commands.set_message_duration(ctx, hours)
@videoarchiver.command(name="settemplate")
@commands.guild_only()
async def set_message_template(self, ctx: commands.Context, *, template: str):
"""Set the archive message template. Use {author}, {url}, and {original_message} as placeholders"""
await self.commands.set_message_template(ctx, template=template)
@videoarchiver.command(name="enablesites")
@commands.guild_only()
async def enable_sites(self, ctx: commands.Context, *, sites: Optional[str] = None):
"""Enable specific sites (leave empty for all sites). Separate multiple sites with spaces."""
await self.commands.enable_sites(ctx, sites=sites)
@videoarchiver.command(name="listsites")
@commands.guild_only()
async def list_sites(self, ctx: commands.Context):
"""List all available sites and currently enabled sites"""
await self.commands.list_sites(ctx)
@videoarchiver.command(name="queue")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def show_queue(self, ctx: commands.Context):
"""Show current queue status with basic metrics"""
await self.commands.show_queue(ctx)
@videoarchiver.command(name="queuemetrics")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def show_queue_metrics(self, ctx: commands.Context):
"""Show detailed queue performance metrics"""
await self.commands.show_queue_metrics(ctx)
@videoarchiver.command(name="clearqueue")
@commands.guild_only()
@commands.admin_or_permissions(administrator=True)
async def clear_queue(self, ctx: commands.Context):
"""Clear the video processing queue for this guild"""
await self.commands.clear_queue(ctx)
async def cog_command_error(self, ctx: commands.Context, error: Exception) -> None: async def cog_command_error(self, ctx: commands.Context, error: Exception) -> None:
"""Handle command errors""" """Handle command errors"""
error_msg = None error_msg = None