Skip to content

Commit 9edbd5f

Browse files
committed
refactor(config): update configuration access across multiple modules
- Refactored the import path for CONFIG to streamline access in various modules. - Adjusted configuration access patterns to reflect the new structure, including updates to Eval, Git, Mail, Levels, and other service files. - Enhanced error handling and logging for better diagnostics related to configuration values. - Ensured consistency in accessing external service configurations across the codebase.
1 parent b03a4f0 commit 9edbd5f

File tree

15 files changed

+63
-59
lines changed

15 files changed

+63
-59
lines changed

src/tux/modules/admin/eval.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from tux.core import checks
88
from tux.core.base_cog import BaseCog
99
from tux.core.types import Tux
10-
from tux.shared.config.settings import CONFIG
10+
from tux.shared.config import CONFIG
1111
from tux.ui.embeds import EmbedCreator
1212

1313

@@ -71,7 +71,7 @@ async def eval(self, ctx: commands.Context[Tux], *, expression: str) -> None:
7171
return
7272

7373
if ctx.author.id not in self.bot.owner_ids:
74-
if not CONFIG.ALLOW_SYSADMINS_EVAL and ctx.author.id in CONFIG.SYSADMIN_IDS:
74+
if not CONFIG.ALLOW_SYSADMINS_EVAL and ctx.author.id in CONFIG.USER_IDS.SYSADMINS:
7575
logger.warning(
7676
f"{ctx.author} tried to run eval but is not the bot owner. (User ID: {ctx.author.id})",
7777
)

src/tux/modules/admin/git.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from tux.core.base_cog import BaseCog
66
from tux.core.types import Tux
77
from tux.services.wrappers.github import GithubService
8-
from tux.shared.config.settings import CONFIG
8+
from tux.shared.config import CONFIG
99
from tux.ui.buttons import GithubButton
1010
from tux.ui.embeds import EmbedCreator
1111

@@ -14,7 +14,7 @@ class Git(BaseCog):
1414
def __init__(self, bot: Tux) -> None:
1515
super().__init__(bot)
1616
self.github = GithubService()
17-
self.repo_url = CONFIG.GITHUB_REPO_URL
17+
self.repo_url = CONFIG.EXTERNAL_SERVICES.GITHUB_REPO_URL
1818
# Usage is auto-generated by BaseCog
1919

