diff options
| author | 2019-09-14 13:10:08 +0200 | |
|---|---|---|
| committer | 2019-09-14 13:10:08 +0200 | |
| commit | f983b8bd4766a8bfd4dfe1b7d0c249b039244dc1 (patch) | |
| tree | e02a5b5c72db7b45f5e48d1823fba503b3f71b1a /bot/utils/moderation.py | |
| parent | Add API response dict to ResponseCodeError (diff) | |
Make 'post_infraction' catch the right exception
The internal 'api' of our API client has changed: It raises a custom
RespondeCodeError instead of an `aiohttp.ClientError` when an API was
not successful. I updated this utility function to catch the right
exception and added handling for unknown users by notifying the user
of that problem directly.
Diffstat (limited to 'bot/utils/moderation.py')
| -rw-r--r-- | bot/utils/moderation.py | 28 |
1 files changed, 17 insertions, 11 deletions
diff --git a/bot/utils/moderation.py b/bot/utils/moderation.py index 152f9d538..b295e4649 100644 --- a/bot/utils/moderation.py +++ b/bot/utils/moderation.py @@ -1,11 +1,11 @@ import logging from datetime import datetime -from typing import Union +from typing import Optional, Union -from aiohttp import ClientError from discord import Member, Object, User from discord.ext.commands import Context +from bot.api import ResponseCodeError from bot.constants import Keys log = logging.getLogger(__name__) @@ -21,8 +21,8 @@ async def post_infraction( expires_at: datetime = None, hidden: bool = False, active: bool = True, -): - +) -> Optional[dict]: + """Posts an infraction to the API.""" payload = { "actor": ctx.message.author.id, "hidden": hidden, @@ -35,13 +35,19 @@ async def post_infraction( payload['expires_at'] = expires_at.isoformat() try: - response = await ctx.bot.api_client.post( - 'bot/infractions', json=payload - ) - except ClientError: - log.exception("There was an error adding an infraction.") - await ctx.send(":x: There was an error adding the infraction.") - return + response = await ctx.bot.api_client.post('bot/infractions', json=payload) + except ResponseCodeError as exp: + if exp.status == 400 and 'user' in exp.response_data: + log.info( + f"{ctx.author} tried to add a {type} infraction to `{user.id}`, " + "but that user id was not found in the database." + ) + await ctx.send(f":x: Cannot add infraction, the specified user is not known to the database.") + return + else: + log.exception("An unexpected ResponseCodeError occurred while adding an infraction:") + await ctx.send(":x: There was an error adding the infraction.") + return return response |