Added proper error handling in enable_database command to handle cases where the setting doesn't exist yet

Fixed redbot import issues by importing specific exception classes
Ensured database setting is properly synchronized between base.py and config_manager.py
Added proper database initialization and reference handling
This commit is contained in:
pacnpal
2024-11-16 01:43:17 +00:00
parent 372b7de34a
commit 669db54442
2 changed files with 42 additions and 18 deletions

View File

@@ -1,5 +1,6 @@
"""Configuration management for VideoArchiver""" """Configuration management for VideoArchiver"""
from redbot.core import Config from redbot.core import Config
from redbot.core import commands # Added for exception types
from typing import Dict, Any, Optional, List, Union, cast from typing import Dict, Any, Optional, List, Union, cast
import discord import discord
import logging import logging
@@ -33,6 +34,7 @@ class ConfigManager:
"retry_delay": 5, "retry_delay": 5,
"discord_retry_attempts": 3, "discord_retry_attempts": 3,
"discord_retry_delay": 5, "discord_retry_delay": 5,
"use_database": False, # Added the missing use_database setting
} }
# Valid settings constraints # Valid settings constraints
@@ -88,7 +90,7 @@ class ConfigManager:
elif setting in ["message_template"] and not isinstance(value, str): elif setting in ["message_template"] and not isinstance(value, str):
raise ConfigError("Message template must be a string") raise ConfigError("Message template must be a string")
elif setting in ["enabled", "delete_after_repost", "disable_update_check"] and not isinstance(value, bool): elif setting in ["enabled", "delete_after_repost", "disable_update_check", "use_database"] and not isinstance(value, bool):
raise ConfigError(f"{setting} must be a boolean") raise ConfigError(f"{setting} must be a boolean")
except Exception as e: except Exception as e:
@@ -343,6 +345,11 @@ class ConfigManager:
value=str(settings["disable_update_check"]), value=str(settings["disable_update_check"]),
inline=True inline=True
) )
embed.add_field(
name="Database Enabled",
value=str(settings["use_database"]),
inline=True
)
# Add enabled sites with validation # Add enabled sites with validation
embed.add_field( embed.add_field(

View File

@@ -12,7 +12,11 @@ from redbot.core.commands import (
hybrid_command, hybrid_command,
hybrid_group, hybrid_group,
guild_only, guild_only,
commands, # Added this import commands,
MissingPermissions,
BotMissingPermissions,
MissingRequiredArgument,
BadArgument,
) )
from redbot.core import checks from redbot.core import checks
from discord import app_commands from discord import app_commands
@@ -102,21 +106,34 @@ class VideoArchiver(GroupCog):
async def enable_database(self, ctx: Context): async def enable_database(self, ctx: Context):
"""Enable the video archive database.""" """Enable the video archive database."""
try: try:
current_setting = await self.config_manager.get_setting( # First check if database is already enabled
ctx.guild.id, "use_database" try:
) current_setting = await self.config_manager.get_setting(
if current_setting: ctx.guild.id, "use_database"
await ctx.send("The video archive database is already enabled.") )
return if current_setting:
await ctx.send("The video archive database is already enabled.")
return
except Exception as e:
logger.error(f"Failed to get setting use_database: {e}")
# If setting doesn't exist, we'll create it
await self.config_manager.update_setting(ctx.guild.id, "use_database", False)
# Initialize database if it's being enabled # Initialize database if it's being enabled
self.db = VideoArchiveDB(self.data_path) try:
# Update processor with database self.db = VideoArchiveDB(self.data_path)
self.processor.db = self.db # Update processor with database
self.processor.queue_handler.db = self.db if self.processor:
self.processor.db = self.db
if self.processor.queue_handler:
self.processor.queue_handler.db = self.db
await self.config_manager.update_setting(ctx.guild.id, "use_database", True) await self.config_manager.update_setting(ctx.guild.id, "use_database", True)
await ctx.send("Video archive database has been enabled.") await ctx.send("Video archive database has been enabled.")
except Exception as e:
logger.error(f"Error initializing database: {e}")
await ctx.send("An error occurred while initializing the database.")
return
except Exception as e: except Exception as e:
logger.error(f"Error enabling database: {e}") logger.error(f"Error enabling database: {e}")
@@ -429,13 +446,13 @@ class VideoArchiver(GroupCog):
"""Handle command errors""" """Handle command errors"""
error_msg = None error_msg = None
try: try:
if isinstance(error, redbot.core.commands.MissingPermissions): # Fixed this line if isinstance(error, MissingPermissions):
error_msg = "❌ You don't have permission to use this command." error_msg = "❌ You don't have permission to use this command."
elif isinstance(error, redbot.core.commands.BotMissingPermissions): # And this line elif isinstance(error, BotMissingPermissions):
error_msg = "❌ I don't have the required permissions to do that." error_msg = "❌ I don't have the required permissions to do that."
elif isinstance(error, redbot.core.commands.MissingRequiredArgument): # And this line elif isinstance(error, MissingRequiredArgument):
error_msg = f"❌ Missing required argument: {error.param.name}" error_msg = f"❌ Missing required argument: {error.param.name}"
elif isinstance(error, redbot.core.commands.BadArgument): # And this line elif isinstance(error, BadArgument):
error_msg = f"❌ Invalid argument: {str(error)}" error_msg = f"❌ Invalid argument: {str(error)}"
elif isinstance(error, ConfigError): elif isinstance(error, ConfigError):
error_msg = f"❌ Configuration error: {str(error)}" error_msg = f"❌ Configuration error: {str(error)}"