From 4ec414ad37c6c10218b80ebd1b028840c0f0f853 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Tue, 29 Jun 2021 11:47:30 -0400 Subject: chore: Merge the .issue command into the github cog --- bot/exts/utilities/githubinfo.py | 273 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 267 insertions(+), 6 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index 539e388b..f0820731 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -1,5 +1,8 @@ import logging import random +import re +import typing as t +from dataclasses import dataclass from datetime import datetime from urllib.parse import quote, quote_plus @@ -7,24 +10,183 @@ import discord from discord.ext import commands from bot.bot import Bot -from bot.constants import Colours, NEGATIVE_REPLIES +from bot.constants import ( + Categories, + Channels, + Colours, + ERROR_REPLIES, + Emojis, + NEGATIVE_REPLIES, + Tokens, + WHITELISTED_CHANNELS +) from bot.exts.core.extensions import invoke_help_command +from bot.utils.decorators import whitelist_override log = logging.getLogger(__name__) GITHUB_API_URL = "https://api.github.com" +BAD_RESPONSE = { + 404: "Issue/pull request not located! Please enter a valid number!", + 403: "Rate limit has been hit! Please try again later!" +} +REQUEST_HEADERS = { + "Accept": "application/vnd.github.v3+json" +} + +REPOSITORY_ENDPOINT = "https://api.github.com/orgs/{org}/repos?per_page=100&type=public" +ISSUE_ENDPOINT = "https://api.github.com/repos/{user}/{repository}/issues/{number}" +PR_ENDPOINT = "https://api.github.com/repos/{user}/{repository}/pulls/{number}" + +if GITHUB_TOKEN := Tokens.github: + REQUEST_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}" + +WHITELISTED_CATEGORIES = ( + Categories.development, Categories.devprojects, Categories.media, Categories.staff +) + +CODE_BLOCK_RE = re.compile( + r"^`([^`\n]+)`" # Inline codeblock + r"|```(.+?)```", # Multiline codeblock + re.DOTALL | re.MULTILINE +) + +# Maximum number of issues in one message +MAXIMUM_ISSUES = 5 + +# Regex used when looking for automatic linking in messages +# regex101 of current regex https://regex101.com/r/V2ji8M/6 +AUTOMATIC_REGEX = re.compile( + r"((?P[a-zA-Z0-9][a-zA-Z0-9\-]{1,39})\/)?(?P[\w\-\.]{1,100})#(?P[0-9]+)" +) + + +@dataclass +class FoundIssue: + """Dataclass representing an issue found by the regex.""" + + organisation: t.Optional[str] + repository: str + number: str + + def __hash__(self) -> int: + return hash((self.organisation, self.repository, self.number)) + + +@dataclass +class FetchError: + """Dataclass representing an error while fetching an issue.""" + + return_code: int + message: str + + +@dataclass +class IssueState: + """Dataclass representing the state of an issue.""" + + repository: str + number: int + url: str + title: str + emoji: str + class GithubInfo(commands.Cog): - """Fetches info from GitHub.""" + """A Cog that fetches info from GitHub.""" def __init__(self, bot: Bot): self.bot = bot + self.repos = [] + + @staticmethod + def remove_codeblocks(message: str) -> str: + """Remove any codeblock in a message.""" + return CODE_BLOCK_RE.sub("", message) + + async def fetch_issues( + self, + number: int, + repository: str, + user: str + ) -> t.Union[IssueState, FetchError]: + """ + Retrieve an issue from a GitHub repository. - async def fetch_data(self, url: str) -> dict: - """Retrieve data as a dictionary.""" - async with self.bot.http_session.get(url) as r: - return await r.json() + Returns IssueState on success, FetchError on failure. + """ + url = ISSUE_ENDPOINT.format(user=user, repository=repository, number=number) + pulls_url = PR_ENDPOINT.format(user=user, repository=repository, number=number) + log.trace(f"Querying GH issues API: {url}") + + async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as r: + json_data = await r.json() + + if r.status == 403: + if r.headers.get("X-RateLimit-Remaining") == "0": + log.info(f"Ratelimit reached while fetching {url}") + return FetchError(403, "Ratelimit reached, please retry in a few minutes.") + return FetchError(403, "Cannot access issue.") + elif r.status in (404, 410): + return FetchError(r.status, "Issue not found.") + elif r.status != 200: + return FetchError(r.status, "Error while fetching issue.") + + # The initial API request is made to the issues API endpoint, which will return information + # if the issue or PR is present. However, the scope of information returned for PRs differs + # from issues: if the 'issues' key is present in the response then we can pull the data we + # need from the initial API call. + if "issues" in json_data["html_url"]: + if json_data.get("state") == "open": + emoji = Emojis.issue_open + else: + emoji = Emojis.issue_closed + + # If the 'issues' key is not contained in the API response and there is no error code, then + # we know that a PR has been requested and a call to the pulls API endpoint is necessary + # to get the desired information for the PR. + else: + log.trace(f"PR provided, querying GH pulls API for additional information: {pulls_url}") + async with self.bot.http_session.get(pulls_url) as p: + pull_data = await p.json() + if pull_data["draft"]: + emoji = Emojis.pull_request_draft + elif pull_data["state"] == "open": + emoji = Emojis.pull_request_open + # When 'merged_at' is not None, this means that the state of the PR is merged + elif pull_data["merged_at"] is not None: + emoji = Emojis.pull_request_merged + else: + emoji = Emojis.pull_request_closed + + issue_url = json_data.get("html_url") + + return IssueState(repository, number, issue_url, json_data.get("title", ""), emoji) + + @staticmethod + def format_embed( + results: t.List[t.Union[IssueState, FetchError]], + user: str, + repository: t.Optional[str] = None + ) -> discord.Embed: + """Take a list of IssueState or FetchError and format a Discord embed for them.""" + description_list = [] + + for result in results: + if isinstance(result, IssueState): + description_list.append(f"{result.emoji} [{result.title}]({result.url})") + elif isinstance(result, FetchError): + description_list.append(f":x: [{result.return_code}] {result.message}") + + resp = discord.Embed( + colour=Colours.bright_green, + description="\n".join(description_list) + ) + + embed_url = f"https://github.com/{user}/{repository}" if repository else f"https://github.com/{user}" + resp.set_author(name="GitHub", url=embed_url) + return resp @commands.group(name="github", aliases=("gh", "git")) @commands.cooldown(1, 10, commands.BucketType.user) @@ -33,6 +195,105 @@ class GithubInfo(commands.Cog): if ctx.invoked_subcommand is None: await invoke_help_command(ctx) + @whitelist_override(channels=WHITELISTED_CHANNELS, categories=WHITELISTED_CATEGORIES) + @github_group.command(aliases=("pr", "issues", "prs"), root_aliases=("issue", "pr")) + async def issue( + self, + ctx: commands.Context, + numbers: commands.Greedy[int], + repository: str = "sir-lancebot", + user: str = "python-discord" + ) -> None: + """Command to retrieve issue(s) from a GitHub repository.""" + # Remove duplicates + numbers = set(numbers) + + err_message = None + if not numbers: + err_message = "You must have at least one issue/PR!" + + elif len(numbers) > MAXIMUM_ISSUES: + err_message = f"Too many issues/PRs! (maximum of {MAXIMUM_ISSUES})" + + # If there's an error with command invocation then send an error embed + if err_message is not None: + err_embed = discord.Embed( + title=random.choice(ERROR_REPLIES), + color=Colours.soft_red, + description=err_message + ) + await ctx.send(embed=err_embed) + await invoke_help_command(ctx) + return + + results = [await self.fetch_issues(number, repository, user) for number in numbers] + await ctx.send(embed=self.format_embed(results, user, repository)) + + @commands.Cog.listener() + async def on_message(self, message: discord.Message) -> None: + """ + Automatic issue linking. + + Listener to retrieve issue(s) from a GitHub repository using automatic linking if matching /#. + """ + # Ignore bots + if message.author.bot: + return + + issues = [ + FoundIssue(*match.group("org", "repo", "number")) + for match in AUTOMATIC_REGEX.finditer(self.remove_codeblocks(message.content)) + ] + links = [] + + if issues: + # Block this from working in DMs + if not message.guild: + await message.channel.send( + embed=discord.Embed( + title=random.choice(NEGATIVE_REPLIES), + description=( + "You can't retrieve issues from DMs. " + f"Try again in <#{Channels.community_bot_commands}>" + ), + colour=Colours.soft_red + ) + ) + return + + log.trace(f"Found {issues = }") + # Remove duplicates + issues = set(issues) + + if len(issues) > MAXIMUM_ISSUES: + embed = discord.Embed( + title=random.choice(ERROR_REPLIES), + color=Colours.soft_red, + description=f"Too many issues/PRs! (maximum of {MAXIMUM_ISSUES})" + ) + await message.channel.send(embed=embed, delete_after=5) + return + + for repo_issue in issues: + result = await self.fetch_issues( + int(repo_issue.number), + repo_issue.repository, + repo_issue.organisation or "python-discord" + ) + if isinstance(result, IssueState): + links.append(result) + + if not links: + return + + resp = self.format_embed(links, "python-discord") + await message.channel.send(embed=resp) + + async def fetch_data(self, url: str) -> dict: + """Retrieve data as a dictionary.""" + async with self.bot.http_session.get(url) as r: + return await r.json() + @github_group.command(name="user", aliases=("userinfo",)) async def github_user_info(self, ctx: commands.Context, username: str) -> None: """Fetches a user's GitHub information.""" -- cgit v1.2.3 From ba10b9b6525beac6637e5a13ead03fb018751201 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 31 Jul 2021 18:42:36 -0400 Subject: chore: Remove the .issue command --- bot/exts/utilities/githubinfo.py | 37 ------------------------------------- 1 file changed, 37 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index f0820731..b0b327b6 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -18,11 +18,8 @@ from bot.constants import ( Emojis, NEGATIVE_REPLIES, Tokens, - WHITELISTED_CHANNELS ) from bot.exts.core.extensions import invoke_help_command -from bot.utils.decorators import whitelist_override - log = logging.getLogger(__name__) GITHUB_API_URL = "https://api.github.com" @@ -195,40 +192,6 @@ class GithubInfo(commands.Cog): if ctx.invoked_subcommand is None: await invoke_help_command(ctx) - @whitelist_override(channels=WHITELISTED_CHANNELS, categories=WHITELISTED_CATEGORIES) - @github_group.command(aliases=("pr", "issues", "prs"), root_aliases=("issue", "pr")) - async def issue( - self, - ctx: commands.Context, - numbers: commands.Greedy[int], - repository: str = "sir-lancebot", - user: str = "python-discord" - ) -> None: - """Command to retrieve issue(s) from a GitHub repository.""" - # Remove duplicates - numbers = set(numbers) - - err_message = None - if not numbers: - err_message = "You must have at least one issue/PR!" - - elif len(numbers) > MAXIMUM_ISSUES: - err_message = f"Too many issues/PRs! (maximum of {MAXIMUM_ISSUES})" - - # If there's an error with command invocation then send an error embed - if err_message is not None: - err_embed = discord.Embed( - title=random.choice(ERROR_REPLIES), - color=Colours.soft_red, - description=err_message - ) - await ctx.send(embed=err_embed) - await invoke_help_command(ctx) - return - - results = [await self.fetch_issues(number, repository, user) for number in numbers] - await ctx.send(embed=self.format_embed(results, user, repository)) - @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: """ -- cgit v1.2.3 From 101001bfabae0cef37cf36ebbf4420f9d80736e4 Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Sat, 18 Sep 2021 10:28:35 -0400 Subject: chore: Apply suggested changes --- bot/exts/utilities/githubinfo.py | 90 ++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 55 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index b0b327b6..c9a65668 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -4,15 +4,15 @@ import re import typing as t from dataclasses import dataclass from datetime import datetime -from urllib.parse import quote, quote_plus +from urllib.parse import quote import discord +from aiohttp import ClientResponse from discord.ext import commands from bot.bot import Bot from bot.constants import ( Categories, - Channels, Colours, ERROR_REPLIES, Emojis, @@ -20,14 +20,11 @@ from bot.constants import ( Tokens, ) from bot.exts.core.extensions import invoke_help_command + log = logging.getLogger(__name__) GITHUB_API_URL = "https://api.github.com" -BAD_RESPONSE = { - 404: "Issue/pull request not located! Please enter a valid number!", - 403: "Rate limit has been hit! Please try again later!" -} REQUEST_HEADERS = { "Accept": "application/vnd.github.v3+json" } @@ -102,11 +99,11 @@ class GithubInfo(commands.Cog): """Remove any codeblock in a message.""" return CODE_BLOCK_RE.sub("", message) - async def fetch_issues( - self, - number: int, - repository: str, - user: str + async def fetch_issue( + self, + number: int, + repository: str, + user: str ) -> t.Union[IssueState, FetchError]: """ Retrieve an issue from a GitHub repository. @@ -117,8 +114,7 @@ class GithubInfo(commands.Cog): pulls_url = PR_ENDPOINT.format(user=user, repository=repository, number=number) log.trace(f"Querying GH issues API: {url}") - async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as r: - json_data = await r.json() + json_data, r = await self.fetch_data(url) if r.status == 403: if r.headers.get("X-RateLimit-Remaining") == "0": @@ -145,17 +141,17 @@ class GithubInfo(commands.Cog): # to get the desired information for the PR. else: log.trace(f"PR provided, querying GH pulls API for additional information: {pulls_url}") - async with self.bot.http_session.get(pulls_url) as p: - pull_data = await p.json() - if pull_data["draft"]: - emoji = Emojis.pull_request_draft - elif pull_data["state"] == "open": - emoji = Emojis.pull_request_open - # When 'merged_at' is not None, this means that the state of the PR is merged - elif pull_data["merged_at"] is not None: - emoji = Emojis.pull_request_merged - else: - emoji = Emojis.pull_request_closed + + pull_data, _ = await self.fetch_data(pulls_url) + if pull_data["draft"]: + emoji = Emojis.pull_request_draft + elif pull_data["state"] == "open": + emoji = Emojis.pull_request_open + # When 'merged_at' is not None, this means that the state of the PR is merged + elif pull_data["merged_at"] is not None: + emoji = Emojis.pull_request_merged + else: + emoji = Emojis.pull_request_closed issue_url = json_data.get("html_url") @@ -163,9 +159,7 @@ class GithubInfo(commands.Cog): @staticmethod def format_embed( - results: t.List[t.Union[IssueState, FetchError]], - user: str, - repository: t.Optional[str] = None + results: t.List[t.Union[IssueState, FetchError]] ) -> discord.Embed: """Take a list of IssueState or FetchError and format a Discord embed for them.""" description_list = [] @@ -181,8 +175,7 @@ class GithubInfo(commands.Cog): description="\n".join(description_list) ) - embed_url = f"https://github.com/{user}/{repository}" if repository else f"https://github.com/{user}" - resp.set_author(name="GitHub", url=embed_url) + resp.set_author(name="GitHub") return resp @commands.group(name="github", aliases=("gh", "git")) @@ -212,16 +205,6 @@ class GithubInfo(commands.Cog): if issues: # Block this from working in DMs if not message.guild: - await message.channel.send( - embed=discord.Embed( - title=random.choice(NEGATIVE_REPLIES), - description=( - "You can't retrieve issues from DMs. " - f"Try again in <#{Channels.community_bot_commands}>" - ), - colour=Colours.soft_red - ) - ) return log.trace(f"Found {issues = }") @@ -238,7 +221,7 @@ class GithubInfo(commands.Cog): return for repo_issue in issues: - result = await self.fetch_issues( + result = await self.fetch_issue( int(repo_issue.number), repo_issue.repository, repo_issue.organisation or "python-discord" @@ -249,19 +232,19 @@ class GithubInfo(commands.Cog): if not links: return - resp = self.format_embed(links, "python-discord") + resp = self.format_embed(links) await message.channel.send(embed=resp) - async def fetch_data(self, url: str) -> dict: - """Retrieve data as a dictionary.""" - async with self.bot.http_session.get(url) as r: - return await r.json() + async def fetch_data(self, url: str) -> tuple[dict[str], ClientResponse]: + """Retrieve data as a dictionary and the response in a tuple.""" + async with self.bot.http_session.get(url, heades=REQUEST_HEADERS) as r: + return await r.json(), r @github_group.command(name="user", aliases=("userinfo",)) async def github_user_info(self, ctx: commands.Context, username: str) -> None: """Fetches a user's GitHub information.""" async with ctx.typing(): - user_data = await self.fetch_data(f"{GITHUB_API_URL}/users/{quote_plus(username)}") + user_data, _ = await self.fetch_data(f"{GITHUB_API_URL}/users/{username}") # User_data will not have a message key if the user exists if "message" in user_data: @@ -274,7 +257,7 @@ class GithubInfo(commands.Cog): await ctx.send(embed=embed) return - org_data = await self.fetch_data(user_data["organizations_url"]) + org_data, _ = await self.fetch_data(user_data["organizations_url"]) orgs = [f"[{org['login']}](https://github.com/{org['login']})" for org in org_data] orgs_to_add = " | ".join(orgs) @@ -290,8 +273,8 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", - description=f"```\n{user_data['bio']}\n```\n" if user_data["bio"] else "", - colour=discord.Colour.og_blurple(), + description=f"```{user_data['bio']}```\n" if user_data["bio"] else "", + colour=discord.Colour.blurple(), url=user_data["html_url"], timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ") ) @@ -315,10 +298,7 @@ class GithubInfo(commands.Cog): ) if user_data["type"] == "User": - embed.add_field( - name="Gists", - value=f"[{gists}](https://gist.github.com/{quote_plus(username, safe='')})" - ) + embed.add_field(name="Gists", value=f"[{gists}](https://gist.github.com/{quote(username, safe='')})") embed.add_field( name=f"Organization{'s' if len(orgs)!=1 else ''}", @@ -347,7 +327,7 @@ class GithubInfo(commands.Cog): return async with ctx.typing(): - repo_data = await self.fetch_data(f"{GITHUB_API_URL}/repos/{quote(repo)}") + repo_data, _ = await self.fetch_data(f"{GITHUB_API_URL}/repos/{quote(repo)}") # There won't be a message key if this repo exists if "message" in repo_data: @@ -363,7 +343,7 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=repo_data["name"], description=repo_data["description"], - colour=discord.Colour.og_blurple(), + colour=discord.Colour.blurple(), url=repo_data["html_url"] ) -- cgit v1.2.3 From cb4114823b91056d9b552d3e75c3c8ca9e879da7 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Thu, 2 Dec 2021 11:33:57 +0000 Subject: Make dataclasses hashable, and fix kwarg spelling error --- bot/exts/utilities/githubinfo.py | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index c9a65668..ee05497a 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -11,14 +11,7 @@ from aiohttp import ClientResponse from discord.ext import commands from bot.bot import Bot -from bot.constants import ( - Categories, - Colours, - ERROR_REPLIES, - Emojis, - NEGATIVE_REPLIES, - Tokens, -) +from bot.constants import Categories, Colours, ERROR_REPLIES, Emojis, NEGATIVE_REPLIES, Tokens from bot.exts.core.extensions import invoke_help_command log = logging.getLogger(__name__) @@ -41,7 +34,7 @@ WHITELISTED_CATEGORIES = ( ) CODE_BLOCK_RE = re.compile( - r"^`([^`\n]+)`" # Inline codeblock + r"^`([^`\n]+)`" # Inline codeblock r"|```(.+?)```", # Multiline codeblock re.DOTALL | re.MULTILINE ) @@ -56,7 +49,7 @@ AUTOMATIC_REGEX = re.compile( ) -@dataclass +@dataclass(eq=True, frozen=True) class FoundIssue: """Dataclass representing an issue found by the regex.""" @@ -64,11 +57,8 @@ class FoundIssue: repository: str number: str - def __hash__(self) -> int: - return hash((self.organisation, self.repository, self.number)) - -@dataclass +@dataclass(eq=True, frozen=True) class FetchError: """Dataclass representing an error while fetching an issue.""" @@ -76,7 +66,7 @@ class FetchError: message: str -@dataclass +@dataclass(eq=True, frozen=True) class IssueState: """Dataclass representing the state of an issue.""" @@ -237,7 +227,7 @@ class GithubInfo(commands.Cog): async def fetch_data(self, url: str) -> tuple[dict[str], ClientResponse]: """Retrieve data as a dictionary and the response in a tuple.""" - async with self.bot.http_session.get(url, heades=REQUEST_HEADERS) as r: + async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as r: return await r.json(), r @github_group.command(name="user", aliases=("userinfo",)) -- cgit v1.2.3 From cdd4067ad7497b48440074494aa4de15a908f7d5 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Thu, 2 Dec 2021 11:42:04 +0000 Subject: use og_blurple in issue embed for consistency --- bot/exts/utilities/githubinfo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index ee05497a..b7dbe64d 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -264,7 +264,7 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", description=f"```{user_data['bio']}```\n" if user_data["bio"] else "", - colour=discord.Colour.blurple(), + colour=discord.Colour.og_blurple(), url=user_data["html_url"], timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ") ) @@ -333,7 +333,7 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=repo_data["name"], description=repo_data["description"], - colour=discord.Colour.blurple(), + colour=discord.Colour.og_blurple(), url=repo_data["html_url"] ) -- cgit v1.2.3 From e584697e0809e60cda899b2148a1efcff993177a Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Fri, 3 Dec 2021 18:38:42 +0000 Subject: Move logging and remove unused varibales in GitHubInfo cog --- bot/exts/utilities/githubinfo.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index b7dbe64d..009e0fad 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -11,7 +11,7 @@ from aiohttp import ClientResponse from discord.ext import commands from bot.bot import Bot -from bot.constants import Categories, Colours, ERROR_REPLIES, Emojis, NEGATIVE_REPLIES, Tokens +from bot.constants import Colours, ERROR_REPLIES, Emojis, NEGATIVE_REPLIES, Tokens from bot.exts.core.extensions import invoke_help_command log = logging.getLogger(__name__) @@ -26,12 +26,8 @@ REPOSITORY_ENDPOINT = "https://api.github.com/orgs/{org}/repos?per_page=100&type ISSUE_ENDPOINT = "https://api.github.com/repos/{user}/{repository}/issues/{number}" PR_ENDPOINT = "https://api.github.com/repos/{user}/{repository}/pulls/{number}" -if GITHUB_TOKEN := Tokens.github: - REQUEST_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}" - -WHITELISTED_CATEGORIES = ( - Categories.development, Categories.devprojects, Categories.media, Categories.staff -) +if Tokens.github: + REQUEST_HEADERS["Authorization"] = f"token {Tokens.github}" CODE_BLOCK_RE = re.compile( r"^`([^`\n]+)`" # Inline codeblock @@ -102,7 +98,6 @@ class GithubInfo(commands.Cog): """ url = ISSUE_ENDPOINT.format(user=user, repository=repository, number=number) pulls_url = PR_ENDPOINT.format(user=user, repository=repository, number=number) - log.trace(f"Querying GH issues API: {url}") json_data, r = await self.fetch_data(url) @@ -130,8 +125,6 @@ class GithubInfo(commands.Cog): # we know that a PR has been requested and a call to the pulls API endpoint is necessary # to get the desired information for the PR. else: - log.trace(f"PR provided, querying GH pulls API for additional information: {pulls_url}") - pull_data, _ = await self.fetch_data(pulls_url) if pull_data["draft"]: emoji = Emojis.pull_request_draft @@ -227,6 +220,7 @@ class GithubInfo(commands.Cog): async def fetch_data(self, url: str) -> tuple[dict[str], ClientResponse]: """Retrieve data as a dictionary and the response in a tuple.""" + log.trace(f"Querying GH issues API: {url}") async with self.bot.http_session.get(url, headers=REQUEST_HEADERS) as r: return await r.json(), r -- cgit v1.2.3 From c815a19612be9e0a28403786696964e14420204f Mon Sep 17 00:00:00 2001 From: ToxicKidz Date: Mon, 14 Feb 2022 18:26:10 -0500 Subject: fix: Add newlines in codeblock formatting --- bot/exts/utilities/githubinfo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot/exts/utilities/githubinfo.py') diff --git a/bot/exts/utilities/githubinfo.py b/bot/exts/utilities/githubinfo.py index 009e0fad..963f54e5 100644 --- a/bot/exts/utilities/githubinfo.py +++ b/bot/exts/utilities/githubinfo.py @@ -257,7 +257,7 @@ class GithubInfo(commands.Cog): embed = discord.Embed( title=f"`{user_data['login']}`'s GitHub profile info", - description=f"```{user_data['bio']}```\n" if user_data["bio"] else "", + description=f"```\n{user_data['bio']}\n```\n" if user_data["bio"] else "", colour=discord.Colour.og_blurple(), url=user_data["html_url"], timestamp=datetime.strptime(user_data["created_at"], "%Y-%m-%dT%H:%M:%SZ") -- cgit v1.2.3