aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar D0rs4n <[email protected]>2021-08-02 21:58:21 +0200
committerGravatar D0rs4n <[email protected]>2021-08-02 21:58:21 +0200
commitf36cdb23cf9a8a5470180d85d336577658d849c3 (patch)
tree65f91b49a49eac8c48c9637a12c1dda2f0111915
parentHandle Wikipedia API errors and warnings in the Wikipedia Cog (diff)
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
-rw-r--r--bot/exts/evergreen/error_handler.py7
-rw-r--r--bot/exts/evergreen/wikipedia.py67
-rw-r--r--bot/utils/exceptions.py10
3 files changed, 47 insertions, 37 deletions
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