From e666fb7b80a9f590257d1426c7604ff180b35e6e Mon Sep 17 00:00:00 2001 From: Salil Chincholikar Date: Tue, 27 Apr 2021 14:39:58 +0530 Subject: Reworded/fixed grammatical error --- 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 2b1c1b31..5e4d6330 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -1,4 +1,4 @@ class UserNotPlayingError(Exception): - """Will raised when user try to use game commands when not playing.""" + """Will be raised when the users try to use game commands when they are not playing.""" pass -- cgit v1.2.3 From 4e0210922ef8d25eeb18f080c9baab022d70d0d2 Mon Sep 17 00:00:00 2001 From: Salil Chincholikar <31334826+chincholikarsalil@users.noreply.github.com> Date: Tue, 27 Apr 2021 19:12:28 +0530 Subject: Updated bot/utils/exceptions.py Co-authored-by: Joe Banks --- 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 5e4d6330..9e080759 100644 --- a/bot/utils/exceptions.py +++ b/bot/utils/exceptions.py @@ -1,4 +1,4 @@ class UserNotPlayingError(Exception): - """Will be raised when the users try to use game commands when they are not playing.""" + """Raised when users try to use game commands when they are not playing.""" pass -- cgit v1.2.3 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/exts/evergreen/error_handler.py | 7 +++- bot/exts/evergreen/wikipedia.py | 67 +++++++++++++++++-------------------- bot/utils/exceptions.py | 10 ++++++ 3 files changed, 47 insertions(+), 37 deletions(-) (limited to 'bot/utils/exceptions.py') diff --git a/bot/exts/evergreen/error_handler.py b/bot/exts/evergreen/error_handler.py index 5873fb83..1662af50 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 UserNotPlayingError +from bot.utils.exceptions import ExternalAPIError, UserNotPlayingError log = logging.getLogger(__name__) @@ -120,6 +120,11 @@ class CommandErrorHandler(commands.Cog): await ctx.send("Game not found.") 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)) + return + with push_scope() as scope: scope.user = { "id": ctx.author.id, diff --git a/bot/exts/evergreen/wikipedia.py b/bot/exts/evergreen/wikipedia.py index 8af22737..d53424fd 100644 --- a/bot/exts/evergreen/wikipedia.py +++ b/bot/exts/evergreen/wikipedia.py @@ -9,6 +9,7 @@ from discord.ext import commands from bot.bot import Bot from bot.utils import LinePaginator +from bot.utils.exceptions import ExternalAPIError log = logging.getLogger(__name__) @@ -37,48 +38,42 @@ class WikipediaSearch(commands.Cog): """Search wikipedia search string and return formatted first 10 pages found.""" url = SEARCH_API.format(number_of_results=10, string=search) async with self.bot.http_session.get(url=url) as resp: - if resp.status == 200: - 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") - - await channel.send( - "There was an issue processing your Wikipedia request, please try again later.") - return - else: + if resp.status != 200: + log.info(f"Unexpected response `{resp.status}` while searching wikipedia for `{search}`") + raise ExternalAPIError("Wikipedia API") - number_of_results = raw_data["query"]["searchinfo"]["totalhits"] - - if number_of_results: - results = raw_data["query"]["search"] - lines = [] - - for article in results: - line = WIKI_SEARCH_RESULT.format( - name=article["title"], - description=unescape( - re.sub( - WIKI_SNIPPET_REGEX, "", article["snippet"] - ) - ), - url=f"https://en.wikipedia.org/?curid={article['pageid']}" + 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") + + number_of_results = raw_data["query"]["searchinfo"]["totalhits"] + + if number_of_results: + results = raw_data["query"]["search"] + lines = [] + + for article in results: + line = WIKI_SEARCH_RESULT.format( + name=article["title"], + description=unescape( + re.sub( + WIKI_SNIPPET_REGEX, "", article["snippet"] ) - lines.append(line) + ), + url=f"https://en.wikipedia.org/?curid={article['pageid']}" + ) + lines.append(line) - return lines + return lines - else: - await channel.send( - "Sorry, we could not find a wikipedia article using that search term." - ) - return else: - log.info(f"Unexpected response `{resp.status}` while searching wikipedia for `{search}`") await channel.send( - "Whoops, the Wikipedia API is having some issues right now. Try again later." + "Sorry, we could not find a wikipedia article using that search term." ) return 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