Core Functionality:

base.py: Streamlined to core cog functionality and lifecycle management
initialization.py: Centralized initialization logic
error_handler.py: Unified error handling
response_handler.py: Consistent response handling
Command Organization:

commands/archiver_commands.py: Core archiver functionality
commands/database_commands.py: Database operations
commands/settings_commands.py: Settings management
All commands properly integrated with the cog using setup functions
Improved Architecture:

Consistent command registration pattern
Better separation of concerns
Maintained all original functionality
Enhanced error handling and response management
Proper command integration with the cog structure
This commit is contained in:
pacnpal
2024-11-16 03:30:11 +00:00
parent 6aeb87fb40
commit 537a325807
8 changed files with 824 additions and 623 deletions

View File

@@ -0,0 +1,11 @@
"""Command handlers for VideoArchiver"""
from .archiver_commands import setup_archiver_commands
from .database_commands import setup_database_commands
from .settings_commands import setup_settings_commands
__all__ = [
'setup_archiver_commands',
'setup_database_commands',
'setup_settings_commands'
]

View File

@@ -0,0 +1,82 @@
"""Module for core archiver commands"""
import discord
from redbot.core.commands import Context, hybrid_group, guild_only, checks
from discord import app_commands
import logging
from ..response_handler import handle_response
logger = logging.getLogger("VideoArchiver")
def setup_archiver_commands(cog):
"""Set up archiver commands for the cog"""
@cog.hybrid_group(name="archiver", fallback="help")
@guild_only()
async def archiver(ctx: Context):
"""Manage video archiver settings."""
if ctx.invoked_subcommand is None:
await handle_response(
ctx, "Use `/help archiver` for a list of commands."
)
@archiver.command(name="enable")
@guild_only()
@checks.admin_or_permissions(administrator=True)
async def enable_archiver(ctx: Context):
"""Enable video archiving in this server."""
try:
current_setting = await cog.config_manager.get_setting(
ctx.guild.id, "enabled"
)
if current_setting:
await handle_response(ctx, "Video archiving is already enabled.")
return
await cog.config_manager.update_setting(ctx.guild.id, "enabled", True)
await handle_response(ctx, "Video archiving has been enabled.")
except Exception as e:
logger.error(f"Error enabling archiver: {e}")
await handle_response(
ctx, "An error occurred while enabling video archiving."
)
@archiver.command(name="disable")
@guild_only()
@checks.admin_or_permissions(administrator=True)
async def disable_archiver(ctx: Context):
"""Disable video archiving in this server."""
try:
current_setting = await cog.config_manager.get_setting(
ctx.guild.id, "enabled"
)
if not current_setting:
await handle_response(ctx, "Video archiving is already disabled.")
return
await cog.config_manager.update_setting(ctx.guild.id, "enabled", False)
await handle_response(ctx, "Video archiving has been disabled.")
except Exception as e:
logger.error(f"Error disabling archiver: {e}")
await handle_response(
ctx, "An error occurred while disabling video archiving."
)
@archiver.command(name="queue")
@guild_only()
async def show_queue(ctx: Context):
"""Show the current video processing queue."""
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
await cog.processor.show_queue_details(ctx)
# Store commands in cog for access
cog.archiver = archiver
cog.enable_archiver = enable_archiver
cog.disable_archiver = disable_archiver
cog.show_queue = show_queue
return archiver

View File

