diff options
| -rw-r--r-- | bot/exts/evergreen/error_handler.py | 7 | ||||
| -rw-r--r-- | bot/exts/evergreen/wikipedia.py | 78 | ||||
| -rw-r--r-- | bot/utils/exceptions.py | 10 | 
3 files changed, 68 insertions, 27 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 7b96cb7b..879146a6 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__) @@ -46,37 +47,62 @@ 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: -                raw_data = await resp.json() -                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']}" -                        ) -                        lines.append(line) - -                    return lines +            if resp.status != 200: +                log.info(f"Unexpected response `{resp.status}` while searching wikipedia for `{search}`") +                raise ExternalAPIError("Wikipedia API") +            raw_data = await resp.json() +            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']}" +                    ) +                    lines.append(line) + +                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: -                    await channel.send( -                        "Sorry, we could not find a wikipedia article using that search term." +                    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"] +                            ) +                        ), +                        url=f"https://en.wikipedia.org/?curid={article['pageid']}"                      ) -                    return +                    lines.append(line) + +                return lines +              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 | 
