Skip to content

Commit

Permalink
🐛 Fix updates command & formatting & comments
Browse files Browse the repository at this point in the history
Fixes a bug where the updates command wouldn't actually request the api, rather the HTML page.
Applies black formatting to the file.
Fixes the files comments and docstrings so they are actually relevant, I was probably lazy when I wrote them.
  • Loading branch information
zachlagden committed Aug 30, 2024
1 parent c08523e commit 482045a
Showing 1 changed file with 106 additions and 67 deletions.
173 changes: 106 additions & 67 deletions cogs/rickbot/cmds_botinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
(c) 2024 Zachariah Michael Lagden (All Rights Reserved)
You may not use, copy, distribute, modify, or sell this code without the express permission of the author.
This cog counts the number of times a user has said the n-word in the server and provides a command to check the records,
as well as a leaderboard command that shows the top 10 users with the most n-word records.
This cog provides commands to get information about the bot, this is a part of the RickBot default cog set.
"""

# Python standard library
Expand All @@ -22,25 +21,56 @@
from config import CONFIG


# Custom Exceptions
class InvalidGitHubURL(Exception):
def __init__(self, message="Invalid GitHub URL"):
self.message = message
super().__init__(self.message)


# Helper functions
def convert_repo_url_to_api(url: str) -> str:
"""
Converts a GitHub repository URL into the corresponding GitHub API URL to retrieve commits.
Args:
url (str): The GitHub repository URL.
Returns:
str: The corresponding GitHub API URL for commits.
"""
# Split the URL by slashes
parts = url.rstrip("/").split("/")

if len(parts) < 2:
raise ValueError("Invalid GitHub URL")

# Extract the owner and repository name
owner = parts[-2]
repo = parts[-1]

# Construct the API URL
api_url = f"https://api.github.com/repos/{owner}/{repo}/commits"

return api_url


# Cog
class RickBot_BotInfoCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot

self.GITHUB_API = (
CONFIG["repo"]["url"]
if "repo" in CONFIG
and "url" in CONFIG["repo"]
and CONFIG["repo"]["url"] != ""
else None
)
self.GITHUB_REPO = CONFIG["repo"]["url"]

def botownercheck(ctx):
return ctx.author.id in CONFIG["devs"]
if self.GITHUB_REPO is not None:
self.GITHUB_API = convert_repo_url_to_api(self.GITHUB_REPO)
else:
self.GITHUB_API = None

@commands.command(name="updates")
async def _updates(self, ctx):
"""
Check github for the latest commits, provides the last 5 along with other relevant information.
Check GitHub for the latest commits, provides the last 5 along with other relevant information.
"""

if self.GITHUB_API is None:
Expand All @@ -53,76 +83,85 @@ async def _updates(self, ctx):
await ctx.message.reply(embed=embed, mention_author=False)
return

query = requests.get(self.GITHUB_API)
try:
response = requests.get(self.GITHUB_API)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()

if not isinstance(data, list):
raise ValueError("Unexpected data format received from GitHub API")

# Sort the commits by date (newest first)
sorted_commits = sorted(
data,
key=lambda x: datetime.strptime(
x["commit"]["author"]["date"], "%Y-%m-%dT%H:%M:%SZ"
),
reverse=True,
)

# Extract required information
commit_list = []
for commit in sorted_commits[:5]: # Only process the latest 5 commits
author_data = commit.get("author")
commit_info = {
"sha": commit["sha"],
"id": commit["sha"][:7],
"date": commit["commit"]["author"]["date"],
"author": commit["commit"]["author"]["name"],
"author_html_url": (
author_data["html_url"] if author_data else "N/A"
),
"email": commit["commit"]["author"]["email"],
"short_message": commit["commit"]["message"].split("\n")[0],
"full_message": commit["commit"]["message"],
"url": commit["url"],
"html_url": commit["html_url"],
}
commit_list.append(commit_info)

# Create the embed
desc = "Here are the latest updates to the bot:\n\n"

for commit in commit_list:
date = datetime.strptime(commit["date"], "%Y-%m-%dT%H:%M:%SZ")

author_link = (
f"[{commit['author'].split(' ')[0]}]({commit['author_html_url']})"
if commit["author_html_url"] != "N/A"
else commit["author"].split(" ")[0]
)
desc += f"**[`{commit['id']}`]({commit['html_url']})** - {format_timestamp(date, TimestampType.RELATIVE)} by {author_link}\n{commit['short_message']}\n\n"

embed = discord.Embed(
title="Latest Updates",
description=desc,
color=MAIN_EMBED_COLOR,
)

embed.set_footer(text="RickBot is a project by lagden.dev.")

await ctx.message.reply(embed=embed, mention_author=False)

if query.status_code != 200:
except requests.exceptions.RequestException as e:
# Handle specific request errors like timeouts, connection errors, etc.
embed = discord.Embed(
title="Error",
description="I'm sorry, there was an error fetching the latest commits. Please try again later.\nIf the problem persists, please contact the bot owner.",
color=ERROR_EMBED_COLOR,
)

await ctx.message.reply(embed=embed, mention_author=False)
return

data = query.json()

if not isinstance(data, list):
except ValueError as e:
# Handle JSON decoding errors or any other data format issues
embed = discord.Embed(
title="Error",
description="I'm sorry, there was an error fetching the latest commits. Please try again later.\nIf the problem persists, please contact the bot owner.",
description=str(e),
color=ERROR_EMBED_COLOR,
)

await ctx.message.reply(embed=embed, mention_author=False)
return

# Sort the commits by date (newest first)
sorted_commits = sorted(
data,
key=lambda x: datetime.strptime(
x["commit"]["author"]["date"], "%Y-%m-%dT%H:%M:%SZ"
),
reverse=True,
)

# Extract required information
commit_list = []
for commit in sorted_commits:
commit_info = {
"sha": commit["sha"],
"id": commit["sha"][0:7],
"date": commit["commit"]["author"]["date"],
"author": commit["commit"]["author"]["name"],
"author_html_url": commit["author"]["html_url"],
"email": commit["commit"]["author"]["email"],
"short_message": commit["commit"]["message"].split("\n")[0],
"full_message": commit["commit"]["message"],
"url": commit["url"],
"html_url": commit["html_url"],
}
commit_list.append(commit_info)

# Create the embed

desc = "Here are the latest updates to the bot:\n\n"

for commit in commit_list[:5]:
date = datetime.strptime(commit["date"], "%Y-%m-%dT%H:%M:%SZ")

desc += f"**[`{commit['id']}`]({commit['html_url']})** - {format_timestamp(date, TimestampType.RELATIVE)} by [{commit['author'].split(' ')[0]}]({commit['author_html_url']})\n{commit['short_message']}\n\n"

embed = discord.Embed(
title="Latest Updates",
description=desc,
color=MAIN_EMBED_COLOR,
)

embed.set_footer(
text="Better Hood Bot is a project by Zach. All rights reserved."
)

await ctx.message.reply(embed=embed, mention_author=False)


async def setup(bot: commands.Bot):
Expand Down

0 comments on commit 482045a

Please sign in to comment.