Skip to content

Commit bd04108

Browse files
authored
Merge pull request #227 from kyb3r/better-errors
Better error messages
2 parents ce91cb9 + 0643c98 commit bd04108

File tree

4 files changed

+53
-17
lines changed

4 files changed

+53
-17
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
# v2.18.2
8+
9+
### Changed
10+
11+
Commands now have better error messages, instead of just sending the help message for a command when an argument fails to be converted to its specified object, the bot now says things like "User 'bob' not found" instead.
12+
713
# v2.18.1
814

915
Un-deprecated the `OWNERS` config variable to support discord developer team accounts.

bot.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -784,11 +784,31 @@ async def on_error(self, event_method, *args, **kwargs):
784784
logger.error(error('Ignoring exception in {}'.format(event_method)))
785785
logger.error(error('Unexpected exception:'), exc_info=sys.exc_info())
786786

787-
async def on_command_error(self, context, exception):
788-
if isinstance(exception, (commands.MissingRequiredArgument,
789-
commands.UserInputError)):
790-
await context.invoke(self.get_command('help'),
791-
command=str(context.command))
787+
async def on_command_error(self, ctx, exception):
788+
789+
def human_join(strings):
790+
if len(strings) <= 2:
791+
return ' or '.join(strings)
792+
else:
793+
return ', '.join(strings[:len(strings)-1]) + ' or ' + strings[-1]
794+
795+
if isinstance(exception, commands.BadUnionArgument):
796+
msg = 'Could not find the specified ' + human_join([c.__name__ for c in exception.converters])
797+
await ctx.trigger_typing()
798+
await ctx.send(embed=discord.Embed(
799+
color=discord.Color.red(),
800+
description=msg
801+
))
802+
803+
elif isinstance(exception, commands.BadArgument):
804+
await ctx.trigger_typing()
805+
await ctx.send(embed=discord.Embed(
806+
color=discord.Color.red(),
807+
description=str(exception)
808+
))
809+
elif isinstance(exception, commands.MissingRequiredArgument):
810+
await ctx.invoke(self.get_command('help'),
811+
command=str(ctx.command))
792812
elif isinstance(exception, commands.CommandNotFound):
793813
logger.warning(error('CommandNotFound: ' + str(exception)))
794814
elif isinstance(exception, commands.CheckFailure):

cogs/modmail.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import re
33
from datetime import datetime
44
from typing import Optional, Union
5+
from types import SimpleNamespace as param
56

67
import discord
78
from discord.ext import commands
@@ -420,7 +421,7 @@ async def logs(self, ctx, *, member: User = None):
420421
if not member:
421422
thread = ctx.thread
422423
if not thread:
423-
raise commands.UserInputError
424+
raise commands.MissingRequiredArgument(param(name='member'))
424425
user = thread.recipient
425426
else:
426427
user = member
@@ -689,15 +690,17 @@ async def block(self, ctx, user: Optional[User] = None, *,
689690
thread = ctx.thread
690691
if thread:
691692
user = thread.recipient
693+
elif after is None:
694+
raise commands.MissingRequiredArgument(param(name='user'))
692695
else:
693-
raise commands.UserInputError
696+
raise commands.BadArgument(f'User "{after.arg}" not found')
694697

695698
if after is not None:
696699
reason = after.arg
697700
if reason.startswith('System Message: '):
698-
raise commands.UserInputError
701+
raise commands.BadArgument('The reason cannot start with `System Message:`.')
699702
if re.search(r'%(.+?)%$', reason) is not None:
700-
raise commands.UserInputError
703+
raise commands.MissingRequiredArgument(param(name='reason'))
701704
if after.dt > after.now:
702705
reason = f'{reason} %{after.dt.isoformat()}%'
703706

@@ -749,12 +752,13 @@ async def unblock(self, ctx, *, user: User = None):
749752
use only.
750753
"""
751754

755+
752756
if user is None:
753757
thread = ctx.thread
754758
if thread:
755759
user = thread.recipient
756760
else:
757-
raise commands.UserInputError
761+
raise commands.MissingRequiredArgument(param(name='user'))
758762

759763
mention = user.mention if hasattr(user, 'mention') else f'`{user.id}`'
760764

@@ -792,14 +796,20 @@ async def unblock(self, ctx, *, user: User = None):
792796

793797
@commands.command()
794798
@checks.has_permissions(PermissionLevel.SUPPORTER)
795-
async def delete(self, ctx, message_id: int = None):
799+
@checks.thread_only()
800+
async def delete(self, ctx, message_id = None):
796801
"""Delete a message that was sent using the reply command.
797802
798803
Deletes the previous message, unless a message ID is provided, which in that case,
799804
deletes the message with that message ID.
800805
"""
801806
thread = ctx.thread
802807

808+
try:
809+
message_id = int(message_id)
810+
except ValueError:
811+
raise commands.BadArgument('An integer message ID needs to be specified.')
812+
803813
linked_message_id = await self.find_linked_message(ctx, message_id)
804814

805815
if linked_message_id is None:

cogs/utility.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ async def format_not_found(self, ctx, command):
130130

131131
choices = set()
132132

133-
for name, c in self.bot.all_commands:
133+
for name, c in self.bot.all_commands.items():
134134
if not c.hidden:
135135
choices.add(name)
136136

@@ -909,7 +909,7 @@ async def add_perms_command(self, ctx, command: str, *, user_or_role: Union[User
909909
elif user_or_role in {'everyone', 'all'}:
910910
value = -1
911911
else:
912-
raise commands.UserInputError('Invalid user or role.')
912+
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
913913

914914
await self.bot.update_perms(self.bot.all_commands[command].name, value)
915915
embed = Embed(
@@ -937,7 +937,7 @@ async def add_perms_level(self, ctx, level: str, *, user_or_role: Union[User, Ro
937937
elif user_or_role in {'everyone', 'all'}:
938938
value = -1
939939
else:
940-
raise commands.UserInputError('Invalid user or role.')
940+
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
941941

942942
await self.bot.update_perms(PermissionLevel[level.upper()], value)
943943
embed = Embed(
@@ -973,7 +973,7 @@ async def remove_perms_command(self, ctx, command: str, *, user_or_role: Union[U
973973
elif user_or_role in {'everyone', 'all'}:
974974
value = -1
975975
else:
976-
raise commands.UserInputError('Invalid user or role.')
976+
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
977977

978978
await self.bot.update_perms(self.bot.all_commands[command].name, value, add=False)
979979
embed = Embed(
@@ -1001,7 +1001,7 @@ async def remove_perms_level(self, ctx, level: str, *, user_or_role: Union[User,
10011001
elif user_or_role in {'everyone', 'all'}:
10021002
value = -1
10031003
else:
1004-
raise commands.UserInputError('Invalid user or role.')
1004+
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
10051005

10061006
await self.bot.update_perms(PermissionLevel[level.upper()], value, add=False)
10071007
embed = Embed(
@@ -1021,7 +1021,7 @@ async def get_perms(self, ctx, *, user_or_role: Union[User, Role, str]):
10211021
elif user_or_role in {'everyone', 'all'}:
10221022
value = -1
10231023
else:
1024-
raise commands.UserInputError('Invalid user or role.')
1024+
raise commands.BadArgument(f'User or Role "{user_or_role}" not found')
10251025

10261026
cmds = []
10271027
levels = []

0 commit comments

Comments
 (0)