From f36cdb23cf9a8a5470180d85d336577658d849c3 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Mon, 2 Aug 2021 21:58:21 +0200 Subject: Refactor wiki_request, add External API related error,-handler - Refactor wiki_request in the Wikipedia Cog, remove unnecessary else statements. - Add ExternalAPIError, and a handler for this Exception into error_handler --- bot/utils/exceptions.py | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'bot/utils/exceptions.py') diff --git a/bot/utils/exceptions.py b/bot/utils/exceptions.py index 9e080759..5ccd6139 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -1,4 +1,14 @@ + class UserNotPlayingError(Exception): """Raised when users try to use game commands when they are not playing.""" pass + + +class ExternalAPIError(Exception): + """Raised when an external API(eg. Wikipedia) returns an error.""" + + def __init__(self, api: str): + super().__init__() + self.api = api + pass -- cgit v1.2.3 From ff0d3a833bbbe517f50124c5157223ff95876931 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Sun, 8 Aug 2021 15:51:44 +0200 Subject: Improve code consitency in Wikipedia Cog,Exceptions, and Error handler --- bot/exts/evergreen/error_handler.py | 11 ++++++++--- bot/exts/evergreen/wikipedia.py | 15 ++++++--------- bot/utils/exceptions.py | 9 ++++++--- 3 files changed, 20 insertions(+), 15 deletions(-) (limited to 'bot/utils/exceptions.py') diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 1662af50..8fcbb8f2 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -113,7 +113,10 @@ class CommandErrorHandler(commands.Cog): return if isinstance(error, commands.CheckFailure): - await ctx.send(embed=self.error_embed("You are not authorized to use this command.", NEGATIVE_REPLIES)) + await ctx.send( + embed=self.error_embed( + "You are not authorized to use this command.", + NEGATIVE_REPLIES)) return if isinstance(error, UserNotPlayingError): @@ -121,8 +124,10 @@ class CommandErrorHandler(commands.Cog): return if isinstance(error, ExternalAPIError): - await ctx.send(embed=self.error_embed(f"There was an error when communicating with the {error.api}", - NEGATIVE_REPLIES)) + await ctx.send( + embed=self.error_embed( + f"There was an error when communicating with the {error.api}", + NEGATIVE_REPLIES)) return with push_scope() as scope: diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index 879146a6..63462433 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -47,9 +47,9 @@ class WikipediaSearch(commands.Cog): """Search wikipedia search string and return formatted first 10 pages found.""" params = WIKI_PARAMS | {"srlimit": 10, "srsearch": search} async with self.bot.http_session.get(url=SEARCH_API, params=params) as resp: - if resp.status != 200: + if (status := resp.status) != 200: log.info(f"Unexpected response `{resp.status}` while searching wikipedia for `{search}`") - raise ExternalAPIError("Wikipedia API") + raise ExternalAPIError("Wikipedia API", status) raw_data = await resp.json() number_of_results = raw_data["query"]["searchinfo"]["totalhits"] @@ -72,13 +72,10 @@ class WikipediaSearch(commands.Cog): return lines raw_data = await resp.json() - if raw_data.get("query", None) is None: - if raw_data.get("errors", None) is not None: - log.info("There was an error regarding the Wikipedia API query.") - else: - log.info("There was an issue when trying to communicate with the Wikipedia API, " - "please try again later.") - raise ExternalAPIError("Wikipedia API") + if not raw_data.get("query", None): + if error := raw_data.get("errors"): + log.error(f"There was an error while communicating with the Wikipedia API: {error}") + raise ExternalAPIError("Wikipedia API", status, error) number_of_results = raw_data["query"]["searchinfo"]["totalhits"] diff --git a/bot/utils/exceptions.py b/bot/utils/exceptions.py index 5ccd6139..73c8e3e1 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -1,3 +1,5 @@ +from typing import Optional + class UserNotPlayingError(Exception): """Raised when users try to use game commands when they are not playing.""" @@ -6,9 +8,10 @@ class UserNotPlayingError(Exception): class ExternalAPIError(Exception): - """Raised when an external API(eg. Wikipedia) returns an error.""" + """Raised when an external API(eg. Wikipedia) returns an error response.""" - def __init__(self, api: str): + def __init__(self, api: str, status_code: int, error_msg: Optional[str] = None): super().__init__() self.api = api - pass + self.status_code = status_code + self.error_msg = error_msg -- cgit v1.2.3 From ce80a2fb34c14e2ece0b4ffc6bda85030764ef9c Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Tue, 17 Aug 2021 16:25:14 +0200 Subject: Improve code consistency and spacing in the Wikipedia Cog --- bot/exts/evergreen/error_handler.py | 4 ++-- bot/exts/evergreen/wikipedia.py | 27 +++++++++++++-------------- bot/utils/exceptions.py | 2 +- 3 files changed, 16 insertions(+), 17 deletions(-) (limited to 'bot/utils/exceptions.py') diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 7a916606..a280c725 100644 --- a/bot/exts/evergreen/error_handler.py +++ b/bot/exts/evergreen/error_handler.py @@ -11,7 +11,7 @@ from sentry_sdk import push_scope from bot.bot import Bot from bot.constants import Channels, Colours, ERROR_REPLIES, NEGATIVE_REPLIES, RedirectOutput from bot.utils.decorators import InChannelCheckFailure, InMonthCheckFailure -from bot.utils.exceptions import ExternalAPIError, UserNotPlayingError +from bot.utils.exceptions import APIError, UserNotPlayingError log = logging.getLogger(__name__) @@ -120,7 +120,7 @@ class CommandErrorHandler(commands.Cog): await ctx.send("Game not found.") return - if isinstance(error, ExternalAPIError): + if isinstance(error, APIError): await ctx.send( embed=self.error_embed( f"There was an error when communicating with the {error.api}", diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index 35ab27f1..cabce1ad 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -2,14 +2,14 @@ import logging import re from datetime import datetime from html import unescape -from typing import List, Optional +from typing import List from discord import Color, Embed, TextChannel from discord.ext import commands from bot.bot import Bot from bot.utils import LinePaginator -from bot.utils.exceptions import ExternalAPIError +from bot.utils.exceptions import APIError log = logging.getLogger(__name__) @@ -43,25 +43,25 @@ class WikipediaSearch(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - async def wiki_request(self, channel: TextChannel, search: str) -> Optional[List[str]]: + async def wiki_request(self, channel: TextChannel, search: str) -> List[str]: """Search wikipedia search string and return formatted first 10 pages found.""" params = WIKI_PARAMS | {"srlimit": 10, "srsearch": search} async with self.bot.http_session.get(url=SEARCH_API, params=params) as resp: if (status := resp.status) != 200: log.info(f"Unexpected response `{status}` while searching wikipedia for `{search}`") - raise ExternalAPIError("Wikipedia API", status) + raise APIError("Wikipedia API", status) raw_data = await resp.json() + if not raw_data.get("query"): if error := raw_data.get("errors"): log.error(f"There was an error while communicating with the Wikipedia API: {error}") - raise ExternalAPIError("Wikipedia API", status, error) + raise APIError("Wikipedia API", status, error) number_of_results = raw_data["query"]["searchinfo"]["totalhits"] - + lines = [] if number_of_results: results = raw_data["query"]["search"] - lines = [] for article in results: line = WIKI_SEARCH_RESULT.format( @@ -75,13 +75,7 @@ class WikipediaSearch(commands.Cog): ) lines.append(line) - return lines - - else: - await channel.send( - "Sorry, we could not find a wikipedia article using that search term." - ) - return + return lines @commands.cooldown(1, 10, commands.BucketType.user) @commands.command(name="wikipedia", aliases=("wiki",)) @@ -99,6 +93,11 @@ class WikipediaSearch(commands.Cog): await LinePaginator.paginate( contents, ctx, embed ) + else: + await ctx.send( + "Sorry, we could not find a wikipedia article using that search term." + ) + return def setup(bot: Bot) -> None: diff --git a/bot/utils/exceptions.py b/bot/utils/exceptions.py index 73c8e3e1..b4175695 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -7,7 +7,7 @@ class UserNotPlayingError(Exception): pass -class ExternalAPIError(Exception): +class APIError(Exception): """Raised when an external API(eg. Wikipedia) returns an error response.""" def __init__(self, api: str, status_code: int, error_msg: Optional[str] = None): -- cgit v1.2.3 From 4f5432a97bfafab237efa6efa7bb6daebc83577d Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Fri, 20 Aug 2021 21:25:17 +0200 Subject: Adjust spacing in the Wikipedia Cog Co-authored-by: Bluenix --- bot/utils/exceptions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot/utils/exceptions.py') diff --git a/bot/utils/exceptions.py b/bot/utils/exceptions.py index b4175695..bf0e5813 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -8,7 +8,7 @@ class UserNotPlayingError(Exception): class APIError(Exception): - """Raised when an external API(eg. Wikipedia) returns an error response.""" + """Raised when an external API (eg. Wikipedia) returns an error response.""" def __init__(self, api: str, status_code: int, error_msg: Optional[str] = None): super().__init__() -- cgit v1.2.3