Move portal attributes to Bot class

This commit is contained in:
2025-09-21 15:23:14 +02:00
parent 2f33d840f3
commit c4cb477637
4 changed files with 22 additions and 42 deletions
+18 -20
View File
@@ -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)