From 2f33d840f36f037e4a9bafeb951343cfc72e8737 Mon Sep 17 00:00:00 2001 From: official-Cromatin Date: Sun, 21 Sep 2025 14:59:12 +0200 Subject: [PATCH 1/2] Move version to independent VERSION file --- src/VERSION | 1 + src/cogs/debug.py | 2 +- src/const.py | 8 ++++++++ src/main.py | 5 ++++- src/utils/portal.py | 1 - 5 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 src/VERSION create mode 100644 src/const.py diff --git a/src/VERSION b/src/VERSION new file mode 100644 index 0000000..2411653 --- /dev/null +++ b/src/VERSION @@ -0,0 +1 @@ +0.5.2 \ No newline at end of file diff --git a/src/cogs/debug.py b/src/cogs/debug.py index 64f67d1..a67a0a6 100644 --- a/src/cogs/debug.py +++ b/src/cogs/debug.py @@ -21,7 +21,7 @@ class Debug_Command(Base_Cog): embed = discord.Embed(title="Debug Information") embed.add_field(name="Version", - value=f"`{portal.PROGRAM_VERSION}`", + value=ctx.client.VERSION, inline=True) embed.add_field(name="Uptime", value=f"{get_elapsed_time_big(datetime.now().timestamp() - portal.STARTUP_TIMESTAMP)}", diff --git a/src/const.py b/src/const.py new file mode 100644 index 0000000..1520a09 --- /dev/null +++ b/src/const.py @@ -0,0 +1,8 @@ +from pathlib import Path + +# Read VERSION file +with open(Path(__file__).resolve().parent / "VERSION") as f: + VERSION = f.read().strip() + + +__all__ = VERSION diff --git a/src/main.py b/src/main.py index 16f2d96..1a6d000 100644 --- a/src/main.py +++ b/src/main.py @@ -13,12 +13,13 @@ from utils.portal import Portal import asyncio from typing import Union from platforms.reddit import Reddit_Adapter +from const import VERSION print(" ____ ____ ___________ __________") print(" / __ \/ __ \/ ___/_ __/ / _/_ __/") print(" / /_/ / / / /\__ \ / /_____ / / / / ") print(" / ____/ /_/ /___/ // /_____// / / / ") -print(" /_/ \____//____//_/ /___/ /_/ ") +print(f" /_/ \____//____//_/ /___/ /_/ v{VERSION}") print(" Copyright (c) 2024-2025 Lars Winzer") print() print(" Source: https://github.com/official-Cromatin/Post-It") @@ -44,6 +45,8 @@ class MyBot(commands.Bot): self.__portal:Portal self.__first_on_ready = False + self.VERSION = VERSION + def set_portal(self, portal:Portal): self.__portal = portal diff --git a/src/utils/portal.py b/src/utils/portal.py index e67701f..9a778e4 100644 --- a/src/utils/portal.py +++ b/src/utils/portal.py @@ -4,7 +4,6 @@ from platforms.reddit import Reddit_Adapter @Singleton class Portal: - PROGRAM_VERSION = "0.3" bot_config:Advanced_ConfigParser = None platforms_config:Advanced_ConfigParser = None STARTUP_TIMESTAMP:float = None -- 2.52.0 From c4cb477637a294ed0c07578e8ddeec76348a58be Mon Sep 17 00:00:00 2001 From: official-Cromatin Date: Sun, 21 Sep 2025 15:23:14 +0200 Subject: [PATCH 2/2] Move portal attributes to Bot class --- src/cogs/debug.py | 8 +++----- src/cogs/post.py | 5 +---- src/main.py | 38 ++++++++++++++++++-------------------- src/utils/portal.py | 13 ------------- 4 files changed, 22 insertions(+), 42 deletions(-) delete mode 100644 src/utils/portal.py diff --git a/src/cogs/debug.py b/src/cogs/debug.py index a67a0a6..4e8922f 100644 --- a/src/cogs/debug.py +++ b/src/cogs/debug.py @@ -4,7 +4,6 @@ from discord.ext import commands from cogs.base_cog import Base_Cog import logging -from utils.portal import Portal from datetime import datetime from utils.datetime_tools import get_elapsed_time_big from utils.logger.decorator import log_command_execution @@ -17,17 +16,16 @@ class Debug_Command(Base_Cog): @app_commands.command(name = "debug", description = "Provides debug informations about the bot, useful for troubleshooting") @log_command_execution async def debug(self, ctx:discord.Interaction): - portal:Portal = Portal.instance() embed = discord.Embed(title="Debug Information") embed.add_field(name="Version", value=ctx.client.VERSION, inline=True) embed.add_field(name="Uptime", - value=f"{get_elapsed_time_big(datetime.now().timestamp() - portal.STARTUP_TIMESTAMP)}", + value=f"{get_elapsed_time_big(datetime.now().timestamp() - ctx.client.STARTUP_TIMESTAMP)}", inline=True) embed.add_field(name="Bot Owner", - value=f"<@{portal.bot_config['DISCORD']['OWNER_ID']}>", + value=f"<@{ctx.client.bot_config['DISCORD']['OWNER_ID']}>", inline=True) embed.add_field(name="Latency to Gateway", value=f"{round(self.__bot.latency * 1000, 2)}ms", @@ -38,7 +36,7 @@ class Debug_Command(Base_Cog): embed.add_field(name="Number of Guilds", value=f"{len(self.__bot.guilds)}", inline=True) - embed.add_field(name = "Number of executed commands", value=f"Total: {portal.no_executed_commands}\nSucceeded: {portal.no_succeeded_commands}\nFailed: {portal.no_failed_commands}") + embed.add_field(name = "Number of executed commands", value=f"Total: {ctx.client.no_executed_commands}\nSucceeded: {ctx.client.no_succeeded_commands}\nFailed: {ctx.client.no_failed_commands}") await ctx.response.send_message(embed=embed) diff --git a/src/cogs/post.py b/src/cogs/post.py index 1e53e72..2ead24e 100644 --- a/src/cogs/post.py +++ b/src/cogs/post.py @@ -6,7 +6,6 @@ from cogs.base_cog import Base_Cog import logging from urllib.parse import urlparse from asyncpraw.models import Submission -from utils.portal import Portal import aiohttp from PIL import Image from io import BytesIO @@ -35,14 +34,12 @@ class Post_Command(Base_Cog): async def post(self, ctx:discord.Interaction, url:str, custom_note:str = None, use_title:bool = True, quality:app_commands.Choice[int] = 95): try: domain_info = urlparse(url) - portal = Portal.instance() toplevel_domain = '.'.join(domain_info.netloc.split('.')[-2:]) begin_process = datetime.now().timestamp() match toplevel_domain: case "reddit.com": self._logger.debug(f"Recieved command by {ctx.user} ({ctx.user.id}) for reddit ({url})") - - subm:Submission = await portal.reddit_adapter.fetch(url) + subm:Submission = await ctx.client.reddit_adapter.fetch(url) image_urls = [] # Check if submission has a gallery if hasattr(subm, "media_metadata"): diff --git a/src/main.py b/src/main.py index 1a6d000..2f0084c 100644 --- a/src/main.py +++ b/src/main.py @@ -9,7 +9,6 @@ from pathlib import Path import re import sys import traceback -from utils.portal import Portal import asyncio from typing import Union from platforms.reddit import Reddit_Adapter @@ -42,13 +41,17 @@ intents.messages = True class MyBot(commands.Bot): def __init__(self): super().__init__(command_prefix=None, help_command=None, intents=intents) - self.__portal:Portal self.__first_on_ready = False self.VERSION = VERSION - - def set_portal(self, portal:Portal): - self.__portal = portal + self.STARTUP_TIMESTAMP: float = None + self.platforms_config: Advanced_ConfigParser = None + self.bot_config: Advanced_ConfigParser = None + self.reddit_adapter: Reddit_Adapter = None + + self.no_executed_commands:int = 0 + self.no_succeeded_commands:int = 0 + self.no_failed_commands:int = 0 async def setup_hook(self): # Register cogs to handle commands @@ -58,13 +61,13 @@ class MyBot(commands.Bot): async def on_app_command_completion(self, interaction: discord.Interaction, command: Union[discord.app_commands.Command, discord.app_commands.ContextMenu]): """Called when a `app_commands.Command` or `app_commands.ContextMenu` has successfully completed without error""" - self.__portal.no_succeeded_commands += 1 + self.no_succeeded_commands += 1 async def on_interaction(self, interaction: discord.Interaction): """Called when an interaction happened""" match interaction.type.name: case discord.InteractionType.application_command.name: - self.__portal.no_executed_commands += 1 + self.no_executed_commands += 1 case discord.InteractionType.ping.name: print("App got pinged by discord") case discord.InteractionType.autocomplete.name: @@ -85,13 +88,13 @@ class MyBot(commands.Bot): task_start = datetime.now().timestamp() startup_logger.debug("Loading platforms config ...") platforms_config = Advanced_ConfigParser(Path.joinpath(base_path, "config", "platforms.ini")) - portal.platforms_config = platforms_config + self.platforms_config = platforms_config startup_logger.info(f"Loaded platforms config after {get_elapsed_time_milliseconds(datetime.now().timestamp() - task_start)}") # Create platforms adapter task_start = datetime.now().timestamp() startup_logger.debug("Creating reddit adapter ...") - portal.reddit_adapter = Reddit_Adapter(platforms_config["REDDIT"]["CLIENT_ID"], platforms_config["REDDIT"]["CLIENT_SECRET"]) + self.reddit_adapter = Reddit_Adapter(platforms_config["REDDIT"]["CLIENT_ID"], platforms_config["REDDIT"]["CLIENT_SECRET"]) startup_logger.info(f"Created reddit adapter after {get_elapsed_time_milliseconds(datetime.now().timestamp() - task_start)}") await self.change_presence(status = discord.Status.online, activity = None) @@ -104,22 +107,17 @@ class MyBot(commands.Bot): app_logger.info(f"Successfully logged in (after {get_elapsed_time_smal(datetime.now().timestamp() - startup)}) as {self.user}") bot = MyBot() -bot_config = Advanced_ConfigParser(Path.joinpath(base_path, "config", "bot.ini")) -if re.match(r'[A-Za-z\d]{24}\.[\w-]{6}\.[\w-]{27}', bot_config["DISCORD"]["TOKEN"]): +bot.STARTUP_TIMESTAMP = startup +bot.bot_config = Advanced_ConfigParser(Path.joinpath(base_path, "config", "bot.ini")) +if re.match(r'[A-Za-z\d]{24}\.[\w-]{6}\.[\w-]{27}', bot.bot_config["DISCORD"]["TOKEN"]): app_logger.critical("Bot (config/bot.ini) configuration invalid, please set a valid token") quit(1) -elif bot_config.compare_to_template() not in ("equal", "config_minus"): +elif bot.bot_config.compare_to_template() not in ("equal", "config_minus"): app_logger.critical("Bot (config/bot.ini) configuration is missing some parts. Make sure it at least has all the same keys as the template") quit(1) else: app_logger.info("Bot configuration valid, continuing with startup") -# Execute some housekeeping actions -portal = Portal.instance() -portal.bot_config = bot_config -portal.STARTUP_TIMESTAMP = startup -bot.set_portal(portal) - # Setup handlers to handle states of command execution @bot.tree.error async def on_app_command_error(ctx:discord.Interaction, error): @@ -127,10 +125,10 @@ async def on_app_command_error(ctx:discord.Interaction, error): print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__) - portal.no_failed_commands += 1 + bot.no_failed_commands += 1 try: - bot.run(bot_config["DISCORD"]["TOKEN"], log_handler = None) + bot.run(bot.bot_config["DISCORD"]["TOKEN"], log_handler = None) except discord.errors.LoginFailure: app_logger.critical("Improper token has been passed. Aborting startup") quit(1) diff --git a/src/utils/portal.py b/src/utils/portal.py deleted file mode 100644 index 9a778e4..0000000 --- a/src/utils/portal.py +++ /dev/null @@ -1,13 +0,0 @@ -from utils.singleton import Singleton -from utils.adv_configparser import Advanced_ConfigParser -from platforms.reddit import Reddit_Adapter - -@Singleton -class Portal: - bot_config:Advanced_ConfigParser = None - platforms_config:Advanced_ConfigParser = None - STARTUP_TIMESTAMP:float = None - no_executed_commands:int = 0 - no_succeeded_commands:int = 0 - no_failed_commands:int = 0 - reddit_adapter: Reddit_Adapter = None \ No newline at end of file -- 2.52.0