diff options
Diffstat (limited to 'bot')
| -rw-r--r-- | bot/exts/evergreen/error_handler.py | 7 | ||||
| -rw-r--r-- | bot/exts/evergreen/wikipedia.py | 67 | ||||
| -rw-r--r-- | bot/utils/exceptions.py | 10 | 
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 | 
