Skip to content

Commit

Permalink
Refactor code to improve readability and maintainability
Browse files Browse the repository at this point in the history
Refactor and optimize code to adhere to DRY, KISS, YAGNI, SOLID, and SoC principles.

* **cogs/autoreact_cog.py**
  - Remove `react_stop` command and related code.
  - Update `react` command to handle stopping reactions.

* **cogs/help_cog.py**
  - Refactor `help_command` function to improve readability.
  - Add `send_all_categories` and `send_category_commands` helper methods.

* **utils/database.py**
  - Consolidate database connection functions into a single `connect_database` function.
  - Update `determine_database` to use the new `connect_database` function.

* **utils/command_handler.py**
  - Optimize `load_cogs` method to avoid repetitive code.

* **cogs/reactstop_cog.py**
  - Delete file as its functionality is now handled in `cogs/autoreact_cog.py`.
  • Loading branch information
outmaneuver committed Oct 27, 2024
1 parent 3b72bfc commit aab9a04
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 79 deletions.
21 changes: 11 additions & 10 deletions cogs/autoreact_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,18 @@ async def react(self, ctx, user_ids: commands.Greedy[int], *emojis):
for user_id in user_ids:
if user_id not in self.user_reactions:
self.user_reactions[user_id] = set()
self.user_reactions[user_id].update(emojis)

await ctx.send(f"Auto-react enabled for users: {', '.join(map(str, user_ids))} with emojis: {', '.join(emojis)}")

@commands.command(name='reactstop')
async def react_stop(self, ctx, user_id: int):
if user_id in self.user_reactions:
del self.user_reactions[user_id]
await ctx.send(f"Auto-react disabled for user: {user_id}")
if emojis:
self.user_reactions[user_id].update(emojis)
else:
if user_id in self.user_reactions:
del self.user_reactions[user_id]
await ctx.send(f"Auto-react disabled for user: {user_id}")
return

if emojis:
await ctx.send(f"Auto-react enabled for users: {', '.join(map(str, user_ids))} with emojis: {', '.join(emojis)}")
else:
await ctx.send(f"No auto-react found for user: {user_id}")
await ctx.send(f"No emojis provided. Auto-react disabled for users: {', '.join(map(str, user_ids))}")

@commands.command(name='reactlist')
async def react_list(self, ctx):
Expand Down
32 changes: 18 additions & 14 deletions cogs/help_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,27 @@ async def help_command(self, ctx, *input):
return

if not input:
# No input, show all categories and commands
help_message = "Help\nUse `{prefix}help <category>` to get more information on a category.\n\nCategories:\n"
for cog in self.bot.cogs:
help_message += f'`{cog}` {self.bot.cogs[cog].__doc__}\n'
await ctx.send(f"```{help_message}```")
await self.send_all_categories(ctx, prefix)
elif len(input) == 1:
# One input, show commands in the category
cog = self.bot.get_cog(input[0])
if cog:
help_message = f"{input[0]} - Commands\n{cog.__doc__}\n\n"
for command in cog.get_commands():
help_message += f"`{prefix}{command.name}`: {command.help}\n"
await ctx.send(f"```{help_message}```")
else:
await ctx.send(f"Category `{input[0]}` not found.")
await self.send_category_commands(ctx, input[0], prefix)
else:
await ctx.send("Invalid input. Use `!help` to see all categories.")

async def send_all_categories(self, ctx, prefix):
help_message = "Help\nUse `{prefix}help <category>` to get more information on a category.\n\nCategories:\n"
for cog in self.bot.cogs:
help_message += f'`{cog}` {self.bot.cogs[cog].__doc__}\n'
await ctx.send(f"```{help_message}```")

async def send_category_commands(self, ctx, category, prefix):
cog = self.bot.get_cog(category)
if cog:
help_message = f"{category} - Commands\n{cog.__doc__}\n\n"
for command in cog.get_commands():
help_message += f"`{prefix}{command.name}`: {command.help}\n"
await ctx.send(f"```{help_message}```")
else:
await ctx.send(f"Category `{category}` not found.")

def setup(bot):
bot.add_cog(HelpCog(bot))
21 changes: 0 additions & 21 deletions cogs/reactstop_cog.py

This file was deleted.

9 changes: 4 additions & 5 deletions utils/command_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ def __init__(self):
self.rate_limiter = RateLimiter()

def load_cogs(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
cog_name = filename[:-3]
cog_module = importlib.import_module(f'cogs.{cog_name}')
self.add_cog(cog_module.setup(self))
cog_files = [f[:-3] for f in os.listdir('./cogs') if f.endswith('.py')]
for cog_name in cog_files:
cog_module = importlib.import_module(f'cogs.{cog_name}')
self.add_cog(cog_module.setup(self))

async def on_ready(self):
print(f'Logged in as {self.user}')
Expand Down
40 changes: 11 additions & 29 deletions utils/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,53 +7,35 @@

load_dotenv()

def connect_sqlite():
def connect_database(db_type):
try:
if os.getenv("LOCAL_DB_PATH"):
if db_type == "sqlite" and os.getenv("LOCAL_DB_PATH"):
return sqlite3.connect(os.getenv("LOCAL_DB_PATH"))
except sqlite3.Error as e:
print(f"SQLite error: {e}")
return None

def connect_mongodb():
try:
if os.getenv("MONGODB_URI"):
elif db_type == "mongodb" and os.getenv("MONGODB_URI"):
return pymongo.MongoClient(os.getenv("MONGODB_URI"))
except pymongo.errors.PyMongoError as e:
print(f"MongoDB error: {e}")
return None

def connect_mysql():
try:
if os.getenv("MYSQL_HOST"):
elif db_type == "mysql" and os.getenv("MYSQL_HOST"):
return mysql.connector.connect(
host=os.getenv("MYSQL_HOST"),
user=os.getenv("MYSQL_USER"),
password=os.getenv("MYSQL_PASSWORD"),
database=os.getenv("MYSQL_DATABASE")
)
except mysql.connector.Error as e:
print(f"MySQL error: {e}")
return None

def connect_redis():
try:
if os.getenv("REDIS_HOST"):
elif db_type == "redis" and os.getenv("REDIS_HOST"):
return redis.StrictRedis(
host=os.getenv("REDIS_HOST"),
port=os.getenv("REDIS_PORT"),
password=os.getenv("REDIS_PASSWORD"),
decode_responses=True
)
except redis.RedisError as e:
print(f"Redis error: {e}")
except (sqlite3.Error, pymongo.errors.PyMongoError, mysql.connector.Error, redis.RedisError) as e:
print(f"{db_type.capitalize()} error: {e}")
return None

def determine_database():
local_db_conn = connect_sqlite()
mongo_client = connect_mongodb()
mysql_conn = connect_mysql()
redis_client = connect_redis()
local_db_conn = connect_database("sqlite")
mongo_client = connect_database("mongodb")
mysql_conn = connect_database("mysql")
redis_client = connect_database("redis")

if not any([local_db_conn, mongo_client, mysql_conn, redis_client]):
print("No external databases configured. Setting up a local database.")
Expand Down

0 comments on commit aab9a04

Please sign in to comment.