From 106789319b1de06e9e8206c3a8d1dedab84496a1 Mon Sep 17 00:00:00 2001 From: salmonik Date: Mon, 23 Mar 2026 17:43:09 +0100 Subject: unify settings api into one file --- cogs/tts.py | 16 ++----------- cogs/utils/settings.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ cogs/vclogs.py | 26 +++++++-------------- main.py | 39 +++---------------------------- 4 files changed, 75 insertions(+), 68 deletions(-) create mode 100644 cogs/utils/settings.py diff --git a/cogs/tts.py b/cogs/tts.py index 46ab637..5e6945c 100644 --- a/cogs/tts.py +++ b/cogs/tts.py @@ -6,12 +6,12 @@ import os import json import discord -import aiofiles import logging import tempfile from discord.ext import commands from gtts import gTTS import asyncio +from cogs.utils.settings import get_volume logger = logging.getLogger(__name__) @@ -19,18 +19,6 @@ class TTS(commands.Cog): def __init__(self, bot): self.bot = bot - async def _load_settings(self): - """Load volume settings from settings.json""" - volume = 1.0 - try: - async with aiofiles.open('settings.json') as f: - content = await f.read() - data = json.loads(content) - volume = data.get('volume', 1.0) - except (json.JSONDecodeError, KeyError, FileNotFoundError) as e: - logger.error(f"Error loading settings: {e}") - return volume - async def _handle_file_output(self, ctx, temp_path, text): """Handle TTS file output""" try: @@ -109,7 +97,7 @@ class TTS(commands.Cog): tts.save(temp_path) # Load settings - volume = await self._load_settings() + volume = get_volume() # Handle output based on user choice if output == "file": diff --git a/cogs/utils/settings.py b/cogs/utils/settings.py new file mode 100644 index 0000000..0a1716f --- /dev/null +++ b/cogs/utils/settings.py @@ -0,0 +1,62 @@ +# This file is part of Senator Sperma +# Licensed under the GPL-3.0 License +# Copyright (C) 2026 Salmonik @ salmonik@tuta.io +# https://codeberg.org/salmonik/senator-sperma + +import json +import logging +import aiofiles +import os + +logger = logging.getLogger(__name__) + +_settings = None +settings_file = "data/settings.json" + +async def load_settings(): + global _settings + global settings_file + + default_settings = { + 'volume': 1.0, + 'baseurl': 'http://localhost:8080' + } + + try: + if os.path.exists(settings_file): + async with aiofiles.open(settings_file, 'r') as f: + content = await f.read() + if content.strip(): + _settings = json.loads(content) + logger.info("Settings loaded into memory") + else: + _settings = default_settings + await save_settings() + logger.warning("Empty settings.json, reset to defaults") + else: + _settings = default_settings + await save_settings() + logger.info("Created default settings.json") + except (json.JSONDecodeError, Exception) as e: + logger.error(f"Error loading settings: {e}") + _settings = default_settings + + return _settings + + +async def save_settings(): + if _settings: + async with aiofiles.open(settings_file, 'w') as f: + await f.write(json.dumps(_settings, indent=2)) + + +def get_settings(): + return _settings + + +def get_volume(): + return _settings.get('volume', 1.0) if _settings else 1.0 + + +def get_baseurl(): + return _settings.get('baseurl', 'http://localhost:8080').rstrip('/') if _settings else 'http://localhost:8080' \ No newline at end of file diff --git a/cogs/vclogs.py b/cogs/vclogs.py index f2efca7..0d80ae7 100644 --- a/cogs/vclogs.py +++ b/cogs/vclogs.py @@ -11,8 +11,8 @@ import asyncio import discord from discord.ext import commands from gtts import gTTS -import aiofiles from cogs.voice import get_voice_manager +from cogs.utils.settings import get_volume, save_settings logger = logging.getLogger(__name__) @@ -51,8 +51,6 @@ class VcLogs(commands.Cog): self._voice_manager = get_voice_manager(self.bot) return self._voice_manager - settings_file = 'settings.json' - @staticmethod async def handle_state_change(member, channel, state_type, is_enabled, log_channel): """Helper method to handle voice state changes""" @@ -81,13 +79,7 @@ class VcLogs(commands.Cog): tts.save(tts_file) voice_client = await voice_mgr.get_voice_client(channel.guild) - volume = 1.0 - - if os.path.exists(VcLogs.settings_file): - async with aiofiles.open(VcLogs.settings_file) as f: - content = await f.read() - data = json.loads(content) - volume = data.get('volume', 1.0) + volume = get_volume() if voice_client is None: voice_client = await voice_mgr.join_channel(channel) @@ -107,14 +99,12 @@ class VcLogs(commands.Cog): name="log_volume" ) async def volume(self, ctx: discord.ApplicationContext, volume: int): - try: - async with aiofiles.open(VcLogs.settings_file, 'w') as f: - json.dump({"volume": volume}, f, indent=4) - await ctx.followup.send(f"Volume has been set to: {volume}") - logger.info(f"Volume changed to: {volume}") - except Exception as e: - await ctx.respond(e, ephemeral=True) - logger.error(f"Error in volume command: {e}", exc_info=True) + from cogs.utils.settings import get_settings + settings = get_settings() + settings['volume'] = volume + await save_settings() + await ctx.followup.send(f"Volume has been set to: {volume}") + logger.info(f"Volume changed to: {volume}") @commands.Cog.listener() async def on_voice_state_update(self, member, before, after): diff --git a/main.py b/main.py index 25b7b33..67db667 100644 --- a/main.py +++ b/main.py @@ -6,14 +6,13 @@ import logging import os import sys -import json import asyncio -import aiofiles import discord from discord.ext import commands from dotenv import load_dotenv from cogs.voice import get_voice_manager +from cogs.utils import settings # Configure logging logging.basicConfig( @@ -32,49 +31,16 @@ asyncio.set_event_loop(loop) intents = discord.Intents.all() bot = commands.Bot(intents=intents, loop=loop) -settings = "settings.json" @bot.event async def on_ready(): logger.info("ŁUKASZ SPERMA AKTYWACJA") - # send the message to channel ID channel = bot.get_channel(1081667823799111804) await channel.send("ŁUKASZ SPERMA AKTYWACJA") - # Create settings.json if it doesn't exist - if not os.path.exists(settings): - default_settings = { - 'volume': 1.0, - 'file_paths': ['audio', 'music', 'sounds', 'videos', 'images'], - 'baseurl': 'http://localhost:8080' - } - async with aiofiles.open(settings, 'w') as f: - await f.write(json.dumps(default_settings, indent=2)) - logger.info("settings.json created") - - # Validate and fix settings.json if it exists - if os.path.exists(settings): - try: - async with aiofiles.open(settings, 'r') as f: - content = await f.read() - if not content.strip(): - raise json.JSONDecodeError("Empty file", "", 0) - data = json.loads(content) - assert 'volume' in data and isinstance(data['volume'], float) - assert 'file_paths' in data and isinstance(data['file_paths'], list) - assert 'baseurl' in data and isinstance(data['baseurl'], str) - except (json.JSONDecodeError, AssertionError) as error: - logger.error(f"Error loading settings.json: {error}") - default_settings = { - 'volume': 1.0, - 'file_paths': ['audio', 'music', 'sounds', 'videos', 'images'], - 'baseurl': 'http://localhost:8080' - } - async with aiofiles.open(settings, 'w') as f: - await f.write(json.dumps(default_settings, indent=2)) - logger.info("settings.json recreated") + await settings.load_settings() @@ -95,6 +61,7 @@ if __name__ == "__main__": 'cogs.music.stop', 'cogs.music.join', 'cogs.search', + 'cogs.trigger', ] try: -- cgit v1.2.3