Skip to content

Commit

Permalink
♻️ Refactor to match lagden.dev comment style
Browse files Browse the repository at this point in the history
  • Loading branch information
zachlagden committed Sep 2, 2024
1 parent 3b2238e commit e2c8b7a
Show file tree
Hide file tree
Showing 15 changed files with 892 additions and 334 deletions.
70 changes: 59 additions & 11 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,84 @@
"""
(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.
(c) 2024 Lagden Development (All Rights Reserved)
Licensed for non-commercial use with attribution required; provided 'as is' without warranty.
See https://github.com/Lagden-Development/.github/blob/main/LICENSE for more information.
Runs the bot.
This script is responsible for running the bot. It sets up the necessary environment, handles signals for
graceful shutdowns, and initiates the bot's main loop. The bot's core functionality is encapsulated in the
RickBot class, which is imported and used here.
"""

import asyncio
import signal
import os
# Import the required modules

from rickbot.main import RickBot
# Python Standard Library
# -----------------------
from typing import (
NoReturn,
) # The build in typing module, used for type hints and annotations.
import asyncio # For handling asynchronous operations, which are crucial for the bot's functionality.
import signal # To handle signals like SIGTERM and SIGINT, allowing for graceful shutdowns.
import os # Provides a way to interact with the operating system, specifically for handling file paths.

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
# Internal Modules
# ------------------------
from rickbot.main import (
RickBot,
) # Importing the RickBot class, which contains the core logic and behavior of the bot.


# Adjust the current working directory
# ------------------------------------
# This ensures that the script's directory is the working directory, no matter where it's run from.
# It's a safeguard to ensure that all relative paths within the bot's operations are correctly resolved.
abspath = os.path.abspath(__file__) # Get the absolute path of this file.
dname = os.path.dirname(abspath) # Determine the directory name of this file.
os.chdir(dname) # Change the current working directory to this file's directory.

# Initialize the bot
# ------------------
# Create an instance of RickBot, which will be used to run and manage the bot's operations.
# This instance encapsulates all the methods and properties necessary for the bot to function.
bot = RickBot()


async def main():
async def main() -> NoReturn:
"""
The main function responsible for starting and managing the bot.
This function sets up signal handlers for graceful shutdowns and then starts the bot.
The signal handlers listen for SIGTERM and SIGINT, which are signals for termination
and interruption (e.g., Ctrl+C), respectively. When such a signal is received, the bot's
shutdown procedure is initiated.
Returns:
NoReturn: This function does not return anything.
"""
# Set up signal handlers for graceful shutdown
# --------------------------------------------
# This loop iterates over the signals SIGTERM and SIGINT, adding a handler for each.
# The handler triggers the bot's shutdown method, allowing for a clean exit.
for s in [signal.SIGTERM, signal.SIGINT]:
asyncio.get_event_loop().add_signal_handler(
s, lambda s=s: asyncio.create_task(bot.shutdown(s))
)

# Start the bot
# -------------
# This line initiates the bot's main functionality, entering its event loop until shutdown is triggered.
await bot.start_bot()


# Entry point for the script
# --------------------------
# This block ensures that the script can be run as a standalone program.
# It tries to run the main asynchronous function, handling common exit scenarios gracefully.
if __name__ == "__main__":
try:
# Run the main asynchronous function
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
# Handle common exit scenarios like keyboard interruption (Ctrl+C) or system exit.
print("Bot shutdown requested, exiting...")
except Exception as e:
# Catch any other exceptions that might occur and log them.
print(f"Unhandled exception: {e}")
87 changes: 65 additions & 22 deletions cogs/rickbot/cmds_botinfo.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
"""
(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.
(c) 2024 Lagden Development (All Rights Reserved)
Licensed for non-commercial use with attribution required; provided 'as is' without warranty.
See https://github.com/Lagden-Development/.github/blob/main/LICENSE for more information.
This cog provides commands to get information about the bot, this is a part of the RickBot default cog set.
This cog provides commands to get information about the bot, and it is part of the RickBot default cog set.
"""

# Python standard library
from datetime import datetime

# Third-party libraries
from discord_timestamps import format_timestamp, TimestampType
from discord.ext import commands
import discord
import requests

# Helper functions
from helpers.colors import MAIN_EMBED_COLOR, ERROR_EMBED_COLOR
# Python Standard Library
# ------------------------
from datetime import (
datetime,
) # Used for parsing and formatting date and time information

# Third Party Libraries
# ---------------------
from discord_timestamps import (
format_timestamp,
TimestampType,
) # Helps format timestamps for Discord messages
from discord.ext import commands # Used for defining Discord bot commands and cogs
import discord # Core library for interacting with Discord's API
import requests # Handles HTTP requests, used here for interacting with the GitHub API

# Internal Modules
# ----------------
from helpers.colors import (
MAIN_EMBED_COLOR,
ERROR_EMBED_COLOR,
) # Predefined color constants for Discord embeds

# Config
from config import CONFIG
# ------
from config import CONFIG # Imports the bot's configuration settings


# Custom Exceptions
class InvalidGitHubURL(Exception):
def __init__(self, message="Invalid GitHub URL"):
"""
Exception raised when an invalid GitHub URL is encountered.
Attributes:
message (str): The error message explaining the issue.
"""

def __init__(self, message: str = "Invalid GitHub URL"):
self.message = message
super().__init__(self.message)

Expand All @@ -38,6 +58,9 @@ def convert_repo_url_to_api(url: str) -> str:
Returns:
str: The corresponding GitHub API URL for commits.
Raises:
ValueError: If the provided URL is invalid.
"""
# Split the URL by slashes
parts = url.rstrip("/").split("/")
Expand All @@ -57,7 +80,16 @@ def convert_repo_url_to_api(url: str) -> str:

# Cog
class RickBot_BotInfoCommands(commands.Cog):
def __init__(self, bot):
"""
Cog for RickBot that provides commands to retrieve information about the bot, including recent GitHub updates.
Attributes:
bot (commands.Bot): The instance of the bot.
GITHUB_REPO (str): The GitHub repository URL configured for the bot.
GITHUB_API (str): The GitHub API URL derived from the repository URL.
"""

def __init__(self, bot: commands.Bot):
self.bot = bot

self.GITHUB_REPO = CONFIG["REPO"]["url"]
Expand All @@ -68,12 +100,14 @@ def __init__(self, bot):
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.
async def _updates(self, ctx: commands.Context):
"""
Check GitHub for the latest commits and provide details about the last 5 commits.
if self.GITHUB_API is None:
Args:
ctx (commands.Context): The command context.
"""
if self.GITHUB_API in [None, ""]:
embed = discord.Embed(
title="Sorry!",
description="This command is disabled.",
Expand Down Expand Up @@ -164,9 +198,12 @@ async def _updates(self, ctx):
await ctx.message.reply(embed=embed, mention_author=False)

@commands.command(name="ping")
async def _ping(self, ctx):
async def _ping(self, ctx: commands.Context):
"""
Check the bot's latency.
Args:
ctx (commands.Context): The command context.
"""
embed = discord.Embed(
title="Pong!",
Expand All @@ -178,4 +215,10 @@ async def _ping(self, ctx):


async def setup(bot: commands.Bot):
"""
Setup function to add this cog to the bot.
Args:
bot (commands.Bot): The instance of the bot.
"""
await bot.add_cog(RickBot_BotInfoCommands(bot))
Loading

0 comments on commit e2c8b7a

Please sign in to comment.