Skip to content

Commit

Permalink
errors updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Drago-03 committed Dec 3, 2024
1 parent d3916e3 commit edb4299
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 56 deletions.
68 changes: 45 additions & 23 deletions cogs/errors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import discord
from discord.ext import commands
import traceback

class ErrorHandler(commands.Cog):
"""Cog for handling errors and displaying them professionally"""
Expand All @@ -14,56 +15,77 @@ async def on_command_error(self, ctx, error):

if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Missing Required Argument",
description=f"You're missing a required argument: `{error.param.name}`.\nPlease provide all required arguments and try again.",
color=discord.Color.red()
title="⚠️ Missing Required Argument",
description=f"**Error:** The command `{ctx.command}` requires additional information.\n\n"
f"**Details:** Missing parameter: `{error.param.name}`\n\n"
f"**Example Usage:**\n```\n{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}\n```",
color=discord.Color.gold()
)

elif isinstance(error, commands.CommandNotFound):
command_name = ctx.message.content.split()[0][1:] # Remove prefix
embed = discord.Embed(
title="Command Not Found",
description="The command you tried to use does not exist. Please check the command and try again.",
title="❌ Command Not Found",
description=f"**Error:** The command `{command_name}` does not exist.\n\n"
f"**Solution:** Use `{ctx.prefix}help` to see all available commands.\n\n"
f"**Note:** Commands are case-sensitive.",
color=discord.Color.red()
)

elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Missing Permissions",
description="You do not have the required permissions to use this command.",
title="🔒 Missing Permissions",
description=f"**Error:** You lack the required permissions.\n\n"
f"**Required Permissions:**\n```\n{', '.join(error.missing_permissions)}\n```\n"
f"**Note:** Contact a server administrator if you believe this is a mistake.",
color=discord.Color.red()
)

elif isinstance(error, commands.BotMissingPermissions):
embed = discord.Embed(
title="Bot Missing Permissions",
description="I do not have the required permissions to execute this command.",
title="🤖 Bot Missing Permissions",
description=f"**Error:** I don't have the required permissions.\n\n"
f"**Required Permissions:**\n```\n{', '.join(error.missing_permissions)}\n```\n"
f"**Solution:** Ask a server administrator to grant me these permissions.",
color=discord.Color.red()
)

elif isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="Command On Cooldown",
description=f"This command is on cooldown. Please try again after {error.retry_after:.2f} seconds.",
color=discord.Color.red()
title="⏳ Command on Cooldown",
description=f"**Error:** This command is on cooldown.\n\n"
f"**Time Remaining:** {error.retry_after:.1f} seconds\n\n"
f"**Note:** This limit helps prevent spam and ensures fair usage.",
color=discord.Color.blue()
)

else:
error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
embed = discord.Embed(
title="An Error Occurred",
description="An unexpected error occurred. Please try again later.",
title="⚠️ Unexpected Error",
description=f"**Error Type:** `{type(error).__name__}`\n\n"
f"**Details:**\n```py\n{str(error)}\n```\n\n"
f"**Developer Info:**\n```py\n{error_traceback[:1000]}\n```",
color=discord.Color.red()
)
embed.add_field(name="Error Details", value=str(error))

# Send the error message to the user
# Add common footer
embed.set_footer(text=f"Command: {ctx.prefix}{ctx.command if ctx.command else 'Unknown'}")

# Send error to user
await ctx.send(embed=embed)

# Log the error in the specified log channel
# Log error
if log_channel:
log_embed = discord.Embed(
title="Error Logged",
description=f"An error occurred in {ctx.guild.name} ({ctx.guild.id})",
title="🔍 Error Log Entry",
description=f"Error occurred in {ctx.guild.name}",
color=discord.Color.red()
)
log_embed.add_field(name="User", value=ctx.author.mention, inline=True)
log_embed.add_field(name="Channel", value=ctx.channel.mention, inline=True)
log_embed.add_field(name="Command", value=ctx.command, inline=True)
log_embed.add_field(name="Error", value=str(error), inline=False)
log_embed.add_field(name="User", value=f"{ctx.author} ({ctx.author.id})", inline=True)
log_embed.add_field(name="Channel", value=f"{ctx.channel.name} ({ctx.channel.id})", inline=True)
log_embed.add_field(name="Command", value=f"{ctx.message.content[:1000]}", inline=False)
log_embed.add_field(name="Error", value=f"```py\n{error_traceback[:1000]}\n```", inline=False)
await log_channel.send(embed=log_embed)

async def setup(bot):
Expand Down
59 changes: 26 additions & 33 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
import sys
import traceback

# Set up detailed logging
# Set up logging
logging.basicConfig(
level=logging.DEBUG, # Changed to DEBUG for more detailed logs
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
Expand All @@ -27,11 +27,12 @@
class IndieGOBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=PREFIX,
command_prefix=PREFIX,
intents=intents,
help_command=None # Disable default help command
)
self.initial_extensions = [
'cogs.errors', # Load error handler first
'cogs.general',
'cogs.moderation',
'cogs.fun',
Expand All @@ -40,63 +41,55 @@ def __init__(self):
'cogs.logging',
'cogs.ai_assistant',
'cogs.coding_help',
'cogs.help', # Load help cog last
'cogs.base',
'cogs.errors',
'cogs.automod',
'cogs.dm_interaction',
'cogs.voice_channel',
'cogs.ocr',
'cogs.reddit'
'cogs.reddit',
'cogs.help' # Load help cog last
]

async def setup_hook(self):
logger.info('Starting bot setup...')

# Load cogs with detailed error handling
# Load all cogs
for extension in self.initial_extensions:
try:
logger.debug(f'Attempting to load extension: {extension}')
await self.load_extension(extension)
logger.info(f'Successfully loaded extension: {extension}')
except Exception as e:
logger.error(f'Failed to load extension {extension}')
logger.error(f'Error type: {type(e).__name__}')
logger.error(f'Error message: {str(e)}')
logger.error('Traceback:')
logger.error(f'Failed to load extension {extension}: {str(e)}')
logger.error(traceback.format_exc())
# Continue loading other extensions instead of stopping
continue

# Try to sync commands after loading available cogs
# Sync commands
try:
logger.info('Syncing command tree...')
await self.tree.sync()
logger.info('Command tree synced successfully')
synced = await self.tree.sync()
logger.info(f'Synced {len(synced)} command(s)')
except Exception as e:
logger.error(f'Failed to sync command tree: {str(e)}')
logger.error(f'Failed to sync commands: {str(e)}')
logger.error(traceback.format_exc())

async def on_ready(self):
logger.info(f"Logged in as {self.user} (ID: {self.user.id})")
logger.info("------")
logger.info(f'Logged in as {self.user} (ID: {self.user.id})')
logger.info('------')

async def on_command_error(self, ctx, error):
if hasattr(ctx.command, 'on_error'):
return

cog = ctx.cog
if cog:
if commands.Cog._get_overridden_method(cog.cog_command_error) is not None:
return

logger.error('Ignoring exception in command {}:'.format(ctx.command), exc_info=error)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
# Pass all errors to the error handler cog
if not hasattr(ctx.command, 'on_error'):
return await ctx.cog.cog_command_error(ctx, error)

bot = IndieGOBot()

async def main():
async with bot:
await bot.start(TOKEN)

asyncio.run(main())
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info('Bot shutdown initiated by user')
except Exception as e:
logger.error(f'Unexpected error: {str(e)}')
logger.error(traceback.format_exc())

0 comments on commit edb4299

Please sign in to comment.