2020
@commands.hybrid_group(

src/tux/modules/admin/mail.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@
88
from tux.core import checks
99
from tux.core.base_cog import BaseCog
1010
from tux.core.types import Tux
11-
from tux.shared.config.settings import CONFIG
11+
from tux.shared.config import CONFIG
1212

1313
MailboxData = dict[str, str | list[str]]
1414

1515

1616
class Mail(BaseCog):
1717
def __init__(self, bot: Tux) -> None:
1818
super().__init__(bot)
19-
self.api_url = CONFIG.MAILCOW_API_URL
19+
self.api_url = CONFIG.EXTERNAL_SERVICES.MAILCOW_API_URL
2020
self.headers = {
2121
"Content-Type": "application/json",
2222
"Accept": "application/json",
23-
"X-API-Key": CONFIG.MAILCOW_API_KEY,
24-
"Authorization": f"Bearer {CONFIG.MAILCOW_API_KEY}",
23+
"X-API-Key": CONFIG.EXTERNAL_SERVICES.MAILCOW_API_KEY,
24+
"Authorization": f"Bearer {CONFIG.EXTERNAL_SERVICES.MAILCOW_API_KEY}",
2525
}
2626
self.default_options: dict[str, str | list[str]] = {
2727
"active": "1",

src/tux/modules/fun/fact.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import random
22
import tomllib
3+
from pathlib import Path
34
from typing import Any
45

56
import discord
@@ -10,10 +11,12 @@
1011

1112
from tux.core.base_cog import BaseCog
1213
from tux.core.types import Tux
13-
from tux.shared.config.settings import workspace_root
1414
from tux.shared.substitutions import handle_substitution
1515
from tux.ui.embeds import EmbedCreator
1616

17+
# Define workspace root relative to the project root
18+
workspace_root = Path(__file__).parent.parent.parent.parent.parent
19+
1720

1821
class Fact(BaseCog):
1922
def __init__(self, bot: Tux) -> None:

src/tux/modules/guild/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from tux.core.base_cog import BaseCog
88
from tux.core.types import Tux
9-
from tux.shared.config.settings import CONFIG
9+
from tux.shared.config import CONFIG
1010
from tux.ui.embeds import EmbedCreator, EmbedType
1111
from tux.ui.views.config import ConfigSetChannels, ConfigSetPrivateLogs, ConfigSetPublicLogs
1212

@@ -387,7 +387,7 @@ async def config_clear_prefix(
387387
user_display_avatar=interaction.user.display_avatar.url,
388388
embed_type=EmbedCreator.SUCCESS,
389389
title="Guild Config",
390-
description=f"The prefix was reset to `{CONFIG.DEFAULT_PREFIX}`",
390+
description=f"The prefix was reset to `{CONFIG.BOT_INFO.PREFIX}`",
391391
),
392392
)
393393

src/tux/modules/levels/level.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from tux.core.base_cog import BaseCog
55
from tux.core.types import Tux
66
from tux.modules.services.levels import LevelsService
7-
from tux.shared.config.settings import CONFIG
7+
from tux.shared.config import CONFIG
88
from tux.ui.embeds import EmbedCreator, EmbedType
99

1010

@@ -52,7 +52,7 @@ async def level(self, ctx: commands.Context[Tux], member: discord.User | discord
5252
level_display = level
5353
xp_display = f"{round(xp)}"
5454

55-
if CONFIG.SHOW_XP_PROGRESS:
55+
if CONFIG.XP_CONFIG.SHOW_XP_PROGRESS:
5656
xp_progress: int
5757
xp_required: int
5858
xp_progress, xp_required = self.levels_service.get_level_progress(xp, level)

src/tux/modules/services/gif_limiter.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from tux.core.base_cog import BaseCog
99
from tux.core.types import Tux
10-
from tux.shared.config.settings import CONFIG
10+
from tux.shared.config import CONFIG
1111

1212

1313
class GifLimiter(BaseCog):
@@ -21,15 +21,15 @@ def __init__(self, bot: Tux) -> None:
2121
super().__init__(bot)
2222

2323
# Max age for a GIF to be considered a recent post
24-
self.recent_gif_age: int = CONFIG.RECENT_GIF_AGE
24+
self.recent_gif_age: int = CONFIG.GIF_LIMITER.RECENT_GIF_AGE
2525

2626
# Max number of GIFs sent recently in a channel
27-
self.channelwide_gif_limits: dict[int, int] = CONFIG.GIF_LIMITS_CHANNEL
27+
self.channelwide_gif_limits: dict[int, int] = CONFIG.GIF_LIMITER.GIF_LIMITS_CHANNEL
2828
# Max number of GIFs sent recently by a user to be able to post one in specified channels
29-
self.user_gif_limits: dict[int, int] = CONFIG.GIF_LIMITS
29+
self.user_gif_limits: dict[int, int] = CONFIG.GIF_LIMITER.GIF_LIMITS_USER
3030

3131
# list of channels in which not to count GIFs
32-
self.gif_limit_exclude: list[int] = CONFIG.GIF_LIMIT_EXCLUDE
32+
self.gif_limit_exclude: list[int] = CONFIG.GIF_LIMITER.GIF_LIMIT_EXCLUDE
3333

3434
# Timestamps for recently-sent GIFs for the server, and channels
3535

src/tux/modules/services/influxdblogger.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from tux.core.base_cog import BaseCog
1010
from tux.core.types import Tux
11-
from tux.shared.config.settings import CONFIG
11+
from tux.shared.config import CONFIG
1212

1313

1414
class InfluxLogger(BaseCog):
@@ -31,9 +31,9 @@ def init_influx(self) -> bool:
3131
bool
3232
True if initialization was successful, False otherwise
3333
"""
34-
influx_token: str = CONFIG.INFLUXDB_TOKEN
35-
influx_url: str = CONFIG.INFLUXDB_URL
36-
self.influx_org = CONFIG.INFLUXDB_ORG
34+
influx_token: str = CONFIG.EXTERNAL_SERVICES.INFLUXDB_TOKEN
35+
influx_url: str = CONFIG.EXTERNAL_SERVICES.INFLUXDB_URL
36+
self.influx_org = CONFIG.EXTERNAL_SERVICES.INFLUXDB_ORG
3737

3838
if (influx_token != "") and (influx_url != "") and (self.influx_org != ""):
3939
write_client = InfluxDBClient(url=influx_url, token=influx_token, org=self.influx_org)

src/tux/modules/services/levels.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,25 @@
88
from tux.core.app import get_prefix
99
from tux.core.base_cog import BaseCog
1010
from tux.core.types import Tux
11-
from tux.shared.config.settings import CONFIG
11+
from tux.shared.config import CONFIG
1212
from tux.ui.embeds import EmbedCreator
1313

1414

1515
class LevelsService(BaseCog):
1616
def __init__(self, bot: Tux) -> None:
1717
super().__init__(bot)
18-
self.xp_cooldown = CONFIG.XP_COOLDOWN
19-
self.levels_exponent = CONFIG.LEVELS_EXPONENT
20-
self.xp_roles = {role["level"]: role["role_id"] for role in CONFIG.XP_ROLES}
21-
self.xp_multipliers = {role["role_id"]: role["multiplier"] for role in CONFIG.XP_MULTIPLIERS}
22-
self.max_level = max(item["level"] for item in CONFIG.XP_ROLES)
23-
self.enable_xp_cap = CONFIG.ENABLE_XP_CAP
18+
19+
# Check if XP roles are configured
20+
if not CONFIG.XP_CONFIG.XP_ROLES:
21+
msg = "XP_ROLES configuration is empty. Please configure XP roles in your .env file."
22+
raise ValueError(msg)
23+
24+
self.xp_cooldown = CONFIG.XP_CONFIG.XP_COOLDOWN
25+
self.levels_exponent = CONFIG.XP_CONFIG.LEVELS_EXPONENT
26+
self.xp_roles = {role["level"]: role["role_id"] for role in CONFIG.XP_CONFIG.XP_ROLES}
27+
self.xp_multipliers = {role["role_id"]: role["multiplier"] for role in CONFIG.XP_CONFIG.XP_MULTIPLIERS}
28+
self.max_level = max(item["level"] for item in CONFIG.XP_CONFIG.XP_ROLES)
29+
self.enable_xp_cap = CONFIG.XP_CONFIG.ENABLE_XP_CAP
2430

2531
@commands.Cog.listener("on_message")
2632
async def xp_listener(self, message: discord.Message) -> None:
@@ -32,7 +38,7 @@ async def xp_listener(self, message: discord.Message) -> None:
3238
message : discord.Message
3339
The message object.
3440
"""
35-
if message.author.bot or message.guild is None or message.channel.id in CONFIG.XP_BLACKLIST_CHANNELS:
41+
if message.author.bot or message.guild is None or message.channel.id in CONFIG.XP_CONFIG.XP_BLACKLIST_CHANNELS:
3642
return
3743

3844
prefixes = await get_prefix(self.bot, message)

src/tux/modules/services/status_roles.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,23 @@
66
from loguru import logger
77

88
from tux.core.base_cog import BaseCog
9-
from tux.shared.config.settings import CONFIG
9+
from tux.shared.config import CONFIG
1010

1111

1212
class StatusRoles(BaseCog):
1313
"""Assign roles to users based on their status."""
1414

1515
def __init__(self, bot: commands.Bot):
1616
self.bot = bot
17-
self.status_roles = CONFIG.STATUS_ROLES
1817
self._unload_task = None # Store task reference here
1918

20-
# Check if config exists and is valid
21-
if not self.status_roles:
22-
logger.warning("No status roles configurations found. Unloading StatusRoles cog.")
19+
# Check if mappings exist and are valid
20+
if not CONFIG.STATUS_ROLES.MAPPINGS:
21+
logger.warning("No status role mappings found. Unloading StatusRoles cog.")
2322
# Store the task reference
2423
self._unload_task = asyncio.create_task(self._unload_self())
2524
else:
26-
logger.info(f"StatusRoles cog initialized with {len(self.status_roles)} role configurations")
25+
logger.info(f"StatusRoles cog initialized with {len(CONFIG.STATUS_ROLES.MAPPINGS)} mappings")
2726

2827
async def _unload_self(self):
2928
"""Unload this cog if configuration is missing."""
@@ -86,17 +85,17 @@ async def check_and_update_roles(self, member: discord.Member):
8685
if status_text is None:
8786
status_text = "" # Use empty string for regex matching if no status
8887

89-
for config in self.status_roles:
90-
# Skip if the config is for a different server
91-
if int(config.get("server_id", 0)) != member.guild.id:
88+
for mapping in CONFIG.STATUS_ROLES.MAPPINGS:
89+
# Skip if the mapping is for a different server
90+
if int(mapping.get("server_id", 0)) != member.guild.id:
9291
continue
9392

94-
role_id = int(config.get("role_id", 0))
95-
pattern = str(config.get("status_regex", ".*"))
93+
role_id = int(mapping.get("role_id", 0))
94+
pattern = str(mapping.get("status_regex", ".*"))
9695

9796
role = member.guild.get_role(role_id)
9897
if not role:
99-
logger.warning(f"Role {role_id} configured in STATUS_ROLES not found in guild {member.guild.name}")
98+
logger.warning(f"Role {role_id} configured in status roles not found in guild {member.guild.name}")
10099
continue
101100

102101
try:

0 commit comments

Comments
 (0)