@@ -0,0 +1,149 @@
"""Module for database-related commands"""
import discord
from redbot.core.commands import Context, hybrid_group, hybrid_command, guild_only, checks
from discord import app_commands
import logging
from ..response_handler import handle_response
from ...database.video_archive_db import VideoArchiveDB
logger = logging.getLogger("VideoArchiver")
def setup_database_commands(cog):
"""Set up database commands for the cog"""
@cog.hybrid_group(name="archivedb", fallback="help")
@guild_only()
async def archivedb(ctx: Context):
"""Manage the video archive database."""
if ctx.invoked_subcommand is None:
await handle_response(
ctx, "Use `/help archivedb` for a list of commands."
)
@archivedb.command(name="enable")
@guild_only()
@checks.admin_or_permissions(administrator=True)
async def enable_database(ctx: Context):
"""Enable the video archive database."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
# Check if database is already enabled
current_setting = await cog.config_manager.get_setting(
ctx.guild.id, "use_database"
)
if current_setting:
await handle_response(
ctx, "The video archive database is already enabled."
)
return
# Initialize database
cog.db = VideoArchiveDB(cog.data_path)
# Update processor with database
if cog.processor:
cog.processor.db = cog.db
if cog.processor.queue_handler:
cog.processor.queue_handler.db = cog.db
# Update setting
await cog.config_manager.update_setting(ctx.guild.id, "use_database", True)
# Send success message
await handle_response(ctx, "Video archive database has been enabled.")
except Exception as e:
logger.error(f"Error enabling database: {e}")
await handle_response(
ctx,
"An error occurred while enabling the database. Please check the logs for details.",
)
@archivedb.command(name="disable")
@guild_only()
@checks.admin_or_permissions(administrator=True)
async def disable_database(ctx: Context):
"""Disable the video archive database."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
current_setting = await cog.config_manager.get_setting(
ctx.guild.id, "use_database"
)
if not current_setting:
await handle_response(
ctx, "The video archive database is already disabled."
)
return
# Remove database references
cog.db = None
cog.processor.db = None
cog.processor.queue_handler.db = None
await cog.config_manager.update_setting(
ctx.guild.id, "use_database", False
)
await handle_response(
ctx, "Video archive database has been disabled."
)
except Exception as e:
logger.error(f"Error disabling database: {e}")
await handle_response(
ctx, "An error occurred while disabling the database."
)
@cog.hybrid_command()
@guild_only()
@app_commands.describe(url="The URL of the video to check")
async def checkarchived(ctx: Context, url: str):
"""Check if a video URL has been archived and get its Discord link if it exists."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not cog.db:
await handle_response(
ctx,
"The archive database is not enabled. Ask an admin to enable it with `/archivedb enable`",
)
return
result = cog.db.get_archived_video(url)
if result:
discord_url, message_id, channel_id, guild_id = result
embed = discord.Embed(
title="Video Found in Archive",
description=f"This video has been archived!\n\nOriginal URL: {url}",
color=discord.Color.green(),
)
embed.add_field(name="Archived Link", value=discord_url)
await handle_response(ctx, embed=embed)
else:
embed = discord.Embed(
title="Video Not Found",
description="This video has not been archived yet.",
color=discord.Color.red(),
)
await handle_response(ctx, embed=embed)
except Exception as e:
logger.error(f"Error checking archived video: {e}")
await handle_response(
ctx, "An error occurred while checking the archive."
)
# Store commands in cog for access
cog.archivedb = archivedb
cog.enable_database = enable_database
cog.disable_database = disable_database
cog.checkarchived = checkarchived
return archivedb

View File

@@ -0,0 +1,330 @@
"""Module for settings-related commands"""
import discord
from redbot.core.commands import Context, hybrid_command, guild_only, checks
from discord import app_commands
import logging
from ..response_handler import handle_response
logger = logging.getLogger("VideoArchiver")
def setup_settings_commands(cog):
"""Set up settings commands for the cog"""
@cog.hybrid_command(name="setchannel")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(channel="The channel where archived videos will be stored")
async def set_archive_channel(ctx: Context, channel: discord.TextChannel):
"""Set the channel where archived videos will be stored."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
await cog.config_manager.update_setting(
ctx.guild.id, "archive_channel", channel.id
)
await handle_response(
ctx, f"Archive channel has been set to {channel.mention}."
)
except Exception as e:
logger.error(f"Error setting archive channel: {e}")
await handle_response(
ctx, "An error occurred while setting the archive channel."
)
@cog.hybrid_command(name="setlog")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(channel="The channel where log messages will be sent")
async def set_log_channel(ctx: Context, channel: discord.TextChannel):
"""Set the channel where log messages will be sent."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
await cog.config_manager.update_setting(
ctx.guild.id, "log_channel", channel.id
)
await handle_response(
ctx, f"Log channel has been set to {channel.mention}."
)
except Exception as e:
logger.error(f"Error setting log channel: {e}")
await handle_response(
ctx, "An error occurred while setting the log channel."
)
@cog.hybrid_command(name="addchannel")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(channel="The channel to monitor for videos")
async def add_enabled_channel(ctx: Context, channel: discord.TextChannel):
"""Add a channel to monitor for videos."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
enabled_channels = await cog.config_manager.get_setting(
ctx.guild.id, "enabled_channels"
)
if channel.id in enabled_channels:
await handle_response(
ctx, f"{channel.mention} is already being monitored."
)
return
enabled_channels.append(channel.id)
await cog.config_manager.update_setting(
ctx.guild.id, "enabled_channels", enabled_channels
)
await handle_response(
ctx, f"Now monitoring {channel.mention} for videos."
)
except Exception as e:
logger.error(f"Error adding enabled channel: {e}")
await handle_response(
ctx, "An error occurred while adding the channel."
)
@cog.hybrid_command(name="removechannel")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(channel="The channel to stop monitoring")
async def remove_enabled_channel(ctx: Context, channel: discord.TextChannel):
"""Remove a channel from video monitoring."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
enabled_channels = await cog.config_manager.get_setting(
ctx.guild.id, "enabled_channels"
)
if channel.id not in enabled_channels:
await handle_response(
ctx, f"{channel.mention} is not being monitored."
)
return
enabled_channels.remove(channel.id)
await cog.config_manager.update_setting(
ctx.guild.id, "enabled_channels", enabled_channels
)
await handle_response(
ctx, f"Stopped monitoring {channel.mention} for videos."
)
except Exception as e:
logger.error(f"Error removing enabled channel: {e}")
await handle_response(
ctx, "An error occurred while removing the channel."
)
@cog.hybrid_command(name="setformat")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(format="The video format to use (mp4, webm, or mkv)")
async def set_video_format(ctx: Context, format: str):
"""Set the video format for archived videos."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
format = format.lower()
if format not in ["mp4", "webm", "mkv"]:
await handle_response(
ctx, "Invalid format. Please use mp4, webm, or mkv."
)
return
await cog.config_manager.update_setting(
ctx.guild.id, "video_format", format
)
await handle_response(ctx, f"Video format has been set to {format}.")
except Exception as e:
logger.error(f"Error setting video format: {e}")
await handle_response(
ctx, "An error occurred while setting the video format."
)
@cog.hybrid_command(name="setquality")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(quality="The video quality (144-4320)")
async def set_video_quality(ctx: Context, quality: int):
"""Set the video quality for archived videos."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not 144 <= quality <= 4320:
await handle_response(
ctx, "Quality must be between 144 and 4320."
)
return
await cog.config_manager.update_setting(
ctx.guild.id, "video_quality", quality
)
await handle_response(
ctx, f"Video quality has been set to {quality}p."
)
except Exception as e:
logger.error(f"Error setting video quality: {e}")
await handle_response(
ctx, "An error occurred while setting the video quality."
)
@cog.hybrid_command(name="setmaxsize")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(size="The maximum file size in MB (1-100)")
async def set_max_file_size(ctx: Context, size: int):
"""Set the maximum file size for archived videos."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not 1 <= size <= 100:
await handle_response(ctx, "Size must be between 1 and 100 MB.")
return
await cog.config_manager.update_setting(
ctx.guild.id, "max_file_size", size
)
await handle_response(
ctx, f"Maximum file size has been set to {size}MB."
)
except Exception as e:
logger.error(f"Error setting max file size: {e}")
await handle_response(
ctx, "An error occurred while setting the maximum file size."
)
@cog.hybrid_command(name="setmessageduration")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(hours="How long to keep messages in hours (0-168)")
async def set_message_duration(ctx: Context, hours: int):
"""Set how long to keep archived messages."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not 0 <= hours <= 168:
await handle_response(
ctx, "Duration must be between 0 and 168 hours (1 week)."
)
return
await cog.config_manager.update_setting(
ctx.guild.id, "message_duration", hours
)
await handle_response(
ctx, f"Message duration has been set to {hours} hours."
)
except Exception as e:
logger.error(f"Error setting message duration: {e}")
await handle_response(
ctx, "An error occurred while setting the message duration."
)
@cog.hybrid_command(name="settemplate")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(
template="The message template to use. Available placeholders: {author}, {channel}, {original_message}"
)
async def set_message_template(ctx: Context, template: str):
"""Set the template for archived messages."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not any(
ph in template for ph in ["{author}", "{channel}", "{original_message}"]
):
await handle_response(
ctx,
"Template must include at least one placeholder: {author}, {channel}, or {original_message}",
)
return
await cog.config_manager.update_setting(
ctx.guild.id, "message_template", template
)
await handle_response(
ctx, f"Message template has been set to: {template}"
)
except Exception as e:
logger.error(f"Error setting message template: {e}")
await handle_response(
ctx, "An error occurred while setting the message template."
)
@cog.hybrid_command(name="setconcurrent")
@guild_only()
@checks.admin_or_permissions(administrator=True)
@app_commands.describe(count="Number of concurrent downloads (1-5)")
async def set_concurrent_downloads(ctx: Context, count: int):
"""Set the number of concurrent downloads allowed."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
if not 1 <= count <= 5:
await handle_response(
ctx, "Concurrent downloads must be between 1 and 5."
)
return
await cog.config_manager.update_setting(
ctx.guild.id, "concurrent_downloads", count
)
await handle_response(
ctx, f"Concurrent downloads has been set to {count}."
)
except Exception as e:
logger.error(f"Error setting concurrent downloads: {e}")
await handle_response(
ctx, "An error occurred while setting concurrent downloads."
)
@cog.hybrid_command(name="settings")
@guild_only()
async def show_settings(ctx: Context):
"""Show current archiver settings."""
try:
# Defer the response immediately for slash commands
if hasattr(ctx, "interaction") and ctx.interaction:
await ctx.defer()
embed = await cog.config_manager.format_settings_embed(ctx.guild)
await handle_response(ctx, embed=embed)
except Exception as e:
logger.error(f"Error showing settings: {e}")
await handle_response(
ctx, "An error occurred while showing settings."
)
# Store commands in cog for access
cog.set_archive_channel = set_archive_channel
cog.set_log_channel = set_log_channel
cog.add_enabled_channel = add_enabled_channel
cog.remove_enabled_channel = remove_enabled_channel
cog.set_video_format = set_video_format
cog.set_video_quality = set_video_quality
cog.set_max_file_size = set_max_file_size
cog.set_message_duration = set_message_duration
cog.set_message_template = set_message_template
cog.set_concurrent_downloads = set_concurrent_downloads
cog.show_settings = show_settings