Last active
December 9, 2022 21:55
-
-
Save zachlagden/02babcd229aff29f0212dc545688a563 to your computer and use it in GitHub Desktop.
pycord - Error handling useful code, because noone can remember everything :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright (c) 2022, Zach Lagden | |
All rights reserved. | |
""" | |
import discord | |
from discord.ext import commands | |
from datetime import datetime | |
import coloredlogs | |
import traceback | |
import logging | |
import stat | |
import sys | |
import os | |
from .messages import cb_reply | |
from .embeds import Embed | |
ignored = (commands.CommandNotFound,) | |
log = logging.getLogger("rickbot") | |
def rmtree_error(func, path, exc_info): | |
""" | |
Error handler for ``shutil.rmtree``. | |
If the error is due to an access error (read only file) | |
it attempts to add write permission and then retries. | |
If the error is for another reason it re-raises the error. | |
Usage : ``shutil.rmtree(path, onerror=onerror)`` | |
""" | |
# Is the error an access error? | |
if not os.access(path, os.W_OK): | |
os.chmod(path, stat.S_IWUSR) | |
func(path) | |
else: | |
raise | |
def logging_setup(): | |
coloredlogs.install( | |
level="INFO", | |
fmt="[%(asctime)s] %(name)s[%(process)d] %(levelname)s: %(message)s", | |
) | |
def create_error_embed( | |
ctx, error: Exception = None, title: str = "", body: str = "", fields: list = None | |
): | |
if fields: | |
fields.append({"name": "Error Output", "value": f"```{error}```"}) | |
return Embed( | |
title=title, | |
description=body, | |
timestamp=datetime.now(), | |
thumbnail="https://miracomosehace.com/wp-content/uploads/2020/06/error-web.jpg", | |
author={ | |
"name": ctx.bot.user.display_name, | |
"url": "", | |
"icon": ctx.bot.user.avatar.url, | |
}, | |
footer={ | |
"text": f"{ctx.bot.user.display_name} error logging", | |
"icon": "", | |
}, | |
fields=fields | |
if fields | |
else [{"name": "Error Output", "value": f"```{error}```"}], | |
) | |
async def handle_error(ctx, error): | |
error = getattr(error, "original", error) | |
if isinstance(error, ignored): | |
return | |
if isinstance(error, commands.DisabledCommand): | |
error_embed = create_error_embed( | |
ctx, error, "Command is disabled", "This command is disabled" | |
) | |
elif isinstance(error, commands.MessageNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Message not found", | |
f"I was unable to find the following message: {error.argument}", | |
) | |
elif isinstance(error, commands.MemberNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Member not found", | |
f"I was unable to find the following member: {error.argument}", | |
) | |
elif isinstance(error, commands.UserNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"User not found", | |
f"I was unable to find the following user: {error.argument}", | |
) | |
elif isinstance(error, commands.ChannelNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Channel not found", | |
f"I was unable to find the following channel: {error.argument}", | |
) | |
elif isinstance(error, commands.ThreadNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Thread not found", | |
f"I was unable to find the following thread: {error.argument}", | |
) | |
elif isinstance(error, commands.GuildNotFound): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Guild not found", | |
f"I was unable to find the following guild: {error.argument}", | |
) | |
elif isinstance(error, commands.MissingPermissions): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Permission denied", | |
f"You need the following permissions to access this command: {error.missing_permissions}", | |
) | |
elif isinstance(error, commands.BotMissingPermissions): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Command failed to run", | |
f"I need the following permissions to run this command: {error.missing_permissions}", | |
) | |
elif isinstance(error, commands.NoPrivateMessage): | |
try: | |
await ctx.author.send(f"{ctx.command} cannot be used in Private Messages.") | |
except discord.HTTPException: | |
pass | |
elif isinstance(error, commands.MissingRequiredArgument): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"Incorrect command usage", | |
f"You must provide the required argument: `{error.param}`", | |
) | |
elif isinstance(error, commands.NSFWChannelRequired): | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"This command can only be used in NSFW channels", | |
"Please try again in a NSFW channel", | |
) | |
else: | |
print("Ignoring exception in command {}:".format(ctx.command), file=sys.stderr) | |
traceback.print_exception( | |
type(error), error, error.__traceback__, file=sys.stderr | |
) | |
log.exception( | |
f"{ctx.author} caused an error in {ctx.command}" | |
) # exc_info=error | |
error_embed = create_error_embed( | |
ctx, | |
error, | |
"An error occurred", | |
"Please try again, if it still doesn't work please DM luna.", | |
) | |
await ctx.reply(embed=error_embed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment