Browse Source

added new roxbot exceptions and the change from error and user error.

tags/v2.0.0
Roxie Gibson 5 years ago
parent
commit
b95d12a68f
4 changed files with 88 additions and 30 deletions
  1. +1
    -0
      roxbot/__init__.py
  2. +3
    -2
      roxbot/enums.py
  3. +32
    -28
      roxbot/err_handle.py
  4. +52
    -0
      roxbot/errors.py

+ 1
- 0
roxbot/__init__.py View File

@@ -26,6 +26,7 @@ SOFTWARE.


from roxbot import checks, http, guild_settings, converters, utils, roxbotfacts
from roxbot.errors import *
from roxbot.enums import EmbedColours
from roxbot.logging import log
from roxbot.utils import blacklisted

+ 3
- 2
roxbot/enums.py View File

@@ -32,8 +32,9 @@ class EmbedColours(IntEnum):
pink = 0xDEADBF # Roxbot Pink
yellow = 0xFDDF86 # Roxbot Yellow
blue = 0x6F90F5 # Roxbot Blue
frog_green = 0x4C943D # Used for FROGTIPS
red = 0xe74c3c # Used for on_error
orange = 0xefa940 # Used for warnings (not the admin cog command)
red = 0xe74c3c # Used for errors
dark_red = 0x992d22 # Used for on_command_error
frog_green = 0x4C943D # Used for FROGTIPS
triv_green = 0x1fb600 # Used for the correct answer in trivia
gold = 0xd4af3a # Used for displaying the winner in trivia

+ 32
- 28
roxbot/err_handle.py View File

@@ -45,39 +45,48 @@ class ErrHandle:
async def on_error(self, event):
if self.dev:
traceback.print_exc()
else:
embed = discord.Embed(title="Roxbot Error", colour=roxbot.EmbedColours.red)
embed.add_field(name='Event', value=event)
embed.description = '```py\n{}\n```'.format(traceback.format_exc())
embed.timestamp = datetime.datetime.utcnow()
await self.bot.get_user(self.bot.owner_id).send(embed=embed)

async def on_command_error(self, ctx, error):
owner = self.bot.get_user(self.bot.owner_id)
if self.dev:
raise error
else:
# UserError warning section

user_errors = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments)

if isinstance(error, user_errors):
embed = discord.Embed(colour=roxbot.EmbedColours.orange)
if isinstance(error, commands.MissingRequiredArgument):
embed.description = "Required argument missing. {}".format(error.args[0])
elif isinstance(error, commands.BadArgument):
embed.description = "Bad Argument given. {}".format(error.args[0])
elif isinstance(error, commands.TooManyArguments):
embed.description = "Too many arguments given."
elif isinstance(error, roxbot.UserError):
embed.description = error.args[0]
elif isinstance(error, roxbot.CogSettingDisabled):
embed.description = "The following is not enabled on this server: {}".format(error.args[0])
return await ctx.send(embed=embed)

# ActualErrorHandling
embed = discord.Embed()
if isinstance(error, commands.NoPrivateMessage):
embed.description = "This command cannot be used in private messages."
elif isinstance(error, commands.DisabledCommand):
embed.description = "This command is disabled."
elif isinstance(error, commands.MissingRequiredArgument):
embed.description = "Required argument missing. {}".format(error.args[0])
elif isinstance(error, commands.BadArgument):
embed.description = "Bad Argument given. {}".format(error.args[0])
elif isinstance(error, commands.TooManyArguments):
embed.description = "Too many arguments given."
elif isinstance(error, commands.CommandNotFound):
cc = guild_settings.get(ctx.guild)["custom_commands"]
if ctx.invoked_with in cc["1"] or ctx.invoked_with in cc["2"]:
embed = None
elif len(ctx.message.content) <= 2:
embed = None
elif any(x in string.punctuation for x in ctx.message.content.strip(ctx.prefix)[0]):
# Should avoid punctuation emoticons. Checks all of the command for punctuation in the string.
embed = None
else:
try:
# Sadly this is the only part that makes a cog not modular. I have tried my best though to make it usable without the cog.
cc = guild_settings.get(ctx.guild)["custom_commands"]
is_custom_command = bool(ctx.invoked_with in cc["1"] or ctx.invoked_with in cc["2"])
is_emoticon_face = bool(any(x in string.punctuation for x in ctx.message.content.strip(ctx.prefix)[0]))
is_too_short = bool(len(ctx.message.content) <= 2)
if is_custom_command or is_emoticon_face or is_too_short:
embed = None
else:
embed.description = "That Command doesn't exist."
except KeyError:
embed.description = "That Command doesn't exist."
elif isinstance(error, commands.BotMissingPermissions):
embed.description = "{}".format(error.args[0].replace("Bot", "roxbot"))
@@ -99,21 +108,16 @@ class ErrHandle:

# Final catches for errors undocumented.
else:

embed = discord.Embed(title='Command Error', colour=roxbot.EmbedColours.dark_red)
embed.description = str(error)
embed.add_field(name='Server', value=ctx.guild)
try:
embed.add_field(name='Channel', value=ctx.channel.mention)
except AttributeError:
embed.add_field(name='Channel', value=ctx.channel.id)
embed.add_field(name='User', value=ctx.author)
embed.add_field(name='Message', value=ctx.message.content)
embed.timestamp = datetime.datetime.utcnow()
elif isinstance(error, commands.CommandError):
embed.description = "Command Error. {}".format(error.args[0])
else:
embed = discord.Embed(
description="Placeholder embed. If you see this please message {}.".format(str(owner)))
raise error
if embed:
embed.colour = roxbot.EmbedColours.dark_red
await ctx.send(embed=embed)

+ 52
- 0
roxbot/errors.py View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-

"""
MIT License

Copyright (c) 2017-2018 Roxanne Gibson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""


from discord.ext import commands


__all__ = ["UserError", "CogSettingDisabled"]


class RoxbotException(commands.CommandError):
"""Base Exception for Roxbot."""
pass


class UserError(RoxbotException):
"""Exception for user errors (similar to BadArgument in discord.ext.commands)"""
def __init__(self, message=None):
if message is not None:
m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
super().__init__(m)


class CogSettingDisabled(RoxbotException):
"""Exception for cog setting being disabled"""
def __init__(self, message=None):
if message is not None:
m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
super().__init__(m)

Loading…
Cancel
Save