diff options
| -rw-r--r-- | bot/exts/info/code_snippets.py | 26 |
1 files changed, 19 insertions, 7 deletions
diff --git a/bot/exts/info/code_snippets.py b/bot/exts/info/code_snippets.py index d854ebb4c..669a21c7d 100644 --- a/bot/exts/info/code_snippets.py +++ b/bot/exts/info/code_snippets.py @@ -1,3 +1,4 @@ +import logging import re import textwrap from urllib.parse import quote_plus @@ -8,6 +9,7 @@ from discord.ext.commands import Cog from bot.bot import Bot from bot.utils.messages import wait_for_deletion +log = logging.getLogger(__name__) GITHUB_RE = re.compile( r'https://github\.com/(?P<repo>.+?)/blob/(?P<path>.+/.+)' @@ -40,11 +42,14 @@ class CodeSnippets(Cog): async def _fetch_response(self, url: str, response_format: str, **kwargs) -> str: """Makes http requests using aiohttp.""" - async with self.bot.http_session.get(url, **kwargs) as response: - if response_format == 'text': - return await response.text() - elif response_format == 'json': - return await response.json() + try: + async with self.bot.http_session.get(url, **kwargs) as response: + if response_format == 'text': + return await response.text() + elif response_format == 'json': + return await response.json() + except Exception: + log.exception(f'Failed to fetch code snippet from {url}.') def _find_ref(self, path: str, refs: tuple) -> tuple: """Loops through all branches and tags to find the required ref.""" @@ -187,9 +192,16 @@ class CodeSnippets(Cog): if not is_valid_language: language = '' + # Adds a label showing the file path to the snippet + if start_line == end_line: + ret = f'`{file_path}` line {start_line}\n' + else: + ret = f'`{file_path}` lines {start_line} to {end_line}\n' + if len(required) != 0: - return f'```{language}\n{required}```\n' - return '' + return f'{ret}```{language}\n{required}```\n' + # Returns an empty codeblock if the snippet is empty + return f'{ret}``` ```\n' def __init__(self, bot: Bot): """Initializes the cog's bot.""" |